babylon.viewer.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. if(typeof exports === 'object' && typeof module === 'object') {
  4. module.exports = factory();
  5. } else if(typeof define === 'function' && define.amd) {
  6. define("babylonjs-viewer", amdDependencies, factory);
  7. } else if(typeof exports === 'object') {
  8. exports["babylonjs-viewer"] = factory();
  9. } else {
  10. root["BabylonViewer"] = factory();
  11. }
  12. })(this, function() {
  13. var BabylonViewer =
  14. /******/ (function(modules) { // webpackBootstrap
  15. /******/ // The module cache
  16. /******/ var installedModules = {};
  17. /******/
  18. /******/ // The require function
  19. /******/ function __webpack_require__(moduleId) {
  20. /******/
  21. /******/ // Check if module is in cache
  22. /******/ if(installedModules[moduleId]) {
  23. /******/ return installedModules[moduleId].exports;
  24. /******/ }
  25. /******/ // Create a new module (and put it into the cache)
  26. /******/ var module = installedModules[moduleId] = {
  27. /******/ i: moduleId,
  28. /******/ l: false,
  29. /******/ exports: {}
  30. /******/ };
  31. /******/
  32. /******/ // Execute the module function
  33. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  34. /******/
  35. /******/ // Flag the module as loaded
  36. /******/ module.l = true;
  37. /******/
  38. /******/ // Return the exports of the module
  39. /******/ return module.exports;
  40. /******/ }
  41. /******/
  42. /******/
  43. /******/ // expose the modules object (__webpack_modules__)
  44. /******/ __webpack_require__.m = modules;
  45. /******/
  46. /******/ // expose the module cache
  47. /******/ __webpack_require__.c = installedModules;
  48. /******/
  49. /******/ // define getter function for harmony exports
  50. /******/ __webpack_require__.d = function(exports, name, getter) {
  51. /******/ if(!__webpack_require__.o(exports, name)) {
  52. /******/ Object.defineProperty(exports, name, {
  53. /******/ configurable: false,
  54. /******/ enumerable: true,
  55. /******/ get: getter
  56. /******/ });
  57. /******/ }
  58. /******/ };
  59. /******/
  60. /******/ // getDefaultExport function for compatibility with non-harmony modules
  61. /******/ __webpack_require__.n = function(module) {
  62. /******/ var getter = module && module.__esModule ?
  63. /******/ function getDefault() { return module['default']; } :
  64. /******/ function getModuleExports() { return module; };
  65. /******/ __webpack_require__.d(getter, 'a', getter);
  66. /******/ return getter;
  67. /******/ };
  68. /******/
  69. /******/ // Object.prototype.hasOwnProperty.call
  70. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  71. /******/
  72. /******/ // __webpack_public_path__
  73. /******/ __webpack_require__.p = "";
  74. /******/
  75. /******/ // Load entry module and return exports
  76. /******/ return __webpack_require__(__webpack_require__.s = 24);
  77. /******/ })
  78. /************************************************************************/
  79. /******/ ([
  80. /* 0 */
  81. /***/ (function(module, exports, __webpack_require__) {
  82. /* WEBPACK VAR INJECTION */(function(global) {
  83. (function universalModuleDefinition(root, factory) {
  84. var amdDependencies = [];
  85. var CANNON = root.CANNON || this.CANNON;
  86. var OIMO = root.OIMO || this.OIMO;
  87. var earcut = root.earcut || this.earcut;
  88. if(true) {
  89. try { CANNON = CANNON || __webpack_require__(26); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(27); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(28); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = function (right) {
  1980. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1981. };
  1982. /**
  1983. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. this.x = x;
  2299. this.y = y;
  2300. }
  2301. /**
  2302. * Gets a string with the Vector2 coordinates
  2303. * @returns a string with the Vector2 coordinates
  2304. */
  2305. Vector2.prototype.toString = function () {
  2306. return "{X: " + this.x + " Y:" + this.y + "}";
  2307. };
  2308. /**
  2309. * Gets class name
  2310. * @returns the string "Vector2"
  2311. */
  2312. Vector2.prototype.getClassName = function () {
  2313. return "Vector2";
  2314. };
  2315. /**
  2316. * Gets current vector hash code
  2317. * @returns the Vector2 hash code as a number
  2318. */
  2319. Vector2.prototype.getHashCode = function () {
  2320. var hash = this.x || 0;
  2321. hash = (hash * 397) ^ (this.y || 0);
  2322. return hash;
  2323. };
  2324. // Operators
  2325. /**
  2326. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2327. * @param array defines the source array
  2328. * @param index defines the offset in source array
  2329. * @returns the current Vector2
  2330. */
  2331. Vector2.prototype.toArray = function (array, index) {
  2332. if (index === void 0) { index = 0; }
  2333. array[index] = this.x;
  2334. array[index + 1] = this.y;
  2335. return this;
  2336. };
  2337. /**
  2338. * Copy the current vector to an array
  2339. * @returns a new array with 2 elements: the Vector2 coordinates.
  2340. */
  2341. Vector2.prototype.asArray = function () {
  2342. var result = new Array();
  2343. this.toArray(result, 0);
  2344. return result;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2348. * @param source defines the source Vector2
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.copyFrom = function (source) {
  2352. this.x = source.x;
  2353. this.y = source.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Sets the Vector2 coordinates with the given floats
  2358. * @param x defines the first coordinate
  2359. * @param y defines the second coordinate
  2360. * @returns the current updated Vector2
  2361. */
  2362. Vector2.prototype.copyFromFloats = function (x, y) {
  2363. this.x = x;
  2364. this.y = y;
  2365. return this;
  2366. };
  2367. /**
  2368. * Sets the Vector2 coordinates with the given floats
  2369. * @param x defines the first coordinate
  2370. * @param y defines the second coordinate
  2371. * @returns the current updated Vector2
  2372. */
  2373. Vector2.prototype.set = function (x, y) {
  2374. return this.copyFromFloats(x, y);
  2375. };
  2376. /**
  2377. * Add another vector with the current one
  2378. * @param otherVector defines the other vector
  2379. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2380. */
  2381. Vector2.prototype.add = function (otherVector) {
  2382. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2383. };
  2384. /**
  2385. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2386. * @param otherVector defines the other vector
  2387. * @param result defines the target vector
  2388. * @returns the unmodified current Vector2
  2389. */
  2390. Vector2.prototype.addToRef = function (otherVector, result) {
  2391. result.x = this.x + otherVector.x;
  2392. result.y = this.y + otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns the current updated Vector2
  2399. */
  2400. Vector2.prototype.addInPlace = function (otherVector) {
  2401. this.x += otherVector.x;
  2402. this.y += otherVector.y;
  2403. return this;
  2404. };
  2405. /**
  2406. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2407. * @param otherVector defines the other vector
  2408. * @returns a new Vector2
  2409. */
  2410. Vector2.prototype.addVector3 = function (otherVector) {
  2411. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2412. };
  2413. /**
  2414. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2415. * @param otherVector defines the other vector
  2416. * @returns a new Vector2
  2417. */
  2418. Vector2.prototype.subtract = function (otherVector) {
  2419. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2420. };
  2421. /**
  2422. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2423. * @param otherVector defines the other vector
  2424. * @param result defines the target vector
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2428. result.x = this.x - otherVector.x;
  2429. result.y = this.y - otherVector.y;
  2430. return this;
  2431. };
  2432. /**
  2433. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2434. * @param otherVector defines the other vector
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.subtractInPlace = function (otherVector) {
  2438. this.x -= otherVector.x;
  2439. this.y -= otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Multiplies in place the current Vector2 coordinates by the given ones
  2444. * @param otherVector defines the other vector
  2445. * @returns the current updated Vector2
  2446. */
  2447. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2448. this.x *= otherVector.x;
  2449. this.y *= otherVector.y;
  2450. return this;
  2451. };
  2452. /**
  2453. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2454. * @param otherVector defines the other vector
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.multiply = function (otherVector) {
  2458. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2459. };
  2460. /**
  2461. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2462. * @param otherVector defines the other vector
  2463. * @param result defines the target vector
  2464. * @returns the unmodified current Vector2
  2465. */
  2466. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2467. result.x = this.x * otherVector.x;
  2468. result.y = this.y * otherVector.y;
  2469. return this;
  2470. };
  2471. /**
  2472. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2473. * @param x defines the first coordinate
  2474. * @param y defines the second coordinate
  2475. * @returns a new Vector2
  2476. */
  2477. Vector2.prototype.multiplyByFloats = function (x, y) {
  2478. return new Vector2(this.x * x, this.y * y);
  2479. };
  2480. /**
  2481. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2482. * @param otherVector defines the other vector
  2483. * @returns a new Vector2
  2484. */
  2485. Vector2.prototype.divide = function (otherVector) {
  2486. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2487. };
  2488. /**
  2489. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2490. * @param otherVector defines the other vector
  2491. * @param result defines the target vector
  2492. * @returns the unmodified current Vector2
  2493. */
  2494. Vector2.prototype.divideToRef = function (otherVector, result) {
  2495. result.x = this.x / otherVector.x;
  2496. result.y = this.y / otherVector.y;
  2497. return this;
  2498. };
  2499. /**
  2500. * Divides the current Vector3 coordinates by the given ones
  2501. * @param otherVector defines the other vector
  2502. * @returns the current updated Vector2
  2503. */
  2504. Vector2.prototype.divideInPlace = function (otherVector) {
  2505. return this.divideToRef(otherVector, this);
  2506. };
  2507. /**
  2508. * Gets a new Vector2 with current Vector2 negated coordinates
  2509. * @returns a new Vector2
  2510. */
  2511. Vector2.prototype.negate = function () {
  2512. return new Vector2(-this.x, -this.y);
  2513. };
  2514. /**
  2515. * Multiply the Vector2 coordinates by scale
  2516. * @param scale defines the scaling factor
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.scaleInPlace = function (scale) {
  2520. this.x *= scale;
  2521. this.y *= scale;
  2522. return this;
  2523. };
  2524. /**
  2525. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2526. * @param scale defines the scaling factor
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.prototype.scale = function (scale) {
  2530. var result = new Vector2(0, 0);
  2531. this.scaleToRef(scale, result);
  2532. return result;
  2533. };
  2534. /**
  2535. * Scale the current Vector2 values by a factor to a given Vector2
  2536. * @param scale defines the scale factor
  2537. * @param result defines the Vector2 object where to store the result
  2538. * @returns the unmodified current Vector2
  2539. */
  2540. Vector2.prototype.scaleToRef = function (scale, result) {
  2541. result.x = this.x * scale;
  2542. result.y = this.y * scale;
  2543. return this;
  2544. };
  2545. /**
  2546. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2547. * @param scale defines the scale factor
  2548. * @param result defines the Vector2 object where to store the result
  2549. * @returns the unmodified current Vector2
  2550. */
  2551. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2552. result.x += this.x * scale;
  2553. result.y += this.y * scale;
  2554. return this;
  2555. };
  2556. /**
  2557. * Gets a boolean if two vectors are equals
  2558. * @param otherVector defines the other vector
  2559. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2560. */
  2561. Vector2.prototype.equals = function (otherVector) {
  2562. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2563. };
  2564. /**
  2565. * Gets a boolean if two vectors are equals (using an epsilon value)
  2566. * @param otherVector defines the other vector
  2567. * @param epsilon defines the minimal distance to consider equality
  2568. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2569. */
  2570. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2571. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2572. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2573. };
  2574. // Properties
  2575. /**
  2576. * Gets the length of the vector
  2577. * @returns the vector length (float)
  2578. */
  2579. Vector2.prototype.length = function () {
  2580. return Math.sqrt(this.x * this.x + this.y * this.y);
  2581. };
  2582. /**
  2583. * Gets the vector squared length
  2584. * @returns the vector squared length (float)
  2585. */
  2586. Vector2.prototype.lengthSquared = function () {
  2587. return (this.x * this.x + this.y * this.y);
  2588. };
  2589. // Methods
  2590. /**
  2591. * Normalize the vector
  2592. * @returns the current updated Vector2
  2593. */
  2594. Vector2.prototype.normalize = function () {
  2595. var len = this.length();
  2596. if (len === 0)
  2597. return this;
  2598. var num = 1.0 / len;
  2599. this.x *= num;
  2600. this.y *= num;
  2601. return this;
  2602. };
  2603. /**
  2604. * Gets a new Vector2 copied from the Vector2
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.prototype.clone = function () {
  2608. return new Vector2(this.x, this.y);
  2609. };
  2610. // Statics
  2611. /**
  2612. * Gets a new Vector2(0, 0)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.Zero = function () {
  2616. return new Vector2(0, 0);
  2617. };
  2618. /**
  2619. * Gets a new Vector2(1, 1)
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.One = function () {
  2623. return new Vector2(1, 1);
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set from the given index element of the given array
  2627. * @param array defines the data source
  2628. * @param offset defines the offset in the data source
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.FromArray = function (array, offset) {
  2632. if (offset === void 0) { offset = 0; }
  2633. return new Vector2(array[offset], array[offset + 1]);
  2634. };
  2635. /**
  2636. * Sets "result" from the given index element of the given array
  2637. * @param array defines the data source
  2638. * @param offset defines the offset in the data source
  2639. * @param result defines the target vector
  2640. */
  2641. Vector2.FromArrayToRef = function (array, offset, result) {
  2642. result.x = array[offset];
  2643. result.y = array[offset + 1];
  2644. };
  2645. /**
  2646. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2647. * @param value1 defines 1st point of control
  2648. * @param value2 defines 2nd point of control
  2649. * @param value3 defines 3rd point of control
  2650. * @param value4 defines 4th point of control
  2651. * @param amount defines the interpolation factor
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2655. var squared = amount * amount;
  2656. var cubed = amount * squared;
  2657. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2658. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2659. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2660. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2661. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2662. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2667. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2668. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2669. * @param value defines the value to clamp
  2670. * @param min defines the lower limit
  2671. * @param max defines the upper limit
  2672. * @returns a new Vector2
  2673. */
  2674. Vector2.Clamp = function (value, min, max) {
  2675. var x = value.x;
  2676. x = (x > max.x) ? max.x : x;
  2677. x = (x < min.x) ? min.x : x;
  2678. var y = value.y;
  2679. y = (y > max.y) ? max.y : y;
  2680. y = (y < min.y) ? min.y : y;
  2681. return new Vector2(x, y);
  2682. };
  2683. /**
  2684. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2685. * @param value1 defines the 1st control point
  2686. * @param tangent1 defines the outgoing tangent
  2687. * @param value2 defines the 2nd control point
  2688. * @param tangent2 defines the incoming tangent
  2689. * @param amount defines the interpolation factor
  2690. * @returns a new Vector2
  2691. */
  2692. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2693. var squared = amount * amount;
  2694. var cubed = amount * squared;
  2695. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2696. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2697. var part3 = (cubed - (2.0 * squared)) + amount;
  2698. var part4 = cubed - squared;
  2699. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2700. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2701. return new Vector2(x, y);
  2702. };
  2703. /**
  2704. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2705. * @param start defines the start vector
  2706. * @param end defines the end vector
  2707. * @param amount defines the interpolation factor
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Lerp = function (start, end, amount) {
  2711. var x = start.x + ((end.x - start.x) * amount);
  2712. var y = start.y + ((end.y - start.y) * amount);
  2713. return new Vector2(x, y);
  2714. };
  2715. /**
  2716. * Gets the dot product of the vector "left" and the vector "right"
  2717. * @param left defines first vector
  2718. * @param right defines second vector
  2719. * @returns the dot product (float)
  2720. */
  2721. Vector2.Dot = function (left, right) {
  2722. return left.x * right.x + left.y * right.y;
  2723. };
  2724. /**
  2725. * Returns a new Vector2 equal to the normalized given vector
  2726. * @param vector defines the vector to normalize
  2727. * @returns a new Vector2
  2728. */
  2729. Vector2.Normalize = function (vector) {
  2730. var newVector = vector.clone();
  2731. newVector.normalize();
  2732. return newVector;
  2733. };
  2734. /**
  2735. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2736. * @param left defines 1st vector
  2737. * @param right defines 2nd vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Minimize = function (left, right) {
  2741. var x = (left.x < right.x) ? left.x : right.x;
  2742. var y = (left.y < right.y) ? left.y : right.y;
  2743. return new Vector2(x, y);
  2744. };
  2745. /**
  2746. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2747. * @param left defines 1st vector
  2748. * @param right defines 2nd vector
  2749. * @returns a new Vector2
  2750. */
  2751. Vector2.Maximize = function (left, right) {
  2752. var x = (left.x > right.x) ? left.x : right.x;
  2753. var y = (left.y > right.y) ? left.y : right.y;
  2754. return new Vector2(x, y);
  2755. };
  2756. /**
  2757. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2758. * @param vector defines the vector to transform
  2759. * @param transformation defines the matrix to apply
  2760. * @returns a new Vector2
  2761. */
  2762. Vector2.Transform = function (vector, transformation) {
  2763. var r = Vector2.Zero();
  2764. Vector2.TransformToRef(vector, transformation, r);
  2765. return r;
  2766. };
  2767. /**
  2768. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2769. * @param vector defines the vector to transform
  2770. * @param transformation defines the matrix to apply
  2771. * @param result defines the target vector
  2772. */
  2773. Vector2.TransformToRef = function (vector, transformation, result) {
  2774. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2775. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2776. result.x = x;
  2777. result.y = y;
  2778. };
  2779. /**
  2780. * Determines if a given vector is included in a triangle
  2781. * @param p defines the vector to test
  2782. * @param p0 defines 1st triangle point
  2783. * @param p1 defines 2nd triangle point
  2784. * @param p2 defines 3rd triangle point
  2785. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2786. */
  2787. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2788. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2789. var sign = a < 0 ? -1 : 1;
  2790. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2791. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2792. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2793. };
  2794. /**
  2795. * Gets the distance between the vectors "value1" and "value2"
  2796. * @param value1 defines first vector
  2797. * @param value2 defines second vector
  2798. * @returns the distance between vectors
  2799. */
  2800. Vector2.Distance = function (value1, value2) {
  2801. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2802. };
  2803. /**
  2804. * Returns the squared distance between the vectors "value1" and "value2"
  2805. * @param value1 defines first vector
  2806. * @param value2 defines second vector
  2807. * @returns the squared distance between vectors
  2808. */
  2809. Vector2.DistanceSquared = function (value1, value2) {
  2810. var x = value1.x - value2.x;
  2811. var y = value1.y - value2.y;
  2812. return (x * x) + (y * y);
  2813. };
  2814. /**
  2815. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2816. * @param value1 defines first vector
  2817. * @param value2 defines second vector
  2818. * @returns a new Vector2
  2819. */
  2820. Vector2.Center = function (value1, value2) {
  2821. var center = value1.add(value2);
  2822. center.scaleInPlace(0.5);
  2823. return center;
  2824. };
  2825. /**
  2826. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2827. * @param p defines the middle point
  2828. * @param segA defines one point of the segment
  2829. * @param segB defines the other point of the segment
  2830. * @returns the shortest distance
  2831. */
  2832. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2833. var l2 = Vector2.DistanceSquared(segA, segB);
  2834. if (l2 === 0.0) {
  2835. return Vector2.Distance(p, segA);
  2836. }
  2837. var v = segB.subtract(segA);
  2838. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2839. var proj = segA.add(v.multiplyByFloats(t, t));
  2840. return Vector2.Distance(p, proj);
  2841. };
  2842. return Vector2;
  2843. }());
  2844. BABYLON.Vector2 = Vector2;
  2845. /**
  2846. * Classed used to store (x,y,z) vector representation
  2847. * A Vector3 is the main object used in 3D geometry
  2848. * It can represent etiher the coordinates of a point the space, either a direction
  2849. * Reminder: Babylon.js uses a left handed forward facing system
  2850. */
  2851. var Vector3 = /** @class */ (function () {
  2852. /**
  2853. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2854. * @param x defines the first coordinates (on X axis)
  2855. * @param y defines the second coordinates (on Y axis)
  2856. * @param z defines the third coordinates (on Z axis)
  2857. */
  2858. function Vector3(
  2859. /**
  2860. * Defines the first coordinates (on X axis)
  2861. */
  2862. x,
  2863. /**
  2864. * Defines the second coordinates (on Y axis)
  2865. */
  2866. y,
  2867. /**
  2868. * Defines the third coordinates (on Z axis)
  2869. */
  2870. z) {
  2871. this.x = x;
  2872. this.y = y;
  2873. this.z = z;
  2874. }
  2875. /**
  2876. * Creates a string representation of the Vector3
  2877. * @returns a string with the Vector3 coordinates.
  2878. */
  2879. Vector3.prototype.toString = function () {
  2880. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2881. };
  2882. /**
  2883. * Gets the class name
  2884. * @returns the string "Vector3"
  2885. */
  2886. Vector3.prototype.getClassName = function () {
  2887. return "Vector3";
  2888. };
  2889. /**
  2890. * Creates the Vector3 hash code
  2891. * @returns a number which tends to be unique between Vector3 instances
  2892. */
  2893. Vector3.prototype.getHashCode = function () {
  2894. var hash = this.x || 0;
  2895. hash = (hash * 397) ^ (this.y || 0);
  2896. hash = (hash * 397) ^ (this.z || 0);
  2897. return hash;
  2898. };
  2899. // Operators
  2900. /**
  2901. * Creates an array containing three elements : the coordinates of the Vector3
  2902. * @returns a new array of numbers
  2903. */
  2904. Vector3.prototype.asArray = function () {
  2905. var result = [];
  2906. this.toArray(result, 0);
  2907. return result;
  2908. };
  2909. /**
  2910. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2911. * @param array defines the destination array
  2912. * @param index defines the offset in the destination array
  2913. * @returns the current Vector3
  2914. */
  2915. Vector3.prototype.toArray = function (array, index) {
  2916. if (index === void 0) { index = 0; }
  2917. array[index] = this.x;
  2918. array[index + 1] = this.y;
  2919. array[index + 2] = this.z;
  2920. return this;
  2921. };
  2922. /**
  2923. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2924. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2925. */
  2926. Vector3.prototype.toQuaternion = function () {
  2927. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2928. };
  2929. /**
  2930. * Adds the given vector to the current Vector3
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.addInPlace = function (otherVector) {
  2935. this.x += otherVector.x;
  2936. this.y += otherVector.y;
  2937. this.z += otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2942. * @param otherVector defines the second operand
  2943. * @returns the resulting Vector3
  2944. */
  2945. Vector3.prototype.add = function (otherVector) {
  2946. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2947. };
  2948. /**
  2949. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2950. * @param otherVector defines the second operand
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the current Vector3
  2953. */
  2954. Vector3.prototype.addToRef = function (otherVector, result) {
  2955. result.x = this.x + otherVector.x;
  2956. result.y = this.y + otherVector.y;
  2957. result.z = this.z + otherVector.z;
  2958. return this;
  2959. };
  2960. /**
  2961. * Subtract the given vector from the current Vector3
  2962. * @param otherVector defines the second operand
  2963. * @returns the current updated Vector3
  2964. */
  2965. Vector3.prototype.subtractInPlace = function (otherVector) {
  2966. this.x -= otherVector.x;
  2967. this.y -= otherVector.y;
  2968. this.z -= otherVector.z;
  2969. return this;
  2970. };
  2971. /**
  2972. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2973. * @param otherVector defines the second operand
  2974. * @returns the resulting Vector3
  2975. */
  2976. Vector3.prototype.subtract = function (otherVector) {
  2977. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2978. };
  2979. /**
  2980. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2981. * @param otherVector defines the second operand
  2982. * @param result defines the Vector3 object where to store the result
  2983. * @returns the current Vector3
  2984. */
  2985. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2986. result.x = this.x - otherVector.x;
  2987. result.y = this.y - otherVector.y;
  2988. result.z = this.z - otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2993. * @param x defines the x coordinate of the operand
  2994. * @param y defines the y coordinate of the operand
  2995. * @param z defines the z coordinate of the operand
  2996. * @returns the resulting Vector3
  2997. */
  2998. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2999. return new Vector3(this.x - x, this.y - y, this.z - z);
  3000. };
  3001. /**
  3002. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3010. result.x = this.x - x;
  3011. result.y = this.y - y;
  3012. result.z = this.z - z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3017. * @returns a new Vector3
  3018. */
  3019. Vector3.prototype.negate = function () {
  3020. return new Vector3(-this.x, -this.y, -this.z);
  3021. };
  3022. /**
  3023. * Multiplies the Vector3 coordinates by the float "scale"
  3024. * @param scale defines the multiplier factor
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.scaleInPlace = function (scale) {
  3028. this.x *= scale;
  3029. this.y *= scale;
  3030. this.z *= scale;
  3031. return this;
  3032. };
  3033. /**
  3034. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3035. * @param scale defines the multiplier factor
  3036. * @returns a new Vector3
  3037. */
  3038. Vector3.prototype.scale = function (scale) {
  3039. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3040. };
  3041. /**
  3042. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3043. * @param scale defines the multiplier factor
  3044. * @param result defines the Vector3 object where to store the result
  3045. * @returns the current Vector3
  3046. */
  3047. Vector3.prototype.scaleToRef = function (scale, result) {
  3048. result.x = this.x * scale;
  3049. result.y = this.y * scale;
  3050. result.z = this.z * scale;
  3051. return this;
  3052. };
  3053. /**
  3054. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3055. * @param scale defines the scale factor
  3056. * @param result defines the Vector3 object where to store the result
  3057. * @returns the unmodified current Vector3
  3058. */
  3059. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3060. result.x += this.x * scale;
  3061. result.y += this.y * scale;
  3062. result.z += this.z * scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3067. * @param otherVector defines the second operand
  3068. * @returns true if both vectors are equals
  3069. */
  3070. Vector3.prototype.equals = function (otherVector) {
  3071. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3072. };
  3073. /**
  3074. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3075. * @param otherVector defines the second operand
  3076. * @param epsilon defines the minimal distance to define values as equals
  3077. * @returns true if both vectors are distant less than epsilon
  3078. */
  3079. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3080. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3081. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3082. };
  3083. /**
  3084. * Returns true if the current Vector3 coordinates equals the given floats
  3085. * @param x defines the x coordinate of the operand
  3086. * @param y defines the y coordinate of the operand
  3087. * @param z defines the z coordinate of the operand
  3088. * @returns true if both vectors are equals
  3089. */
  3090. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3091. return this.x === x && this.y === y && this.z === z;
  3092. };
  3093. /**
  3094. * Multiplies the current Vector3 coordinates by the given ones
  3095. * @param otherVector defines the second operand
  3096. * @returns the current updated Vector3
  3097. */
  3098. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3099. this.x *= otherVector.x;
  3100. this.y *= otherVector.y;
  3101. this.z *= otherVector.z;
  3102. return this;
  3103. };
  3104. /**
  3105. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3106. * @param otherVector defines the second operand
  3107. * @returns the new Vector3
  3108. */
  3109. Vector3.prototype.multiply = function (otherVector) {
  3110. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3111. };
  3112. /**
  3113. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3114. * @param otherVector defines the second operand
  3115. * @param result defines the Vector3 object where to store the result
  3116. * @returns the current Vector3
  3117. */
  3118. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3119. result.x = this.x * otherVector.x;
  3120. result.y = this.y * otherVector.y;
  3121. result.z = this.z * otherVector.z;
  3122. return this;
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3126. * @param x defines the x coordinate of the operand
  3127. * @param y defines the y coordinate of the operand
  3128. * @param z defines the z coordinate of the operand
  3129. * @returns the new Vector3
  3130. */
  3131. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3132. return new Vector3(this.x * x, this.y * y, this.z * z);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3136. * @param otherVector defines the second operand
  3137. * @returns the new Vector3
  3138. */
  3139. Vector3.prototype.divide = function (otherVector) {
  3140. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3141. };
  3142. /**
  3143. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3144. * @param otherVector defines the second operand
  3145. * @param result defines the Vector3 object where to store the result
  3146. * @returns the current Vector3
  3147. */
  3148. Vector3.prototype.divideToRef = function (otherVector, result) {
  3149. result.x = this.x / otherVector.x;
  3150. result.y = this.y / otherVector.y;
  3151. result.z = this.z / otherVector.z;
  3152. return this;
  3153. };
  3154. /**
  3155. * Divides the current Vector3 coordinates by the given ones.
  3156. * @param otherVector defines the second operand
  3157. * @returns the current updated Vector3
  3158. */
  3159. Vector3.prototype.divideInPlace = function (otherVector) {
  3160. return this.divideToRef(otherVector, this);
  3161. };
  3162. /**
  3163. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3164. * @param other defines the second operand
  3165. * @returns the current updated Vector3
  3166. */
  3167. Vector3.prototype.minimizeInPlace = function (other) {
  3168. if (other.x < this.x)
  3169. this.x = other.x;
  3170. if (other.y < this.y)
  3171. this.y = other.y;
  3172. if (other.z < this.z)
  3173. this.z = other.z;
  3174. return this;
  3175. };
  3176. /**
  3177. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3178. * @param other defines the second operand
  3179. * @returns the current updated Vector3
  3180. */
  3181. Vector3.prototype.maximizeInPlace = function (other) {
  3182. if (other.x > this.x)
  3183. this.x = other.x;
  3184. if (other.y > this.y)
  3185. this.y = other.y;
  3186. if (other.z > this.z)
  3187. this.z = other.z;
  3188. return this;
  3189. };
  3190. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3191. /**
  3192. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3193. */
  3194. get: function () {
  3195. var absX = Math.abs(this.x);
  3196. var absY = Math.abs(this.y);
  3197. if (absX !== absY) {
  3198. return true;
  3199. }
  3200. var absZ = Math.abs(this.z);
  3201. if (absX !== absZ) {
  3202. return true;
  3203. }
  3204. if (absY !== absZ) {
  3205. return true;
  3206. }
  3207. return false;
  3208. },
  3209. enumerable: true,
  3210. configurable: true
  3211. });
  3212. // Properties
  3213. /**
  3214. * Gets the length of the Vector3
  3215. * @returns the length of the Vecto3
  3216. */
  3217. Vector3.prototype.length = function () {
  3218. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3219. };
  3220. /**
  3221. * Gets the squared length of the Vector3
  3222. * @returns squared length of the Vector3
  3223. */
  3224. Vector3.prototype.lengthSquared = function () {
  3225. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3226. };
  3227. /**
  3228. * Normalize the current Vector3.
  3229. * Please note that this is an in place operation.
  3230. * @returns the current updated Vector3
  3231. */
  3232. Vector3.prototype.normalize = function () {
  3233. var len = this.length();
  3234. if (len === 0 || len === 1.0)
  3235. return this;
  3236. var num = 1.0 / len;
  3237. this.x *= num;
  3238. this.y *= num;
  3239. this.z *= num;
  3240. return this;
  3241. };
  3242. /**
  3243. * Normalize the current Vector3 to a new vector
  3244. * @returns the new Vector3
  3245. */
  3246. Vector3.prototype.normalizeToNew = function () {
  3247. var normalized = new Vector3(0, 0, 0);
  3248. this.normalizeToRef(normalized);
  3249. return normalized;
  3250. };
  3251. /**
  3252. * Normalize the current Vector3 to the reference
  3253. * @param reference define the Vector3 to update
  3254. * @returns the updated Vector3
  3255. */
  3256. Vector3.prototype.normalizeToRef = function (reference) {
  3257. var len = this.length();
  3258. if (len === 0 || len === 1.0) {
  3259. reference.set(this.x, this.y, this.z);
  3260. return reference;
  3261. }
  3262. var scale = 1.0 / len;
  3263. this.scaleToRef(scale, reference);
  3264. return reference;
  3265. };
  3266. /**
  3267. * Creates a new Vector3 copied from the current Vector3
  3268. * @returns the new Vector3
  3269. */
  3270. Vector3.prototype.clone = function () {
  3271. return new Vector3(this.x, this.y, this.z);
  3272. };
  3273. /**
  3274. * Copies the given vector coordinates to the current Vector3 ones
  3275. * @param source defines the source Vector3
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.copyFrom = function (source) {
  3279. this.x = source.x;
  3280. this.y = source.y;
  3281. this.z = source.z;
  3282. return this;
  3283. };
  3284. /**
  3285. * Copies the given floats to the current Vector3 coordinates
  3286. * @param x defines the x coordinate of the operand
  3287. * @param y defines the y coordinate of the operand
  3288. * @param z defines the z coordinate of the operand
  3289. * @returns the current updated Vector3
  3290. */
  3291. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3292. this.x = x;
  3293. this.y = y;
  3294. this.z = z;
  3295. return this;
  3296. };
  3297. /**
  3298. * Copies the given floats to the current Vector3 coordinates
  3299. * @param x defines the x coordinate of the operand
  3300. * @param y defines the y coordinate of the operand
  3301. * @param z defines the z coordinate of the operand
  3302. * @returns the current updated Vector3
  3303. */
  3304. Vector3.prototype.set = function (x, y, z) {
  3305. return this.copyFromFloats(x, y, z);
  3306. };
  3307. // Statics
  3308. /**
  3309. * Get the clip factor between two vectors
  3310. * @param vector0 defines the first operand
  3311. * @param vector1 defines the second operand
  3312. * @param axis defines the axis to use
  3313. * @param size defines the size along the axis
  3314. * @returns the clip factor
  3315. */
  3316. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3317. var d0 = Vector3.Dot(vector0, axis) - size;
  3318. var d1 = Vector3.Dot(vector1, axis) - size;
  3319. var s = d0 / (d0 - d1);
  3320. return s;
  3321. };
  3322. /**
  3323. * Get angle between two vectors
  3324. * @param vector0 angle between vector0 and vector1
  3325. * @param vector1 angle between vector0 and vector1
  3326. * @param normal direction of the normal
  3327. * @return the angle between vector0 and vector1
  3328. */
  3329. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3330. var v0 = vector0.clone().normalize();
  3331. var v1 = vector1.clone().normalize();
  3332. var dot = Vector3.Dot(v0, v1);
  3333. var n = Vector3.Cross(v0, v1);
  3334. if (Vector3.Dot(n, normal) > 0) {
  3335. return Math.acos(dot);
  3336. }
  3337. return -Math.acos(dot);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set from the index "offset" of the given array
  3341. * @param array defines the source array
  3342. * @param offset defines the offset in the source array
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.FromArray = function (array, offset) {
  3346. if (!offset) {
  3347. offset = 0;
  3348. }
  3349. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3353. * This function is deprecated. Use FromArray instead
  3354. * @param array defines the source array
  3355. * @param offset defines the offset in the source array
  3356. * @returns the new Vector3
  3357. */
  3358. Vector3.FromFloatArray = function (array, offset) {
  3359. return Vector3.FromArray(array, offset);
  3360. };
  3361. /**
  3362. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3363. * @param array defines the source array
  3364. * @param offset defines the offset in the source array
  3365. * @param result defines the Vector3 where to store the result
  3366. */
  3367. Vector3.FromArrayToRef = function (array, offset, result) {
  3368. result.x = array[offset];
  3369. result.y = array[offset + 1];
  3370. result.z = array[offset + 2];
  3371. };
  3372. /**
  3373. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3374. * This function is deprecated. Use FromArrayToRef instead.
  3375. * @param array defines the source array
  3376. * @param offset defines the offset in the source array
  3377. * @param result defines the Vector3 where to store the result
  3378. */
  3379. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3380. return Vector3.FromArrayToRef(array, offset, result);
  3381. };
  3382. /**
  3383. * Sets the given vector "result" with the given floats.
  3384. * @param x defines the x coordinate of the source
  3385. * @param y defines the y coordinate of the source
  3386. * @param z defines the z coordinate of the source
  3387. * @param result defines the Vector3 where to store the result
  3388. */
  3389. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3390. result.x = x;
  3391. result.y = y;
  3392. result.z = z;
  3393. };
  3394. /**
  3395. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3396. * @returns a new empty Vector3
  3397. */
  3398. Vector3.Zero = function () {
  3399. return new Vector3(0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3403. * @returns a new unit Vector3
  3404. */
  3405. Vector3.One = function () {
  3406. return new Vector3(1.0, 1.0, 1.0);
  3407. };
  3408. /**
  3409. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3410. * @returns a new up Vector3
  3411. */
  3412. Vector3.Up = function () {
  3413. return new Vector3(0.0, 1.0, 0.0);
  3414. };
  3415. /**
  3416. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3417. * @returns a new forward Vector3
  3418. */
  3419. Vector3.Forward = function () {
  3420. return new Vector3(0.0, 0.0, 1.0);
  3421. };
  3422. /**
  3423. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3424. * @returns a new right Vector3
  3425. */
  3426. Vector3.Right = function () {
  3427. return new Vector3(1.0, 0.0, 0.0);
  3428. };
  3429. /**
  3430. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3431. * @returns a new left Vector3
  3432. */
  3433. Vector3.Left = function () {
  3434. return new Vector3(-1.0, 0.0, 0.0);
  3435. };
  3436. /**
  3437. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3438. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3439. * @param vector defines the Vector3 to transform
  3440. * @param transformation defines the transformation matrix
  3441. * @returns the transformed Vector3
  3442. */
  3443. Vector3.TransformCoordinates = function (vector, transformation) {
  3444. var result = Vector3.Zero();
  3445. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3450. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @param result defines the Vector3 where to store the result
  3454. */
  3455. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3456. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3457. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3458. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3459. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3460. result.x = x / w;
  3461. result.y = y / w;
  3462. result.z = z / w;
  3463. };
  3464. /**
  3465. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3466. * This method computes tranformed coordinates only, not transformed direction vectors
  3467. * @param x define the x coordinate of the source vector
  3468. * @param y define the y coordinate of the source vector
  3469. * @param z define the z coordinate of the source vector
  3470. * @param transformation defines the transformation matrix
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3474. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3475. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3476. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3477. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3478. result.x = rx / rw;
  3479. result.y = ry / rw;
  3480. result.z = rz / rw;
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3484. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3485. * @param vector defines the Vector3 to transform
  3486. * @param transformation defines the transformation matrix
  3487. * @returns the new Vector3
  3488. */
  3489. Vector3.TransformNormal = function (vector, transformation) {
  3490. var result = Vector3.Zero();
  3491. Vector3.TransformNormalToRef(vector, transformation, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param vector defines the Vector3 to transform
  3498. * @param transformation defines the transformation matrix
  3499. * @param result defines the Vector3 where to store the result
  3500. */
  3501. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3502. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3503. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3504. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3505. result.x = x;
  3506. result.y = y;
  3507. result.z = z;
  3508. };
  3509. /**
  3510. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3511. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3512. * @param x define the x coordinate of the source vector
  3513. * @param y define the y coordinate of the source vector
  3514. * @param z define the z coordinate of the source vector
  3515. * @param transformation defines the transformation matrix
  3516. * @param result defines the Vector3 where to store the result
  3517. */
  3518. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3519. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3520. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3521. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3522. };
  3523. /**
  3524. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3525. * @param value1 defines the first control point
  3526. * @param value2 defines the second control point
  3527. * @param value3 defines the third control point
  3528. * @param value4 defines the fourth control point
  3529. * @param amount defines the amount on the spline to use
  3530. * @returns the new Vector3
  3531. */
  3532. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3533. var squared = amount * amount;
  3534. var cubed = amount * squared;
  3535. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3536. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3537. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3538. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3539. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3540. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3541. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3542. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3543. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3544. return new Vector3(x, y, z);
  3545. };
  3546. /**
  3547. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3548. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3549. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3550. * @param value defines the current value
  3551. * @param min defines the lower range value
  3552. * @param max defines the upper range value
  3553. * @returns the new Vector3
  3554. */
  3555. Vector3.Clamp = function (value, min, max) {
  3556. var x = value.x;
  3557. x = (x > max.x) ? max.x : x;
  3558. x = (x < min.x) ? min.x : x;
  3559. var y = value.y;
  3560. y = (y > max.y) ? max.y : y;
  3561. y = (y < min.y) ? min.y : y;
  3562. var z = value.z;
  3563. z = (z > max.z) ? max.z : z;
  3564. z = (z < min.z) ? min.z : z;
  3565. return new Vector3(x, y, z);
  3566. };
  3567. /**
  3568. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3569. * @param value1 defines the first control point
  3570. * @param tangent1 defines the first tangent vector
  3571. * @param value2 defines the second control point
  3572. * @param tangent2 defines the second tangent vector
  3573. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3577. var squared = amount * amount;
  3578. var cubed = amount * squared;
  3579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3581. var part3 = (cubed - (2.0 * squared)) + amount;
  3582. var part4 = cubed - squared;
  3583. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3584. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3585. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3586. return new Vector3(x, y, z);
  3587. };
  3588. /**
  3589. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3590. * @param start defines the start value
  3591. * @param end defines the end value
  3592. * @param amount max defines amount between both (between 0 and 1)
  3593. * @returns the new Vector3
  3594. */
  3595. Vector3.Lerp = function (start, end, amount) {
  3596. var result = new Vector3(0, 0, 0);
  3597. Vector3.LerpToRef(start, end, amount, result);
  3598. return result;
  3599. };
  3600. /**
  3601. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3602. * @param start defines the start value
  3603. * @param end defines the end value
  3604. * @param amount max defines amount between both (between 0 and 1)
  3605. * @param result defines the Vector3 where to store the result
  3606. */
  3607. Vector3.LerpToRef = function (start, end, amount, result) {
  3608. result.x = start.x + ((end.x - start.x) * amount);
  3609. result.y = start.y + ((end.y - start.y) * amount);
  3610. result.z = start.z + ((end.z - start.z) * amount);
  3611. };
  3612. /**
  3613. * Returns the dot product (float) between the vectors "left" and "right"
  3614. * @param left defines the left operand
  3615. * @param right defines the right operand
  3616. * @returns the dot product
  3617. */
  3618. Vector3.Dot = function (left, right) {
  3619. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3620. };
  3621. /**
  3622. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3623. * The cross product is then orthogonal to both "left" and "right"
  3624. * @param left defines the left operand
  3625. * @param right defines the right operand
  3626. * @returns the cross product
  3627. */
  3628. Vector3.Cross = function (left, right) {
  3629. var result = Vector3.Zero();
  3630. Vector3.CrossToRef(left, right, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Sets the given vector "result" with the cross product of "left" and "right"
  3635. * The cross product is then orthogonal to both "left" and "right"
  3636. * @param left defines the left operand
  3637. * @param right defines the right operand
  3638. * @param result defines the Vector3 where to store the result
  3639. */
  3640. Vector3.CrossToRef = function (left, right, result) {
  3641. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3642. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3643. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3644. result.copyFrom(MathTmp.Vector3[0]);
  3645. };
  3646. /**
  3647. * Returns a new Vector3 as the normalization of the given vector
  3648. * @param vector defines the Vector3 to normalize
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.Normalize = function (vector) {
  3652. var result = Vector3.Zero();
  3653. Vector3.NormalizeToRef(vector, result);
  3654. return result;
  3655. };
  3656. /**
  3657. * Sets the given vector "result" with the normalization of the given first vector
  3658. * @param vector defines the Vector3 to normalize
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.NormalizeToRef = function (vector, result) {
  3662. result.copyFrom(vector);
  3663. result.normalize();
  3664. };
  3665. /**
  3666. * Project a Vector3 onto screen space
  3667. * @param vector defines the Vector3 to project
  3668. * @param world defines the world matrix to use
  3669. * @param transform defines the transform (view x projection) matrix to use
  3670. * @param viewport defines the screen viewport to use
  3671. * @returns the new Vector3
  3672. */
  3673. Vector3.Project = function (vector, world, transform, viewport) {
  3674. var cw = viewport.width;
  3675. var ch = viewport.height;
  3676. var cx = viewport.x;
  3677. var cy = viewport.y;
  3678. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3679. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3680. var matrix = MathTmp.Matrix[0];
  3681. world.multiplyToRef(transform, matrix);
  3682. matrix.multiplyToRef(viewportMatrix, matrix);
  3683. return Vector3.TransformCoordinates(vector, matrix);
  3684. };
  3685. /**
  3686. * Unproject from screen space to object space
  3687. * @param source defines the screen space Vector3 to use
  3688. * @param viewportWidth defines the current width of the viewport
  3689. * @param viewportHeight defines the current height of the viewport
  3690. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3691. * @param transform defines the transform (view x projection) matrix to use
  3692. * @returns the new Vector3
  3693. */
  3694. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3695. var matrix = MathTmp.Matrix[0];
  3696. world.multiplyToRef(transform, matrix);
  3697. matrix.invert();
  3698. source.x = source.x / viewportWidth * 2 - 1;
  3699. source.y = -(source.y / viewportHeight * 2 - 1);
  3700. var vector = Vector3.TransformCoordinates(source, matrix);
  3701. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3702. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3703. vector = vector.scale(1.0 / num);
  3704. }
  3705. return vector;
  3706. };
  3707. /**
  3708. * Unproject from screen space to object space
  3709. * @param source defines the screen space Vector3 to use
  3710. * @param viewportWidth defines the current width of the viewport
  3711. * @param viewportHeight defines the current height of the viewport
  3712. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3713. * @param view defines the view matrix to use
  3714. * @param projection defines the projection matrix to use
  3715. * @returns the new Vector3
  3716. */
  3717. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3718. var result = Vector3.Zero();
  3719. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3720. return result;
  3721. };
  3722. /**
  3723. * Unproject from screen space to object space
  3724. * @param source defines the screen space Vector3 to use
  3725. * @param viewportWidth defines the current width of the viewport
  3726. * @param viewportHeight defines the current height of the viewport
  3727. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3728. * @param view defines the view matrix to use
  3729. * @param projection defines the projection matrix to use
  3730. * @param result defines the Vector3 where to store the result
  3731. */
  3732. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3733. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3734. };
  3735. /**
  3736. * Unproject from screen space to object space
  3737. * @param sourceX defines the screen space x coordinate to use
  3738. * @param sourceY defines the screen space y coordinate to use
  3739. * @param sourceZ defines the screen space z coordinate to use
  3740. * @param viewportWidth defines the current width of the viewport
  3741. * @param viewportHeight defines the current height of the viewport
  3742. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3743. * @param view defines the view matrix to use
  3744. * @param projection defines the projection matrix to use
  3745. * @param result defines the Vector3 where to store the result
  3746. */
  3747. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3748. var matrix = MathTmp.Matrix[0];
  3749. world.multiplyToRef(view, matrix);
  3750. matrix.multiplyToRef(projection, matrix);
  3751. matrix.invert();
  3752. var screenSource = MathTmp.Vector3[0];
  3753. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3754. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3755. screenSource.z = 2 * sourceZ - 1.0;
  3756. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3757. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3758. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3759. result.scaleInPlace(1.0 / num);
  3760. }
  3761. };
  3762. /**
  3763. * Gets the minimal coordinate values between two Vector3
  3764. * @param left defines the first operand
  3765. * @param right defines the second operand
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.Minimize = function (left, right) {
  3769. var min = left.clone();
  3770. min.minimizeInPlace(right);
  3771. return min;
  3772. };
  3773. /**
  3774. * Gets the maximal coordinate values between two Vector3
  3775. * @param left defines the first operand
  3776. * @param right defines the second operand
  3777. * @returns the new Vector3
  3778. */
  3779. Vector3.Maximize = function (left, right) {
  3780. var max = left.clone();
  3781. max.maximizeInPlace(right);
  3782. return max;
  3783. };
  3784. /**
  3785. * Returns the distance between the vectors "value1" and "value2"
  3786. * @param value1 defines the first operand
  3787. * @param value2 defines the second operand
  3788. * @returns the distance
  3789. */
  3790. Vector3.Distance = function (value1, value2) {
  3791. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3792. };
  3793. /**
  3794. * Returns the squared distance between the vectors "value1" and "value2"
  3795. * @param value1 defines the first operand
  3796. * @param value2 defines the second operand
  3797. * @returns the squared distance
  3798. */
  3799. Vector3.DistanceSquared = function (value1, value2) {
  3800. var x = value1.x - value2.x;
  3801. var y = value1.y - value2.y;
  3802. var z = value1.z - value2.z;
  3803. return (x * x) + (y * y) + (z * z);
  3804. };
  3805. /**
  3806. * Returns a new Vector3 located at the center between "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the new Vector3
  3810. */
  3811. Vector3.Center = function (value1, value2) {
  3812. var center = value1.add(value2);
  3813. center.scaleInPlace(0.5);
  3814. return center;
  3815. };
  3816. /**
  3817. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3819. * to something in order to rotate it from its local system to the given target system
  3820. * Note: axis1, axis2 and axis3 are normalized during this operation
  3821. * @param axis1 defines the first axis
  3822. * @param axis2 defines the second axis
  3823. * @param axis3 defines the third axis
  3824. * @returns a new Vector3
  3825. */
  3826. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3827. var rotation = Vector3.Zero();
  3828. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3829. return rotation;
  3830. };
  3831. /**
  3832. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @param ref defines the Vector3 where to store the result
  3837. */
  3838. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3839. var quat = MathTmp.Quaternion[0];
  3840. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3841. quat.toEulerAnglesToRef(ref);
  3842. };
  3843. return Vector3;
  3844. }());
  3845. BABYLON.Vector3 = Vector3;
  3846. //Vector4 class created for EulerAngle class conversion to Quaternion
  3847. var Vector4 = /** @class */ (function () {
  3848. /**
  3849. * Creates a Vector4 object from the given floats.
  3850. */
  3851. function Vector4(x, y, z, w) {
  3852. this.x = x;
  3853. this.y = y;
  3854. this.z = z;
  3855. this.w = w;
  3856. }
  3857. /**
  3858. * Returns the string with the Vector4 coordinates.
  3859. */
  3860. Vector4.prototype.toString = function () {
  3861. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3862. };
  3863. /**
  3864. * Returns the string "Vector4".
  3865. */
  3866. Vector4.prototype.getClassName = function () {
  3867. return "Vector4";
  3868. };
  3869. /**
  3870. * Returns the Vector4 hash code.
  3871. */
  3872. Vector4.prototype.getHashCode = function () {
  3873. var hash = this.x || 0;
  3874. hash = (hash * 397) ^ (this.y || 0);
  3875. hash = (hash * 397) ^ (this.z || 0);
  3876. hash = (hash * 397) ^ (this.w || 0);
  3877. return hash;
  3878. };
  3879. // Operators
  3880. /**
  3881. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3882. */
  3883. Vector4.prototype.asArray = function () {
  3884. var result = new Array();
  3885. this.toArray(result, 0);
  3886. return result;
  3887. };
  3888. /**
  3889. * Populates the given array from the given index with the Vector4 coordinates.
  3890. * Returns the Vector4.
  3891. */
  3892. Vector4.prototype.toArray = function (array, index) {
  3893. if (index === undefined) {
  3894. index = 0;
  3895. }
  3896. array[index] = this.x;
  3897. array[index + 1] = this.y;
  3898. array[index + 2] = this.z;
  3899. array[index + 3] = this.w;
  3900. return this;
  3901. };
  3902. /**
  3903. * Adds the given vector to the current Vector4.
  3904. * Returns the updated Vector4.
  3905. */
  3906. Vector4.prototype.addInPlace = function (otherVector) {
  3907. this.x += otherVector.x;
  3908. this.y += otherVector.y;
  3909. this.z += otherVector.z;
  3910. this.w += otherVector.w;
  3911. return this;
  3912. };
  3913. /**
  3914. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3915. */
  3916. Vector4.prototype.add = function (otherVector) {
  3917. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3918. };
  3919. /**
  3920. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3921. * Returns the current Vector4.
  3922. */
  3923. Vector4.prototype.addToRef = function (otherVector, result) {
  3924. result.x = this.x + otherVector.x;
  3925. result.y = this.y + otherVector.y;
  3926. result.z = this.z + otherVector.z;
  3927. result.w = this.w + otherVector.w;
  3928. return this;
  3929. };
  3930. /**
  3931. * Subtract in place the given vector from the current Vector4.
  3932. * Returns the updated Vector4.
  3933. */
  3934. Vector4.prototype.subtractInPlace = function (otherVector) {
  3935. this.x -= otherVector.x;
  3936. this.y -= otherVector.y;
  3937. this.z -= otherVector.z;
  3938. this.w -= otherVector.w;
  3939. return this;
  3940. };
  3941. /**
  3942. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3943. */
  3944. Vector4.prototype.subtract = function (otherVector) {
  3945. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3946. };
  3947. /**
  3948. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3949. * Returns the current Vector4.
  3950. */
  3951. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3952. result.x = this.x - otherVector.x;
  3953. result.y = this.y - otherVector.y;
  3954. result.z = this.z - otherVector.z;
  3955. result.w = this.w - otherVector.w;
  3956. return this;
  3957. };
  3958. /**
  3959. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3960. */
  3961. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3962. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3963. };
  3964. /**
  3965. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3966. * Returns the current Vector4.
  3967. */
  3968. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3969. result.x = this.x - x;
  3970. result.y = this.y - y;
  3971. result.z = this.z - z;
  3972. result.w = this.w - w;
  3973. return this;
  3974. };
  3975. /**
  3976. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3977. */
  3978. Vector4.prototype.negate = function () {
  3979. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3980. };
  3981. /**
  3982. * Multiplies the current Vector4 coordinates by scale (float).
  3983. * Returns the updated Vector4.
  3984. */
  3985. Vector4.prototype.scaleInPlace = function (scale) {
  3986. this.x *= scale;
  3987. this.y *= scale;
  3988. this.z *= scale;
  3989. this.w *= scale;
  3990. return this;
  3991. };
  3992. /**
  3993. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3994. */
  3995. Vector4.prototype.scale = function (scale) {
  3996. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3997. };
  3998. /**
  3999. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4000. * Returns the current Vector4.
  4001. */
  4002. Vector4.prototype.scaleToRef = function (scale, result) {
  4003. result.x = this.x * scale;
  4004. result.y = this.y * scale;
  4005. result.z = this.z * scale;
  4006. result.w = this.w * scale;
  4007. return this;
  4008. };
  4009. /**
  4010. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4011. * @param scale defines the scale factor
  4012. * @param result defines the Vector4 object where to store the result
  4013. * @returns the unmodified current Vector4
  4014. */
  4015. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4016. result.x += this.x * scale;
  4017. result.y += this.y * scale;
  4018. result.z += this.z * scale;
  4019. result.w += this.w * scale;
  4020. return this;
  4021. };
  4022. /**
  4023. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4024. */
  4025. Vector4.prototype.equals = function (otherVector) {
  4026. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4027. };
  4028. /**
  4029. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4030. */
  4031. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4032. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4033. return otherVector
  4034. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4035. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4036. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4037. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4038. };
  4039. /**
  4040. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4041. */
  4042. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4043. return this.x === x && this.y === y && this.z === z && this.w === w;
  4044. };
  4045. /**
  4046. * Multiplies in place the current Vector4 by the given one.
  4047. * Returns the updated Vector4.
  4048. */
  4049. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4050. this.x *= otherVector.x;
  4051. this.y *= otherVector.y;
  4052. this.z *= otherVector.z;
  4053. this.w *= otherVector.w;
  4054. return this;
  4055. };
  4056. /**
  4057. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4058. */
  4059. Vector4.prototype.multiply = function (otherVector) {
  4060. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4061. };
  4062. /**
  4063. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4064. * Returns the current Vector4.
  4065. */
  4066. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4067. result.x = this.x * otherVector.x;
  4068. result.y = this.y * otherVector.y;
  4069. result.z = this.z * otherVector.z;
  4070. result.w = this.w * otherVector.w;
  4071. return this;
  4072. };
  4073. /**
  4074. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4075. */
  4076. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4077. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4078. };
  4079. /**
  4080. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4081. */
  4082. Vector4.prototype.divide = function (otherVector) {
  4083. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4084. };
  4085. /**
  4086. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4087. * Returns the current Vector4.
  4088. */
  4089. Vector4.prototype.divideToRef = function (otherVector, result) {
  4090. result.x = this.x / otherVector.x;
  4091. result.y = this.y / otherVector.y;
  4092. result.z = this.z / otherVector.z;
  4093. result.w = this.w / otherVector.w;
  4094. return this;
  4095. };
  4096. /**
  4097. * Divides the current Vector3 coordinates by the given ones.
  4098. * @returns the updated Vector3.
  4099. */
  4100. Vector4.prototype.divideInPlace = function (otherVector) {
  4101. return this.divideToRef(otherVector, this);
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.minimizeInPlace = function (other) {
  4109. if (other.x < this.x)
  4110. this.x = other.x;
  4111. if (other.y < this.y)
  4112. this.y = other.y;
  4113. if (other.z < this.z)
  4114. this.z = other.z;
  4115. if (other.w < this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4121. * @param other defines the second operand
  4122. * @returns the current updated Vector4
  4123. */
  4124. Vector4.prototype.maximizeInPlace = function (other) {
  4125. if (other.x > this.x)
  4126. this.x = other.x;
  4127. if (other.y > this.y)
  4128. this.y = other.y;
  4129. if (other.z > this.z)
  4130. this.z = other.z;
  4131. if (other.w > this.w)
  4132. this.w = other.w;
  4133. return this;
  4134. };
  4135. // Properties
  4136. /**
  4137. * Returns the Vector4 length (float).
  4138. */
  4139. Vector4.prototype.length = function () {
  4140. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4141. };
  4142. /**
  4143. * Returns the Vector4 squared length (float).
  4144. */
  4145. Vector4.prototype.lengthSquared = function () {
  4146. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4147. };
  4148. // Methods
  4149. /**
  4150. * Normalizes in place the Vector4.
  4151. * Returns the updated Vector4.
  4152. */
  4153. Vector4.prototype.normalize = function () {
  4154. var len = this.length();
  4155. if (len === 0)
  4156. return this;
  4157. var num = 1.0 / len;
  4158. this.x *= num;
  4159. this.y *= num;
  4160. this.z *= num;
  4161. this.w *= num;
  4162. return this;
  4163. };
  4164. /**
  4165. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4166. */
  4167. Vector4.prototype.toVector3 = function () {
  4168. return new Vector3(this.x, this.y, this.z);
  4169. };
  4170. /**
  4171. * Returns a new Vector4 copied from the current one.
  4172. */
  4173. Vector4.prototype.clone = function () {
  4174. return new Vector4(this.x, this.y, this.z, this.w);
  4175. };
  4176. /**
  4177. * Updates the current Vector4 with the given one coordinates.
  4178. * Returns the updated Vector4.
  4179. */
  4180. Vector4.prototype.copyFrom = function (source) {
  4181. this.x = source.x;
  4182. this.y = source.y;
  4183. this.z = source.z;
  4184. this.w = source.w;
  4185. return this;
  4186. };
  4187. /**
  4188. * Updates the current Vector4 coordinates with the given floats.
  4189. * Returns the updated Vector4.
  4190. */
  4191. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4192. this.x = x;
  4193. this.y = y;
  4194. this.z = z;
  4195. this.w = w;
  4196. return this;
  4197. };
  4198. /**
  4199. * Updates the current Vector4 coordinates with the given floats.
  4200. * Returns the updated Vector4.
  4201. */
  4202. Vector4.prototype.set = function (x, y, z, w) {
  4203. return this.copyFromFloats(x, y, z, w);
  4204. };
  4205. // Statics
  4206. /**
  4207. * Returns a new Vector4 set from the starting index of the given array.
  4208. */
  4209. Vector4.FromArray = function (array, offset) {
  4210. if (!offset) {
  4211. offset = 0;
  4212. }
  4213. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4214. };
  4215. /**
  4216. * Updates the given vector "result" from the starting index of the given array.
  4217. */
  4218. Vector4.FromArrayToRef = function (array, offset, result) {
  4219. result.x = array[offset];
  4220. result.y = array[offset + 1];
  4221. result.z = array[offset + 2];
  4222. result.w = array[offset + 3];
  4223. };
  4224. /**
  4225. * Updates the given vector "result" from the starting index of the given Float32Array.
  4226. */
  4227. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4228. Vector4.FromArrayToRef(array, offset, result);
  4229. };
  4230. /**
  4231. * Updates the given vector "result" coordinates from the given floats.
  4232. */
  4233. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4234. result.x = x;
  4235. result.y = y;
  4236. result.z = z;
  4237. result.w = w;
  4238. };
  4239. /**
  4240. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4241. */
  4242. Vector4.Zero = function () {
  4243. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4244. };
  4245. /**
  4246. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4247. */
  4248. Vector4.One = function () {
  4249. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4250. };
  4251. /**
  4252. * Returns a new normalized Vector4 from the given one.
  4253. */
  4254. Vector4.Normalize = function (vector) {
  4255. var result = Vector4.Zero();
  4256. Vector4.NormalizeToRef(vector, result);
  4257. return result;
  4258. };
  4259. /**
  4260. * Updates the given vector "result" from the normalization of the given one.
  4261. */
  4262. Vector4.NormalizeToRef = function (vector, result) {
  4263. result.copyFrom(vector);
  4264. result.normalize();
  4265. };
  4266. Vector4.Minimize = function (left, right) {
  4267. var min = left.clone();
  4268. min.minimizeInPlace(right);
  4269. return min;
  4270. };
  4271. Vector4.Maximize = function (left, right) {
  4272. var max = left.clone();
  4273. max.maximizeInPlace(right);
  4274. return max;
  4275. };
  4276. /**
  4277. * Returns the distance (float) between the vectors "value1" and "value2".
  4278. */
  4279. Vector4.Distance = function (value1, value2) {
  4280. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4281. };
  4282. /**
  4283. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4284. */
  4285. Vector4.DistanceSquared = function (value1, value2) {
  4286. var x = value1.x - value2.x;
  4287. var y = value1.y - value2.y;
  4288. var z = value1.z - value2.z;
  4289. var w = value1.w - value2.w;
  4290. return (x * x) + (y * y) + (z * z) + (w * w);
  4291. };
  4292. /**
  4293. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4294. */
  4295. Vector4.Center = function (value1, value2) {
  4296. var center = value1.add(value2);
  4297. center.scaleInPlace(0.5);
  4298. return center;
  4299. };
  4300. /**
  4301. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4302. * This methods computes transformed normalized direction vectors only.
  4303. */
  4304. Vector4.TransformNormal = function (vector, transformation) {
  4305. var result = Vector4.Zero();
  4306. Vector4.TransformNormalToRef(vector, transformation, result);
  4307. return result;
  4308. };
  4309. /**
  4310. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4311. * This methods computes transformed normalized direction vectors only.
  4312. */
  4313. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4314. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4315. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4316. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4317. result.x = x;
  4318. result.y = y;
  4319. result.z = z;
  4320. result.w = vector.w;
  4321. };
  4322. /**
  4323. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4324. * This methods computes transformed normalized direction vectors only.
  4325. */
  4326. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4327. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4328. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4329. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4330. result.w = w;
  4331. };
  4332. return Vector4;
  4333. }());
  4334. BABYLON.Vector4 = Vector4;
  4335. var Size = /** @class */ (function () {
  4336. /**
  4337. * Creates a Size object from the given width and height (floats).
  4338. */
  4339. function Size(width, height) {
  4340. this.width = width;
  4341. this.height = height;
  4342. }
  4343. // Returns a string with the Size width and height.
  4344. Size.prototype.toString = function () {
  4345. return "{W: " + this.width + ", H: " + this.height + "}";
  4346. };
  4347. /**
  4348. * Returns the string "Size"
  4349. */
  4350. Size.prototype.getClassName = function () {
  4351. return "Size";
  4352. };
  4353. /**
  4354. * Returns the Size hash code.
  4355. */
  4356. Size.prototype.getHashCode = function () {
  4357. var hash = this.width || 0;
  4358. hash = (hash * 397) ^ (this.height || 0);
  4359. return hash;
  4360. };
  4361. /**
  4362. * Updates the current size from the given one.
  4363. * Returns the updated Size.
  4364. */
  4365. Size.prototype.copyFrom = function (src) {
  4366. this.width = src.width;
  4367. this.height = src.height;
  4368. };
  4369. /**
  4370. * Updates in place the current Size from the given floats.
  4371. * Returns the updated Size.
  4372. */
  4373. Size.prototype.copyFromFloats = function (width, height) {
  4374. this.width = width;
  4375. this.height = height;
  4376. return this;
  4377. };
  4378. /**
  4379. * Updates in place the current Size from the given floats.
  4380. * Returns the updated Size.
  4381. */
  4382. Size.prototype.set = function (width, height) {
  4383. return this.copyFromFloats(width, height);
  4384. };
  4385. /**
  4386. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4387. */
  4388. Size.prototype.multiplyByFloats = function (w, h) {
  4389. return new Size(this.width * w, this.height * h);
  4390. };
  4391. /**
  4392. * Returns a new Size copied from the given one.
  4393. */
  4394. Size.prototype.clone = function () {
  4395. return new Size(this.width, this.height);
  4396. };
  4397. /**
  4398. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4399. */
  4400. Size.prototype.equals = function (other) {
  4401. if (!other) {
  4402. return false;
  4403. }
  4404. return (this.width === other.width) && (this.height === other.height);
  4405. };
  4406. Object.defineProperty(Size.prototype, "surface", {
  4407. /**
  4408. * Returns the surface of the Size : width * height (float).
  4409. */
  4410. get: function () {
  4411. return this.width * this.height;
  4412. },
  4413. enumerable: true,
  4414. configurable: true
  4415. });
  4416. /**
  4417. * Returns a new Size set to (0.0, 0.0)
  4418. */
  4419. Size.Zero = function () {
  4420. return new Size(0.0, 0.0);
  4421. };
  4422. /**
  4423. * Returns a new Size set as the addition result of the current Size and the given one.
  4424. */
  4425. Size.prototype.add = function (otherSize) {
  4426. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4427. return r;
  4428. };
  4429. /**
  4430. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4431. */
  4432. Size.prototype.subtract = function (otherSize) {
  4433. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4434. return r;
  4435. };
  4436. /**
  4437. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4438. */
  4439. Size.Lerp = function (start, end, amount) {
  4440. var w = start.width + ((end.width - start.width) * amount);
  4441. var h = start.height + ((end.height - start.height) * amount);
  4442. return new Size(w, h);
  4443. };
  4444. return Size;
  4445. }());
  4446. BABYLON.Size = Size;
  4447. /**
  4448. * Class used to store quaternion data
  4449. * @see https://en.wikipedia.org/wiki/Quaternion
  4450. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4451. */
  4452. var Quaternion = /** @class */ (function () {
  4453. /**
  4454. * Creates a new Quaternion from the given floats
  4455. * @param x defines the first component (0 by default)
  4456. * @param y defines the second component (0 by default)
  4457. * @param z defines the third component (0 by default)
  4458. * @param w defines the fourth component (1.0 by default)
  4459. */
  4460. function Quaternion(
  4461. /** defines the first component (0 by default) */
  4462. x,
  4463. /** defines the second component (0 by default) */
  4464. y,
  4465. /** defines the third component (0 by default) */
  4466. z,
  4467. /** defines the fourth component (1.0 by default) */
  4468. w) {
  4469. if (x === void 0) { x = 0.0; }
  4470. if (y === void 0) { y = 0.0; }
  4471. if (z === void 0) { z = 0.0; }
  4472. if (w === void 0) { w = 1.0; }
  4473. this.x = x;
  4474. this.y = y;
  4475. this.z = z;
  4476. this.w = w;
  4477. }
  4478. /**
  4479. * Gets a string representation for the current quaternion
  4480. * @returns a string with the Quaternion coordinates
  4481. */
  4482. Quaternion.prototype.toString = function () {
  4483. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4484. };
  4485. /**
  4486. * Gets the class name of the quaternion
  4487. * @returns the string "Quaternion"
  4488. */
  4489. Quaternion.prototype.getClassName = function () {
  4490. return "Quaternion";
  4491. };
  4492. /**
  4493. * Gets a hash code for this quaternion
  4494. * @returns the quaternion hash code
  4495. */
  4496. Quaternion.prototype.getHashCode = function () {
  4497. var hash = this.x || 0;
  4498. hash = (hash * 397) ^ (this.y || 0);
  4499. hash = (hash * 397) ^ (this.z || 0);
  4500. hash = (hash * 397) ^ (this.w || 0);
  4501. return hash;
  4502. };
  4503. /**
  4504. * Copy the quaternion to an array
  4505. * @returns a new array populated with 4 elements from the quaternion coordinates
  4506. */
  4507. Quaternion.prototype.asArray = function () {
  4508. return [this.x, this.y, this.z, this.w];
  4509. };
  4510. /**
  4511. * Check if two quaternions are equals
  4512. * @param otherQuaternion defines the second operand
  4513. * @return true if the current quaternion and the given one coordinates are strictly equals
  4514. */
  4515. Quaternion.prototype.equals = function (otherQuaternion) {
  4516. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4517. };
  4518. /**
  4519. * Clone the current quaternion
  4520. * @returns a new quaternion copied from the current one
  4521. */
  4522. Quaternion.prototype.clone = function () {
  4523. return new Quaternion(this.x, this.y, this.z, this.w);
  4524. };
  4525. /**
  4526. * Copy a quaternion to the current one
  4527. * @param other defines the other quaternion
  4528. * @returns the updated current quaternion
  4529. */
  4530. Quaternion.prototype.copyFrom = function (other) {
  4531. this.x = other.x;
  4532. this.y = other.y;
  4533. this.z = other.z;
  4534. this.w = other.w;
  4535. return this;
  4536. };
  4537. /**
  4538. * Updates the current quaternion with the given float coordinates
  4539. * @param x defines the x coordinate
  4540. * @param y defines the y coordinate
  4541. * @param z defines the z coordinate
  4542. * @param w defines the w coordinate
  4543. * @returns the updated current quaternion
  4544. */
  4545. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4546. this.x = x;
  4547. this.y = y;
  4548. this.z = z;
  4549. this.w = w;
  4550. return this;
  4551. };
  4552. /**
  4553. * Updates the current quaternion from the given float coordinates
  4554. * @param x defines the x coordinate
  4555. * @param y defines the y coordinate
  4556. * @param z defines the z coordinate
  4557. * @param w defines the w coordinate
  4558. * @returns the updated current quaternion
  4559. */
  4560. Quaternion.prototype.set = function (x, y, z, w) {
  4561. return this.copyFromFloats(x, y, z, w);
  4562. };
  4563. /**
  4564. * Adds two quaternions
  4565. * @param other defines the second operand
  4566. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4567. */
  4568. Quaternion.prototype.add = function (other) {
  4569. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4570. };
  4571. /**
  4572. * Add a quaternion to the current one
  4573. * @param other defines the quaternion to add
  4574. * @returns the current quaternion
  4575. */
  4576. Quaternion.prototype.addInPlace = function (other) {
  4577. this.x += other.x;
  4578. this.y += other.y;
  4579. this.z += other.z;
  4580. this.w += other.w;
  4581. return this;
  4582. };
  4583. /**
  4584. * Subtract two quaternions
  4585. * @param other defines the second operand
  4586. * @returns a new quaternion as the subtraction result of the given one from the current one
  4587. */
  4588. Quaternion.prototype.subtract = function (other) {
  4589. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4590. };
  4591. /**
  4592. * Multiplies the current quaternion by a scale factor
  4593. * @param value defines the scale factor
  4594. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4595. */
  4596. Quaternion.prototype.scale = function (value) {
  4597. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4598. };
  4599. /**
  4600. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4601. * @param scale defines the scale factor
  4602. * @param result defines the Quaternion object where to store the result
  4603. * @returns the unmodified current quaternion
  4604. */
  4605. Quaternion.prototype.scaleToRef = function (scale, result) {
  4606. result.x = this.x * scale;
  4607. result.y = this.y * scale;
  4608. result.z = this.z * scale;
  4609. result.w = this.w * scale;
  4610. return this;
  4611. };
  4612. /**
  4613. * Multiplies in place the current quaternion by a scale factor
  4614. * @param value defines the scale factor
  4615. * @returns the current modified quaternion
  4616. */
  4617. Quaternion.prototype.scaleInPlace = function (value) {
  4618. this.x *= value;
  4619. this.y *= value;
  4620. this.z *= value;
  4621. this.w *= value;
  4622. return this;
  4623. };
  4624. /**
  4625. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4626. * @param scale defines the scale factor
  4627. * @param result defines the Quaternion object where to store the result
  4628. * @returns the unmodified current quaternion
  4629. */
  4630. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4631. result.x += this.x * scale;
  4632. result.y += this.y * scale;
  4633. result.z += this.z * scale;
  4634. result.w += this.w * scale;
  4635. return this;
  4636. };
  4637. /**
  4638. * Multiplies two quaternions
  4639. * @param q1 defines the second operand
  4640. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4641. */
  4642. Quaternion.prototype.multiply = function (q1) {
  4643. var result = new Quaternion(0, 0, 0, 1.0);
  4644. this.multiplyToRef(q1, result);
  4645. return result;
  4646. };
  4647. /**
  4648. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4649. * @param q1 defines the second operand
  4650. * @param result defines the target quaternion
  4651. * @returns the current quaternion
  4652. */
  4653. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4654. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4655. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4656. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4657. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4658. result.copyFromFloats(x, y, z, w);
  4659. return this;
  4660. };
  4661. /**
  4662. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4663. * @param q1 defines the second operand
  4664. * @returns the currentupdated quaternion
  4665. */
  4666. Quaternion.prototype.multiplyInPlace = function (q1) {
  4667. this.multiplyToRef(q1, this);
  4668. return this;
  4669. };
  4670. /**
  4671. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4672. * @param ref defines the target quaternion
  4673. * @returns the current quaternion
  4674. */
  4675. Quaternion.prototype.conjugateToRef = function (ref) {
  4676. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4677. return this;
  4678. };
  4679. /**
  4680. * Conjugates in place (1-q) the current quaternion
  4681. * @returns the current updated quaternion
  4682. */
  4683. Quaternion.prototype.conjugateInPlace = function () {
  4684. this.x *= -1;
  4685. this.y *= -1;
  4686. this.z *= -1;
  4687. return this;
  4688. };
  4689. /**
  4690. * Conjugates in place (1-q) the current quaternion
  4691. * @returns a new quaternion
  4692. */
  4693. Quaternion.prototype.conjugate = function () {
  4694. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4695. return result;
  4696. };
  4697. /**
  4698. * Gets length of current quaternion
  4699. * @returns the quaternion length (float)
  4700. */
  4701. Quaternion.prototype.length = function () {
  4702. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4703. };
  4704. /**
  4705. * Normalize in place the current quaternion
  4706. * @returns the current updated quaternion
  4707. */
  4708. Quaternion.prototype.normalize = function () {
  4709. var length = 1.0 / this.length();
  4710. this.x *= length;
  4711. this.y *= length;
  4712. this.z *= length;
  4713. this.w *= length;
  4714. return this;
  4715. };
  4716. /**
  4717. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4718. * @param order is a reserved parameter and is ignore for now
  4719. * @returns a new Vector3 containing the Euler angles
  4720. */
  4721. Quaternion.prototype.toEulerAngles = function (order) {
  4722. if (order === void 0) { order = "YZX"; }
  4723. var result = Vector3.Zero();
  4724. this.toEulerAnglesToRef(result, order);
  4725. return result;
  4726. };
  4727. /**
  4728. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4729. * @param result defines the vector which will be filled with the Euler angles
  4730. * @param order is a reserved parameter and is ignore for now
  4731. * @returns the current unchanged quaternion
  4732. */
  4733. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4734. if (order === void 0) { order = "YZX"; }
  4735. var qz = this.z;
  4736. var qx = this.x;
  4737. var qy = this.y;
  4738. var qw = this.w;
  4739. var sqw = qw * qw;
  4740. var sqz = qz * qz;
  4741. var sqx = qx * qx;
  4742. var sqy = qy * qy;
  4743. var zAxisY = qy * qz - qx * qw;
  4744. var limit = .4999999;
  4745. if (zAxisY < -limit) {
  4746. result.y = 2 * Math.atan2(qy, qw);
  4747. result.x = Math.PI / 2;
  4748. result.z = 0;
  4749. }
  4750. else if (zAxisY > limit) {
  4751. result.y = 2 * Math.atan2(qy, qw);
  4752. result.x = -Math.PI / 2;
  4753. result.z = 0;
  4754. }
  4755. else {
  4756. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4757. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4758. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4759. }
  4760. return this;
  4761. };
  4762. /**
  4763. * Updates the given rotation matrix with the current quaternion values
  4764. * @param result defines the target matrix
  4765. * @returns the current unchanged quaternion
  4766. */
  4767. Quaternion.prototype.toRotationMatrix = function (result) {
  4768. var xx = this.x * this.x;
  4769. var yy = this.y * this.y;
  4770. var zz = this.z * this.z;
  4771. var xy = this.x * this.y;
  4772. var zw = this.z * this.w;
  4773. var zx = this.z * this.x;
  4774. var yw = this.y * this.w;
  4775. var yz = this.y * this.z;
  4776. var xw = this.x * this.w;
  4777. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4778. result.m[1] = 2.0 * (xy + zw);
  4779. result.m[2] = 2.0 * (zx - yw);
  4780. result.m[3] = 0;
  4781. result.m[4] = 2.0 * (xy - zw);
  4782. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4783. result.m[6] = 2.0 * (yz + xw);
  4784. result.m[7] = 0;
  4785. result.m[8] = 2.0 * (zx + yw);
  4786. result.m[9] = 2.0 * (yz - xw);
  4787. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4788. result.m[11] = 0;
  4789. result.m[12] = 0;
  4790. result.m[13] = 0;
  4791. result.m[14] = 0;
  4792. result.m[15] = 1.0;
  4793. result._markAsUpdated();
  4794. return this;
  4795. };
  4796. /**
  4797. * Updates the current quaternion from the given rotation matrix values
  4798. * @param matrix defines the source matrix
  4799. * @returns the current updated quaternion
  4800. */
  4801. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4802. Quaternion.FromRotationMatrixToRef(matrix, this);
  4803. return this;
  4804. };
  4805. // Statics
  4806. /**
  4807. * Creates a new quaternion from a rotation matrix
  4808. * @param matrix defines the source matrix
  4809. * @returns a new quaternion created from the given rotation matrix values
  4810. */
  4811. Quaternion.FromRotationMatrix = function (matrix) {
  4812. var result = new Quaternion();
  4813. Quaternion.FromRotationMatrixToRef(matrix, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Updates the given quaternion with the given rotation matrix values
  4818. * @param matrix defines the source matrix
  4819. * @param result defines the target quaternion
  4820. */
  4821. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4822. var data = matrix.m;
  4823. var m11 = data[0], m12 = data[4], m13 = data[8];
  4824. var m21 = data[1], m22 = data[5], m23 = data[9];
  4825. var m31 = data[2], m32 = data[6], m33 = data[10];
  4826. var trace = m11 + m22 + m33;
  4827. var s;
  4828. if (trace > 0) {
  4829. s = 0.5 / Math.sqrt(trace + 1.0);
  4830. result.w = 0.25 / s;
  4831. result.x = (m32 - m23) * s;
  4832. result.y = (m13 - m31) * s;
  4833. result.z = (m21 - m12) * s;
  4834. }
  4835. else if (m11 > m22 && m11 > m33) {
  4836. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4837. result.w = (m32 - m23) / s;
  4838. result.x = 0.25 * s;
  4839. result.y = (m12 + m21) / s;
  4840. result.z = (m13 + m31) / s;
  4841. }
  4842. else if (m22 > m33) {
  4843. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4844. result.w = (m13 - m31) / s;
  4845. result.x = (m12 + m21) / s;
  4846. result.y = 0.25 * s;
  4847. result.z = (m23 + m32) / s;
  4848. }
  4849. else {
  4850. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4851. result.w = (m21 - m12) / s;
  4852. result.x = (m13 + m31) / s;
  4853. result.y = (m23 + m32) / s;
  4854. result.z = 0.25 * s;
  4855. }
  4856. };
  4857. /**
  4858. * Returns the dot product (float) between the quaternions "left" and "right"
  4859. * @param left defines the left operand
  4860. * @param right defines the right operand
  4861. * @returns the dot product
  4862. */
  4863. Quaternion.Dot = function (left, right) {
  4864. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4865. };
  4866. /**
  4867. * Checks if the two quaternions are close to each other
  4868. * @param quat0 defines the first quaternion to check
  4869. * @param quat1 defines the second quaternion to check
  4870. * @returns true if the two quaternions are close to each other
  4871. */
  4872. Quaternion.AreClose = function (quat0, quat1) {
  4873. var dot = Quaternion.Dot(quat0, quat1);
  4874. return dot >= 0;
  4875. };
  4876. /**
  4877. * Creates an empty quaternion
  4878. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4879. */
  4880. Quaternion.Zero = function () {
  4881. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4882. };
  4883. /**
  4884. * Inverse a given quaternion
  4885. * @param q defines the source quaternion
  4886. * @returns a new quaternion as the inverted current quaternion
  4887. */
  4888. Quaternion.Inverse = function (q) {
  4889. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4890. };
  4891. /**
  4892. * Creates an identity quaternion
  4893. * @returns the identity quaternion
  4894. */
  4895. Quaternion.Identity = function () {
  4896. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4897. };
  4898. /**
  4899. * Gets a boolean indicating if the given quaternion is identity
  4900. * @param quaternion defines the quaternion to check
  4901. * @returns true if the quaternion is identity
  4902. */
  4903. Quaternion.IsIdentity = function (quaternion) {
  4904. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4905. };
  4906. /**
  4907. * Creates a quaternion from a rotation around an axis
  4908. * @param axis defines the axis to use
  4909. * @param angle defines the angle to use
  4910. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4911. */
  4912. Quaternion.RotationAxis = function (axis, angle) {
  4913. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4914. };
  4915. /**
  4916. * Creates a rotation around an axis and stores it into the given quaternion
  4917. * @param axis defines the axis to use
  4918. * @param angle defines the angle to use
  4919. * @param result defines the target quaternion
  4920. * @returns the target quaternion
  4921. */
  4922. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4923. var sin = Math.sin(angle / 2);
  4924. axis.normalize();
  4925. result.w = Math.cos(angle / 2);
  4926. result.x = axis.x * sin;
  4927. result.y = axis.y * sin;
  4928. result.z = axis.z * sin;
  4929. return result;
  4930. };
  4931. /**
  4932. * Creates a new quaternion from data stored into an array
  4933. * @param array defines the data source
  4934. * @param offset defines the offset in the source array where the data starts
  4935. * @returns a new quaternion
  4936. */
  4937. Quaternion.FromArray = function (array, offset) {
  4938. if (!offset) {
  4939. offset = 0;
  4940. }
  4941. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4942. };
  4943. /**
  4944. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4945. * @param yaw defines the rotation around Y axis
  4946. * @param pitch defines the rotation around X axis
  4947. * @param roll defines the rotation around Z axis
  4948. * @returns the new quaternion
  4949. */
  4950. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4951. var q = new Quaternion();
  4952. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4953. return q;
  4954. };
  4955. /**
  4956. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4957. * @param yaw defines the rotation around Y axis
  4958. * @param pitch defines the rotation around X axis
  4959. * @param roll defines the rotation around Z axis
  4960. * @param result defines the target quaternion
  4961. */
  4962. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4963. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4964. var halfRoll = roll * 0.5;
  4965. var halfPitch = pitch * 0.5;
  4966. var halfYaw = yaw * 0.5;
  4967. var sinRoll = Math.sin(halfRoll);
  4968. var cosRoll = Math.cos(halfRoll);
  4969. var sinPitch = Math.sin(halfPitch);
  4970. var cosPitch = Math.cos(halfPitch);
  4971. var sinYaw = Math.sin(halfYaw);
  4972. var cosYaw = Math.cos(halfYaw);
  4973. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4974. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4975. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4976. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4977. };
  4978. /**
  4979. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4980. * @param alpha defines the rotation around first axis
  4981. * @param beta defines the rotation around second axis
  4982. * @param gamma defines the rotation around third axis
  4983. * @returns the new quaternion
  4984. */
  4985. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4986. var result = new Quaternion();
  4987. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4988. return result;
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4992. * @param alpha defines the rotation around first axis
  4993. * @param beta defines the rotation around second axis
  4994. * @param gamma defines the rotation around third axis
  4995. * @param result defines the target quaternion
  4996. */
  4997. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4998. // Produces a quaternion from Euler angles in the z-x-z orientation
  4999. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5000. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5001. var halfBeta = beta * 0.5;
  5002. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5003. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5004. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5005. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5006. };
  5007. /**
  5008. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5009. * @param axis1 defines the first axis
  5010. * @param axis2 defines the second axis
  5011. * @param axis3 defines the third axis
  5012. * @returns the new quaternion
  5013. */
  5014. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5015. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5016. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5017. return quat;
  5018. };
  5019. /**
  5020. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5021. * @param axis1 defines the first axis
  5022. * @param axis2 defines the second axis
  5023. * @param axis3 defines the third axis
  5024. * @param ref defines the target quaternion
  5025. */
  5026. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5027. var rotMat = MathTmp.Matrix[0];
  5028. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5029. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5030. };
  5031. /**
  5032. * Interpolates between two quaternions
  5033. * @param left defines first quaternion
  5034. * @param right defines second quaternion
  5035. * @param amount defines the gradient to use
  5036. * @returns the new interpolated quaternion
  5037. */
  5038. Quaternion.Slerp = function (left, right, amount) {
  5039. var result = Quaternion.Identity();
  5040. Quaternion.SlerpToRef(left, right, amount, result);
  5041. return result;
  5042. };
  5043. /**
  5044. * Interpolates between two quaternions and stores it into a target quaternion
  5045. * @param left defines first quaternion
  5046. * @param right defines second quaternion
  5047. * @param amount defines the gradient to use
  5048. * @param result defines the target quaternion
  5049. */
  5050. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5051. var num2;
  5052. var num3;
  5053. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5054. var flag = false;
  5055. if (num4 < 0) {
  5056. flag = true;
  5057. num4 = -num4;
  5058. }
  5059. if (num4 > 0.999999) {
  5060. num3 = 1 - amount;
  5061. num2 = flag ? -amount : amount;
  5062. }
  5063. else {
  5064. var num5 = Math.acos(num4);
  5065. var num6 = (1.0 / Math.sin(num5));
  5066. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5067. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5068. }
  5069. result.x = (num3 * left.x) + (num2 * right.x);
  5070. result.y = (num3 * left.y) + (num2 * right.y);
  5071. result.z = (num3 * left.z) + (num2 * right.z);
  5072. result.w = (num3 * left.w) + (num2 * right.w);
  5073. };
  5074. /**
  5075. * Interpolate between two quaternions using Hermite interpolation
  5076. * @param value1 defines first quaternion
  5077. * @param tangent1 defines the incoming tangent
  5078. * @param value2 defines second quaternion
  5079. * @param tangent2 defines the outgoing tangent
  5080. * @param amount defines the target quaternion
  5081. * @returns the new interpolated quaternion
  5082. */
  5083. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5084. var squared = amount * amount;
  5085. var cubed = amount * squared;
  5086. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5087. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5088. var part3 = (cubed - (2.0 * squared)) + amount;
  5089. var part4 = cubed - squared;
  5090. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5091. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5092. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5093. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5094. return new Quaternion(x, y, z, w);
  5095. };
  5096. return Quaternion;
  5097. }());
  5098. BABYLON.Quaternion = Quaternion;
  5099. /**
  5100. * Class used to store matrix data (4x4)
  5101. */
  5102. var Matrix = /** @class */ (function () {
  5103. /**
  5104. * Creates an empty matrix (filled with zeros)
  5105. */
  5106. function Matrix() {
  5107. this._isIdentity = false;
  5108. this._isIdentityDirty = true;
  5109. /**
  5110. * Gets or sets the internal data of the matrix
  5111. */
  5112. this.m = new Float32Array(16);
  5113. this._markAsUpdated();
  5114. }
  5115. /** @hidden */
  5116. Matrix.prototype._markAsUpdated = function () {
  5117. this.updateFlag = Matrix._updateFlagSeed++;
  5118. this._isIdentityDirty = true;
  5119. };
  5120. // Properties
  5121. /**
  5122. * Check if the current matrix is indentity
  5123. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5124. * @returns true is the matrix is the identity matrix
  5125. */
  5126. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5127. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5128. if (this._isIdentityDirty) {
  5129. this._isIdentityDirty = false;
  5130. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5131. this._isIdentity = false;
  5132. }
  5133. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5134. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5135. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5136. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5137. this._isIdentity = false;
  5138. }
  5139. else {
  5140. this._isIdentity = true;
  5141. }
  5142. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5143. this._isIdentity = false;
  5144. }
  5145. }
  5146. return this._isIdentity;
  5147. };
  5148. /**
  5149. * Gets the determinant of the matrix
  5150. * @returns the matrix determinant
  5151. */
  5152. Matrix.prototype.determinant = function () {
  5153. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5154. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5155. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5156. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5157. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5158. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5159. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5160. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5161. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5162. };
  5163. // Methods
  5164. /**
  5165. * Returns the matrix as a Float32Array
  5166. * @returns the matrix underlying array
  5167. */
  5168. Matrix.prototype.toArray = function () {
  5169. return this.m;
  5170. };
  5171. /**
  5172. * Returns the matrix as a Float32Array
  5173. * @returns the matrix underlying array.
  5174. */
  5175. Matrix.prototype.asArray = function () {
  5176. return this.toArray();
  5177. };
  5178. /**
  5179. * Inverts the current matrix in place
  5180. * @returns the current inverted matrix
  5181. */
  5182. Matrix.prototype.invert = function () {
  5183. this.invertToRef(this);
  5184. return this;
  5185. };
  5186. /**
  5187. * Sets all the matrix elements to zero
  5188. * @returns the current matrix
  5189. */
  5190. Matrix.prototype.reset = function () {
  5191. for (var index = 0; index < 16; index++) {
  5192. this.m[index] = 0.0;
  5193. }
  5194. this._markAsUpdated();
  5195. return this;
  5196. };
  5197. /**
  5198. * Adds the current matrix with a second one
  5199. * @param other defines the matrix to add
  5200. * @returns a new matrix as the addition of the current matrix and the given one
  5201. */
  5202. Matrix.prototype.add = function (other) {
  5203. var result = new Matrix();
  5204. this.addToRef(other, result);
  5205. return result;
  5206. };
  5207. /**
  5208. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5209. * @param other defines the matrix to add
  5210. * @param result defines the target matrix
  5211. * @returns the current matrix
  5212. */
  5213. Matrix.prototype.addToRef = function (other, result) {
  5214. for (var index = 0; index < 16; index++) {
  5215. result.m[index] = this.m[index] + other.m[index];
  5216. }
  5217. result._markAsUpdated();
  5218. return this;
  5219. };
  5220. /**
  5221. * Adds in place the given matrix to the current matrix
  5222. * @param other defines the second operand
  5223. * @returns the current updated matrix
  5224. */
  5225. Matrix.prototype.addToSelf = function (other) {
  5226. for (var index = 0; index < 16; index++) {
  5227. this.m[index] += other.m[index];
  5228. }
  5229. this._markAsUpdated();
  5230. return this;
  5231. };
  5232. /**
  5233. * Sets the given matrix to the current inverted Matrix
  5234. * @param other defines the target matrix
  5235. * @returns the unmodified current matrix
  5236. */
  5237. Matrix.prototype.invertToRef = function (other) {
  5238. var l1 = this.m[0];
  5239. var l2 = this.m[1];
  5240. var l3 = this.m[2];
  5241. var l4 = this.m[3];
  5242. var l5 = this.m[4];
  5243. var l6 = this.m[5];
  5244. var l7 = this.m[6];
  5245. var l8 = this.m[7];
  5246. var l9 = this.m[8];
  5247. var l10 = this.m[9];
  5248. var l11 = this.m[10];
  5249. var l12 = this.m[11];
  5250. var l13 = this.m[12];
  5251. var l14 = this.m[13];
  5252. var l15 = this.m[14];
  5253. var l16 = this.m[15];
  5254. var l17 = (l11 * l16) - (l12 * l15);
  5255. var l18 = (l10 * l16) - (l12 * l14);
  5256. var l19 = (l10 * l15) - (l11 * l14);
  5257. var l20 = (l9 * l16) - (l12 * l13);
  5258. var l21 = (l9 * l15) - (l11 * l13);
  5259. var l22 = (l9 * l14) - (l10 * l13);
  5260. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5261. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5262. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5263. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5264. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5265. var l28 = (l7 * l16) - (l8 * l15);
  5266. var l29 = (l6 * l16) - (l8 * l14);
  5267. var l30 = (l6 * l15) - (l7 * l14);
  5268. var l31 = (l5 * l16) - (l8 * l13);
  5269. var l32 = (l5 * l15) - (l7 * l13);
  5270. var l33 = (l5 * l14) - (l6 * l13);
  5271. var l34 = (l7 * l12) - (l8 * l11);
  5272. var l35 = (l6 * l12) - (l8 * l10);
  5273. var l36 = (l6 * l11) - (l7 * l10);
  5274. var l37 = (l5 * l12) - (l8 * l9);
  5275. var l38 = (l5 * l11) - (l7 * l9);
  5276. var l39 = (l5 * l10) - (l6 * l9);
  5277. other.m[0] = l23 * l27;
  5278. other.m[4] = l24 * l27;
  5279. other.m[8] = l25 * l27;
  5280. other.m[12] = l26 * l27;
  5281. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5282. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5283. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5284. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5285. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5286. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5287. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5288. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5289. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5290. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5291. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5292. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5293. other._markAsUpdated();
  5294. return this;
  5295. };
  5296. /**
  5297. * Inserts the translation vector (using 3 floats) in the current matrix
  5298. * @param x defines the 1st component of the translation
  5299. * @param y defines the 2nd component of the translation
  5300. * @param z defines the 3rd component of the translation
  5301. * @returns the current updated matrix
  5302. */
  5303. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5304. this.m[12] = x;
  5305. this.m[13] = y;
  5306. this.m[14] = z;
  5307. this._markAsUpdated();
  5308. return this;
  5309. };
  5310. /**
  5311. * Inserts the translation vector in the current matrix
  5312. * @param vector3 defines the translation to insert
  5313. * @returns the current updated matrix
  5314. */
  5315. Matrix.prototype.setTranslation = function (vector3) {
  5316. this.m[12] = vector3.x;
  5317. this.m[13] = vector3.y;
  5318. this.m[14] = vector3.z;
  5319. this._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Gets the translation value of the current matrix
  5324. * @returns a new Vector3 as the extracted translation from the matrix
  5325. */
  5326. Matrix.prototype.getTranslation = function () {
  5327. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5328. };
  5329. /**
  5330. * Fill a Vector3 with the extracted translation from the matrix
  5331. * @param result defines the Vector3 where to store the translation
  5332. * @returns the current matrix
  5333. */
  5334. Matrix.prototype.getTranslationToRef = function (result) {
  5335. result.x = this.m[12];
  5336. result.y = this.m[13];
  5337. result.z = this.m[14];
  5338. return this;
  5339. };
  5340. /**
  5341. * Remove rotation and scaling part from the matrix
  5342. * @returns the updated matrix
  5343. */
  5344. Matrix.prototype.removeRotationAndScaling = function () {
  5345. this.setRowFromFloats(0, 1, 0, 0, 0);
  5346. this.setRowFromFloats(1, 0, 1, 0, 0);
  5347. this.setRowFromFloats(2, 0, 0, 1, 0);
  5348. return this;
  5349. };
  5350. /**
  5351. * Multiply two matrices
  5352. * @param other defines the second operand
  5353. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5354. */
  5355. Matrix.prototype.multiply = function (other) {
  5356. var result = new Matrix();
  5357. this.multiplyToRef(other, result);
  5358. return result;
  5359. };
  5360. /**
  5361. * Copy the current matrix from the given one
  5362. * @param other defines the source matrix
  5363. * @returns the current updated matrix
  5364. */
  5365. Matrix.prototype.copyFrom = function (other) {
  5366. for (var index = 0; index < 16; index++) {
  5367. this.m[index] = other.m[index];
  5368. }
  5369. this._markAsUpdated();
  5370. return this;
  5371. };
  5372. /**
  5373. * Populates the given array from the starting index with the current matrix values
  5374. * @param array defines the target array
  5375. * @param offset defines the offset in the target array where to start storing values
  5376. * @returns the current matrix
  5377. */
  5378. Matrix.prototype.copyToArray = function (array, offset) {
  5379. if (offset === void 0) { offset = 0; }
  5380. for (var index = 0; index < 16; index++) {
  5381. array[offset + index] = this.m[index];
  5382. }
  5383. return this;
  5384. };
  5385. /**
  5386. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5387. * @param other defines the second operand
  5388. * @param result defines the matrix where to store the multiplication
  5389. * @returns the current matrix
  5390. */
  5391. Matrix.prototype.multiplyToRef = function (other, result) {
  5392. this.multiplyToArray(other, result.m, 0);
  5393. result._markAsUpdated();
  5394. return this;
  5395. };
  5396. /**
  5397. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5398. * @param other defines the second operand
  5399. * @param result defines the array where to store the multiplication
  5400. * @param offset defines the offset in the target array where to start storing values
  5401. * @returns the current matrix
  5402. */
  5403. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5404. var tm0 = this.m[0];
  5405. var tm1 = this.m[1];
  5406. var tm2 = this.m[2];
  5407. var tm3 = this.m[3];
  5408. var tm4 = this.m[4];
  5409. var tm5 = this.m[5];
  5410. var tm6 = this.m[6];
  5411. var tm7 = this.m[7];
  5412. var tm8 = this.m[8];
  5413. var tm9 = this.m[9];
  5414. var tm10 = this.m[10];
  5415. var tm11 = this.m[11];
  5416. var tm12 = this.m[12];
  5417. var tm13 = this.m[13];
  5418. var tm14 = this.m[14];
  5419. var tm15 = this.m[15];
  5420. var om0 = other.m[0];
  5421. var om1 = other.m[1];
  5422. var om2 = other.m[2];
  5423. var om3 = other.m[3];
  5424. var om4 = other.m[4];
  5425. var om5 = other.m[5];
  5426. var om6 = other.m[6];
  5427. var om7 = other.m[7];
  5428. var om8 = other.m[8];
  5429. var om9 = other.m[9];
  5430. var om10 = other.m[10];
  5431. var om11 = other.m[11];
  5432. var om12 = other.m[12];
  5433. var om13 = other.m[13];
  5434. var om14 = other.m[14];
  5435. var om15 = other.m[15];
  5436. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5437. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5438. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5439. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5440. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5441. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5442. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5443. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5444. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5445. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5446. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5447. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5448. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5449. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5450. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5451. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5452. return this;
  5453. };
  5454. /**
  5455. * Check equality between this matrix and a second one
  5456. * @param value defines the second matrix to compare
  5457. * @returns true is the current matrix and the given one values are strictly equal
  5458. */
  5459. Matrix.prototype.equals = function (value) {
  5460. return value &&
  5461. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5462. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5463. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5464. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5465. };
  5466. /**
  5467. * Clone the current matrix
  5468. * @returns a new matrix from the current matrix
  5469. */
  5470. Matrix.prototype.clone = function () {
  5471. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5472. };
  5473. /**
  5474. * Returns the name of the current matrix class
  5475. * @returns the string "Matrix"
  5476. */
  5477. Matrix.prototype.getClassName = function () {
  5478. return "Matrix";
  5479. };
  5480. /**
  5481. * Gets the hash code of the current matrix
  5482. * @returns the hash code
  5483. */
  5484. Matrix.prototype.getHashCode = function () {
  5485. var hash = this.m[0] || 0;
  5486. for (var i = 1; i < 16; i++) {
  5487. hash = (hash * 397) ^ (this.m[i] || 0);
  5488. }
  5489. return hash;
  5490. };
  5491. /**
  5492. * Decomposes the current Matrix into a translation, rotation and scaling components
  5493. * @param scale defines the scale vector3 given as a reference to update
  5494. * @param rotation defines the rotation quaternion given as a reference to update
  5495. * @param translation defines the translation vector3 given as a reference to update
  5496. * @returns true if operation was successful
  5497. */
  5498. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5499. if (translation) {
  5500. translation.x = this.m[12];
  5501. translation.y = this.m[13];
  5502. translation.z = this.m[14];
  5503. }
  5504. scale = scale || MathTmp.Vector3[0];
  5505. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5506. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5507. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5508. if (this.determinant() <= 0) {
  5509. scale.y *= -1;
  5510. }
  5511. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5512. if (rotation) {
  5513. rotation.x = 0;
  5514. rotation.y = 0;
  5515. rotation.z = 0;
  5516. rotation.w = 1;
  5517. }
  5518. return false;
  5519. }
  5520. if (rotation) {
  5521. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5522. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5523. }
  5524. return true;
  5525. };
  5526. /**
  5527. * Gets specific row of the matrix
  5528. * @param index defines the number of the row to get
  5529. * @returns the index-th row of the current matrix as a new Vector4
  5530. */
  5531. Matrix.prototype.getRow = function (index) {
  5532. if (index < 0 || index > 3) {
  5533. return null;
  5534. }
  5535. var i = index * 4;
  5536. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5537. };
  5538. /**
  5539. * Sets the index-th row of the current matrix to the vector4 values
  5540. * @param index defines the number of the row to set
  5541. * @param row defines the target vector4
  5542. * @returns the updated current matrix
  5543. */
  5544. Matrix.prototype.setRow = function (index, row) {
  5545. if (index < 0 || index > 3) {
  5546. return this;
  5547. }
  5548. var i = index * 4;
  5549. this.m[i + 0] = row.x;
  5550. this.m[i + 1] = row.y;
  5551. this.m[i + 2] = row.z;
  5552. this.m[i + 3] = row.w;
  5553. this._markAsUpdated();
  5554. return this;
  5555. };
  5556. /**
  5557. * Compute the transpose of the matrix
  5558. * @returns the new transposed matrix
  5559. */
  5560. Matrix.prototype.transpose = function () {
  5561. return Matrix.Transpose(this);
  5562. };
  5563. /**
  5564. * Compute the transpose of the matrix and store it in a given matrix
  5565. * @param result defines the target matrix
  5566. * @returns the current matrix
  5567. */
  5568. Matrix.prototype.transposeToRef = function (result) {
  5569. Matrix.TransposeToRef(this, result);
  5570. return this;
  5571. };
  5572. /**
  5573. * Sets the index-th row of the current matrix with the given 4 x float values
  5574. * @param index defines the row index
  5575. * @param x defines the x component to set
  5576. * @param y defines the y component to set
  5577. * @param z defines the z component to set
  5578. * @param w defines the w component to set
  5579. * @returns the updated current matrix
  5580. */
  5581. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5582. if (index < 0 || index > 3) {
  5583. return this;
  5584. }
  5585. var i = index * 4;
  5586. this.m[i + 0] = x;
  5587. this.m[i + 1] = y;
  5588. this.m[i + 2] = z;
  5589. this.m[i + 3] = w;
  5590. this._markAsUpdated();
  5591. return this;
  5592. };
  5593. /**
  5594. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5595. * @param scale defines the scale factor
  5596. * @returns a new matrix
  5597. */
  5598. Matrix.prototype.scale = function (scale) {
  5599. var result = new Matrix();
  5600. this.scaleToRef(scale, result);
  5601. return result;
  5602. };
  5603. /**
  5604. * Scale the current matrix values by a factor to a given result matrix
  5605. * @param scale defines the scale factor
  5606. * @param result defines the matrix to store the result
  5607. * @returns the current matrix
  5608. */
  5609. Matrix.prototype.scaleToRef = function (scale, result) {
  5610. for (var index = 0; index < 16; index++) {
  5611. result.m[index] = this.m[index] * scale;
  5612. }
  5613. result._markAsUpdated();
  5614. return this;
  5615. };
  5616. /**
  5617. * Scale the current matrix values by a factor and add the result to a given matrix
  5618. * @param scale defines the scale factor
  5619. * @param result defines the Matrix to store the result
  5620. * @returns the current matrix
  5621. */
  5622. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5623. for (var index = 0; index < 16; index++) {
  5624. result.m[index] += this.m[index] * scale;
  5625. }
  5626. result._markAsUpdated();
  5627. return this;
  5628. };
  5629. /**
  5630. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5631. * @param ref matrix to store the result
  5632. */
  5633. Matrix.prototype.toNormalMatrix = function (ref) {
  5634. this.invertToRef(ref);
  5635. ref.transpose();
  5636. var m = ref.m;
  5637. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5638. };
  5639. /**
  5640. * Gets only rotation part of the current matrix
  5641. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5642. */
  5643. Matrix.prototype.getRotationMatrix = function () {
  5644. var result = Matrix.Identity();
  5645. this.getRotationMatrixToRef(result);
  5646. return result;
  5647. };
  5648. /**
  5649. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5650. * @param result defines the target matrix to store data to
  5651. * @returns the current matrix
  5652. */
  5653. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5654. var m = this.m;
  5655. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5656. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5657. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5658. if (this.determinant() <= 0) {
  5659. sy *= -1;
  5660. }
  5661. if (sx === 0 || sy === 0 || sz === 0) {
  5662. Matrix.IdentityToRef(result);
  5663. }
  5664. else {
  5665. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5666. }
  5667. return this;
  5668. };
  5669. // Statics
  5670. /**
  5671. * Creates a matrix from an array
  5672. * @param array defines the source array
  5673. * @param offset defines an offset in the source array
  5674. * @returns a new Matrix set from the starting index of the given array
  5675. */
  5676. Matrix.FromArray = function (array, offset) {
  5677. var result = new Matrix();
  5678. if (!offset) {
  5679. offset = 0;
  5680. }
  5681. Matrix.FromArrayToRef(array, offset, result);
  5682. return result;
  5683. };
  5684. /**
  5685. * Copy the content of an array into a given matrix
  5686. * @param array defines the source array
  5687. * @param offset defines an offset in the source array
  5688. * @param result defines the target matrix
  5689. */
  5690. Matrix.FromArrayToRef = function (array, offset, result) {
  5691. for (var index = 0; index < 16; index++) {
  5692. result.m[index] = array[index + offset];
  5693. }
  5694. result._markAsUpdated();
  5695. };
  5696. /**
  5697. * Stores an array into a matrix after having multiplied each component by a given factor
  5698. * @param array defines the source array
  5699. * @param offset defines the offset in the source array
  5700. * @param scale defines the scaling factor
  5701. * @param result defines the target matrix
  5702. */
  5703. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5704. for (var index = 0; index < 16; index++) {
  5705. result.m[index] = array[index + offset] * scale;
  5706. }
  5707. result._markAsUpdated();
  5708. };
  5709. /**
  5710. * Stores a list of values (16) inside a given matrix
  5711. * @param initialM11 defines 1st value of 1st row
  5712. * @param initialM12 defines 2nd value of 1st row
  5713. * @param initialM13 defines 3rd value of 1st row
  5714. * @param initialM14 defines 4th value of 1st row
  5715. * @param initialM21 defines 1st value of 2nd row
  5716. * @param initialM22 defines 2nd value of 2nd row
  5717. * @param initialM23 defines 3rd value of 2nd row
  5718. * @param initialM24 defines 4th value of 2nd row
  5719. * @param initialM31 defines 1st value of 3rd row
  5720. * @param initialM32 defines 2nd value of 3rd row
  5721. * @param initialM33 defines 3rd value of 3rd row
  5722. * @param initialM34 defines 4th value of 3rd row
  5723. * @param initialM41 defines 1st value of 4th row
  5724. * @param initialM42 defines 2nd value of 4th row
  5725. * @param initialM43 defines 3rd value of 4th row
  5726. * @param initialM44 defines 4th value of 4th row
  5727. * @param result defines the target matrix
  5728. */
  5729. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5730. result.m[0] = initialM11;
  5731. result.m[1] = initialM12;
  5732. result.m[2] = initialM13;
  5733. result.m[3] = initialM14;
  5734. result.m[4] = initialM21;
  5735. result.m[5] = initialM22;
  5736. result.m[6] = initialM23;
  5737. result.m[7] = initialM24;
  5738. result.m[8] = initialM31;
  5739. result.m[9] = initialM32;
  5740. result.m[10] = initialM33;
  5741. result.m[11] = initialM34;
  5742. result.m[12] = initialM41;
  5743. result.m[13] = initialM42;
  5744. result.m[14] = initialM43;
  5745. result.m[15] = initialM44;
  5746. result._markAsUpdated();
  5747. };
  5748. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5749. /**
  5750. * Gets an identity matrix that must not be updated
  5751. */
  5752. get: function () {
  5753. return Matrix._identityReadOnly;
  5754. },
  5755. enumerable: true,
  5756. configurable: true
  5757. });
  5758. /**
  5759. * Creates new matrix from a list of values (16)
  5760. * @param initialM11 defines 1st value of 1st row
  5761. * @param initialM12 defines 2nd value of 1st row
  5762. * @param initialM13 defines 3rd value of 1st row
  5763. * @param initialM14 defines 4th value of 1st row
  5764. * @param initialM21 defines 1st value of 2nd row
  5765. * @param initialM22 defines 2nd value of 2nd row
  5766. * @param initialM23 defines 3rd value of 2nd row
  5767. * @param initialM24 defines 4th value of 2nd row
  5768. * @param initialM31 defines 1st value of 3rd row
  5769. * @param initialM32 defines 2nd value of 3rd row
  5770. * @param initialM33 defines 3rd value of 3rd row
  5771. * @param initialM34 defines 4th value of 3rd row
  5772. * @param initialM41 defines 1st value of 4th row
  5773. * @param initialM42 defines 2nd value of 4th row
  5774. * @param initialM43 defines 3rd value of 4th row
  5775. * @param initialM44 defines 4th value of 4th row
  5776. * @returns the new matrix
  5777. */
  5778. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5779. var result = new Matrix();
  5780. result.m[0] = initialM11;
  5781. result.m[1] = initialM12;
  5782. result.m[2] = initialM13;
  5783. result.m[3] = initialM14;
  5784. result.m[4] = initialM21;
  5785. result.m[5] = initialM22;
  5786. result.m[6] = initialM23;
  5787. result.m[7] = initialM24;
  5788. result.m[8] = initialM31;
  5789. result.m[9] = initialM32;
  5790. result.m[10] = initialM33;
  5791. result.m[11] = initialM34;
  5792. result.m[12] = initialM41;
  5793. result.m[13] = initialM42;
  5794. result.m[14] = initialM43;
  5795. result.m[15] = initialM44;
  5796. return result;
  5797. };
  5798. /**
  5799. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5800. * @param scale defines the scale vector3
  5801. * @param rotation defines the rotation quaternion
  5802. * @param translation defines the translation vector3
  5803. * @returns a new matrix
  5804. */
  5805. Matrix.Compose = function (scale, rotation, translation) {
  5806. var result = Matrix.Identity();
  5807. Matrix.ComposeToRef(scale, rotation, translation, result);
  5808. return result;
  5809. };
  5810. /**
  5811. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5812. * @param scale defines the scale vector3
  5813. * @param rotation defines the rotation quaternion
  5814. * @param translation defines the translation vector3
  5815. * @param result defines the target matrix
  5816. */
  5817. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5818. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5819. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5820. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5821. result.setTranslation(translation);
  5822. };
  5823. /**
  5824. * Creates a new identity matrix
  5825. * @returns a new identity matrix
  5826. */
  5827. Matrix.Identity = function () {
  5828. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5829. };
  5830. /**
  5831. * Creates a new identity matrix and stores the result in a given matrix
  5832. * @param result defines the target matrix
  5833. */
  5834. Matrix.IdentityToRef = function (result) {
  5835. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5836. };
  5837. /**
  5838. * Creates a new zero matrix
  5839. * @returns a new zero matrix
  5840. */
  5841. Matrix.Zero = function () {
  5842. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5843. };
  5844. /**
  5845. * Creates a new rotation matrix for "angle" radians around the X axis
  5846. * @param angle defines the angle (in radians) to use
  5847. * @return the new matrix
  5848. */
  5849. Matrix.RotationX = function (angle) {
  5850. var result = new Matrix();
  5851. Matrix.RotationXToRef(angle, result);
  5852. return result;
  5853. };
  5854. /**
  5855. * Creates a new matrix as the invert of a given matrix
  5856. * @param source defines the source matrix
  5857. * @returns the new matrix
  5858. */
  5859. Matrix.Invert = function (source) {
  5860. var result = new Matrix();
  5861. source.invertToRef(result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5866. * @param angle defines the angle (in radians) to use
  5867. * @param result defines the target matrix
  5868. */
  5869. Matrix.RotationXToRef = function (angle, result) {
  5870. var s = Math.sin(angle);
  5871. var c = Math.cos(angle);
  5872. result.m[0] = 1.0;
  5873. result.m[15] = 1.0;
  5874. result.m[5] = c;
  5875. result.m[10] = c;
  5876. result.m[9] = -s;
  5877. result.m[6] = s;
  5878. result.m[1] = 0.0;
  5879. result.m[2] = 0.0;
  5880. result.m[3] = 0.0;
  5881. result.m[4] = 0.0;
  5882. result.m[7] = 0.0;
  5883. result.m[8] = 0.0;
  5884. result.m[11] = 0.0;
  5885. result.m[12] = 0.0;
  5886. result.m[13] = 0.0;
  5887. result.m[14] = 0.0;
  5888. result._markAsUpdated();
  5889. };
  5890. /**
  5891. * Creates a new rotation matrix for "angle" radians around the Y axis
  5892. * @param angle defines the angle (in radians) to use
  5893. * @return the new matrix
  5894. */
  5895. Matrix.RotationY = function (angle) {
  5896. var result = new Matrix();
  5897. Matrix.RotationYToRef(angle, result);
  5898. return result;
  5899. };
  5900. /**
  5901. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5902. * @param angle defines the angle (in radians) to use
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.RotationYToRef = function (angle, result) {
  5906. var s = Math.sin(angle);
  5907. var c = Math.cos(angle);
  5908. result.m[5] = 1.0;
  5909. result.m[15] = 1.0;
  5910. result.m[0] = c;
  5911. result.m[2] = -s;
  5912. result.m[8] = s;
  5913. result.m[10] = c;
  5914. result.m[1] = 0.0;
  5915. result.m[3] = 0.0;
  5916. result.m[4] = 0.0;
  5917. result.m[6] = 0.0;
  5918. result.m[7] = 0.0;
  5919. result.m[9] = 0.0;
  5920. result.m[11] = 0.0;
  5921. result.m[12] = 0.0;
  5922. result.m[13] = 0.0;
  5923. result.m[14] = 0.0;
  5924. result._markAsUpdated();
  5925. };
  5926. /**
  5927. * Creates a new rotation matrix for "angle" radians around the Z axis
  5928. * @param angle defines the angle (in radians) to use
  5929. * @return the new matrix
  5930. */
  5931. Matrix.RotationZ = function (angle) {
  5932. var result = new Matrix();
  5933. Matrix.RotationZToRef(angle, result);
  5934. return result;
  5935. };
  5936. /**
  5937. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5938. * @param angle defines the angle (in radians) to use
  5939. * @param result defines the target matrix
  5940. */
  5941. Matrix.RotationZToRef = function (angle, result) {
  5942. var s = Math.sin(angle);
  5943. var c = Math.cos(angle);
  5944. result.m[10] = 1.0;
  5945. result.m[15] = 1.0;
  5946. result.m[0] = c;
  5947. result.m[1] = s;
  5948. result.m[4] = -s;
  5949. result.m[5] = c;
  5950. result.m[2] = 0.0;
  5951. result.m[3] = 0.0;
  5952. result.m[6] = 0.0;
  5953. result.m[7] = 0.0;
  5954. result.m[8] = 0.0;
  5955. result.m[9] = 0.0;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result._markAsUpdated();
  5961. };
  5962. /**
  5963. * Creates a new rotation matrix for "angle" radians around the given axis
  5964. * @param axis defines the axis to use
  5965. * @param angle defines the angle (in radians) to use
  5966. * @return the new matrix
  5967. */
  5968. Matrix.RotationAxis = function (axis, angle) {
  5969. var result = Matrix.Zero();
  5970. Matrix.RotationAxisToRef(axis, angle, result);
  5971. return result;
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5975. * @param axis defines the axis to use
  5976. * @param angle defines the angle (in radians) to use
  5977. * @param result defines the target matrix
  5978. */
  5979. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5980. var s = Math.sin(-angle);
  5981. var c = Math.cos(-angle);
  5982. var c1 = 1 - c;
  5983. axis.normalize();
  5984. result.m[0] = (axis.x * axis.x) * c1 + c;
  5985. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5986. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5987. result.m[3] = 0.0;
  5988. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5989. result.m[5] = (axis.y * axis.y) * c1 + c;
  5990. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5991. result.m[7] = 0.0;
  5992. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5993. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5994. result.m[10] = (axis.z * axis.z) * c1 + c;
  5995. result.m[11] = 0.0;
  5996. result.m[15] = 1.0;
  5997. result._markAsUpdated();
  5998. };
  5999. /**
  6000. * Creates a rotation matrix
  6001. * @param yaw defines the yaw angle in radians (Y axis)
  6002. * @param pitch defines the pitch angle in radians (X axis)
  6003. * @param roll defines the roll angle in radians (X axis)
  6004. * @returns the new rotation matrix
  6005. */
  6006. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6007. var result = new Matrix();
  6008. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6009. return result;
  6010. };
  6011. /**
  6012. * Creates a rotation matrix and stores it in a given matrix
  6013. * @param yaw defines the yaw angle in radians (Y axis)
  6014. * @param pitch defines the pitch angle in radians (X axis)
  6015. * @param roll defines the roll angle in radians (X axis)
  6016. * @param result defines the target matrix
  6017. */
  6018. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6019. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6020. this._tempQuaternion.toRotationMatrix(result);
  6021. };
  6022. /**
  6023. * Creates a scaling matrix
  6024. * @param x defines the scale factor on X axis
  6025. * @param y defines the scale factor on Y axis
  6026. * @param z defines the scale factor on Z axis
  6027. * @returns the new matrix
  6028. */
  6029. Matrix.Scaling = function (x, y, z) {
  6030. var result = Matrix.Zero();
  6031. Matrix.ScalingToRef(x, y, z, result);
  6032. return result;
  6033. };
  6034. /**
  6035. * Creates a scaling matrix and stores it in a given matrix
  6036. * @param x defines the scale factor on X axis
  6037. * @param y defines the scale factor on Y axis
  6038. * @param z defines the scale factor on Z axis
  6039. * @param result defines the target matrix
  6040. */
  6041. Matrix.ScalingToRef = function (x, y, z, result) {
  6042. result.m[0] = x;
  6043. result.m[1] = 0.0;
  6044. result.m[2] = 0.0;
  6045. result.m[3] = 0.0;
  6046. result.m[4] = 0.0;
  6047. result.m[5] = y;
  6048. result.m[6] = 0.0;
  6049. result.m[7] = 0.0;
  6050. result.m[8] = 0.0;
  6051. result.m[9] = 0.0;
  6052. result.m[10] = z;
  6053. result.m[11] = 0.0;
  6054. result.m[12] = 0.0;
  6055. result.m[13] = 0.0;
  6056. result.m[14] = 0.0;
  6057. result.m[15] = 1.0;
  6058. result._markAsUpdated();
  6059. };
  6060. /**
  6061. * Creates a translation matrix
  6062. * @param x defines the translation on X axis
  6063. * @param y defines the translation on Y axis
  6064. * @param z defines the translationon Z axis
  6065. * @returns the new matrix
  6066. */
  6067. Matrix.Translation = function (x, y, z) {
  6068. var result = Matrix.Identity();
  6069. Matrix.TranslationToRef(x, y, z, result);
  6070. return result;
  6071. };
  6072. /**
  6073. * Creates a translation matrix and stores it in a given matrix
  6074. * @param x defines the translation on X axis
  6075. * @param y defines the translation on Y axis
  6076. * @param z defines the translationon Z axis
  6077. * @param result defines the target matrix
  6078. */
  6079. Matrix.TranslationToRef = function (x, y, z, result) {
  6080. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6081. };
  6082. /**
  6083. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6084. * @param startValue defines the start value
  6085. * @param endValue defines the end value
  6086. * @param gradient defines the gradient factor
  6087. * @returns the new matrix
  6088. */
  6089. Matrix.Lerp = function (startValue, endValue, gradient) {
  6090. var result = Matrix.Zero();
  6091. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6092. return result;
  6093. };
  6094. /**
  6095. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6096. * @param startValue defines the start value
  6097. * @param endValue defines the end value
  6098. * @param gradient defines the gradient factor
  6099. * @param result defines the Matrix object where to store data
  6100. */
  6101. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6102. for (var index = 0; index < 16; index++) {
  6103. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6104. }
  6105. result._markAsUpdated();
  6106. };
  6107. /**
  6108. * Builds a new matrix whose values are computed by:
  6109. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6110. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6111. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6112. * @param startValue defines the first matrix
  6113. * @param endValue defines the second matrix
  6114. * @param gradient defines the gradient between the two matrices
  6115. * @returns the new matrix
  6116. */
  6117. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6118. var result = Matrix.Zero();
  6119. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6120. return result;
  6121. };
  6122. /**
  6123. * Update a matrix to values which are computed by:
  6124. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6125. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6126. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6127. * @param startValue defines the first matrix
  6128. * @param endValue defines the second matrix
  6129. * @param gradient defines the gradient between the two matrices
  6130. * @param result defines the target matrix
  6131. */
  6132. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6133. var startScale = MathTmp.Vector3[0];
  6134. var startRotation = MathTmp.Quaternion[0];
  6135. var startTranslation = MathTmp.Vector3[1];
  6136. startValue.decompose(startScale, startRotation, startTranslation);
  6137. var endScale = MathTmp.Vector3[2];
  6138. var endRotation = MathTmp.Quaternion[1];
  6139. var endTranslation = MathTmp.Vector3[3];
  6140. endValue.decompose(endScale, endRotation, endTranslation);
  6141. var resultScale = MathTmp.Vector3[4];
  6142. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6143. var resultRotation = MathTmp.Quaternion[2];
  6144. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6145. var resultTranslation = MathTmp.Vector3[5];
  6146. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6147. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6148. };
  6149. /**
  6150. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6151. * This function works in left handed mode
  6152. * @param eye defines the final position of the entity
  6153. * @param target defines where the entity should look at
  6154. * @param up defines the up vector for the entity
  6155. * @returns the new matrix
  6156. */
  6157. Matrix.LookAtLH = function (eye, target, up) {
  6158. var result = Matrix.Zero();
  6159. Matrix.LookAtLHToRef(eye, target, up, result);
  6160. return result;
  6161. };
  6162. /**
  6163. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6164. * This function works in left handed mode
  6165. * @param eye defines the final position of the entity
  6166. * @param target defines where the entity should look at
  6167. * @param up defines the up vector for the entity
  6168. * @param result defines the target matrix
  6169. */
  6170. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6171. // Z axis
  6172. target.subtractToRef(eye, this._zAxis);
  6173. this._zAxis.normalize();
  6174. // X axis
  6175. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6176. if (this._xAxis.lengthSquared() === 0) {
  6177. this._xAxis.x = 1.0;
  6178. }
  6179. else {
  6180. this._xAxis.normalize();
  6181. }
  6182. // Y axis
  6183. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6184. this._yAxis.normalize();
  6185. // Eye angles
  6186. var ex = -Vector3.Dot(this._xAxis, eye);
  6187. var ey = -Vector3.Dot(this._yAxis, eye);
  6188. var ez = -Vector3.Dot(this._zAxis, eye);
  6189. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6190. };
  6191. /**
  6192. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6193. * This function works in right handed mode
  6194. * @param eye defines the final position of the entity
  6195. * @param target defines where the entity should look at
  6196. * @param up defines the up vector for the entity
  6197. * @returns the new matrix
  6198. */
  6199. Matrix.LookAtRH = function (eye, target, up) {
  6200. var result = Matrix.Zero();
  6201. Matrix.LookAtRHToRef(eye, target, up, result);
  6202. return result;
  6203. };
  6204. /**
  6205. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6206. * This function works in right handed mode
  6207. * @param eye defines the final position of the entity
  6208. * @param target defines where the entity should look at
  6209. * @param up defines the up vector for the entity
  6210. * @param result defines the target matrix
  6211. */
  6212. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6213. // Z axis
  6214. eye.subtractToRef(target, this._zAxis);
  6215. this._zAxis.normalize();
  6216. // X axis
  6217. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6218. if (this._xAxis.lengthSquared() === 0) {
  6219. this._xAxis.x = 1.0;
  6220. }
  6221. else {
  6222. this._xAxis.normalize();
  6223. }
  6224. // Y axis
  6225. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6226. this._yAxis.normalize();
  6227. // Eye angles
  6228. var ex = -Vector3.Dot(this._xAxis, eye);
  6229. var ey = -Vector3.Dot(this._yAxis, eye);
  6230. var ez = -Vector3.Dot(this._zAxis, eye);
  6231. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6232. };
  6233. /**
  6234. * Create a left-handed orthographic projection matrix
  6235. * @param width defines the viewport width
  6236. * @param height defines the viewport height
  6237. * @param znear defines the near clip plane
  6238. * @param zfar defines the far clip plane
  6239. * @returns a new matrix as a left-handed orthographic projection matrix
  6240. */
  6241. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6242. var matrix = Matrix.Zero();
  6243. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6244. return matrix;
  6245. };
  6246. /**
  6247. * Store a left-handed orthographic projection to a given matrix
  6248. * @param width defines the viewport width
  6249. * @param height defines the viewport height
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @param result defines the target matrix
  6253. */
  6254. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6255. var n = znear;
  6256. var f = zfar;
  6257. var a = 2.0 / width;
  6258. var b = 2.0 / height;
  6259. var c = 2.0 / (f - n);
  6260. var d = -(f + n) / (f - n);
  6261. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6262. };
  6263. /**
  6264. * Create a left-handed orthographic projection matrix
  6265. * @param left defines the viewport left coordinate
  6266. * @param right defines the viewport right coordinate
  6267. * @param bottom defines the viewport bottom coordinate
  6268. * @param top defines the viewport top coordinate
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @returns a new matrix as a left-handed orthographic projection matrix
  6272. */
  6273. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6274. var matrix = Matrix.Zero();
  6275. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6276. return matrix;
  6277. };
  6278. /**
  6279. * Stores a left-handed orthographic projection into a given matrix
  6280. * @param left defines the viewport left coordinate
  6281. * @param right defines the viewport right coordinate
  6282. * @param bottom defines the viewport bottom coordinate
  6283. * @param top defines the viewport top coordinate
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @param result defines the target matrix
  6287. */
  6288. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6289. var n = znear;
  6290. var f = zfar;
  6291. var a = 2.0 / (right - left);
  6292. var b = 2.0 / (top - bottom);
  6293. var c = 2.0 / (f - n);
  6294. var d = -(f + n) / (f - n);
  6295. var i0 = (left + right) / (left - right);
  6296. var i1 = (top + bottom) / (bottom - top);
  6297. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6298. };
  6299. /**
  6300. * Creates a right-handed orthographic projection matrix
  6301. * @param left defines the viewport left coordinate
  6302. * @param right defines the viewport right coordinate
  6303. * @param bottom defines the viewport bottom coordinate
  6304. * @param top defines the viewport top coordinate
  6305. * @param znear defines the near clip plane
  6306. * @param zfar defines the far clip plane
  6307. * @returns a new matrix as a right-handed orthographic projection matrix
  6308. */
  6309. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6310. var matrix = Matrix.Zero();
  6311. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6312. return matrix;
  6313. };
  6314. /**
  6315. * Stores a right-handed orthographic projection into a given matrix
  6316. * @param left defines the viewport left coordinate
  6317. * @param right defines the viewport right coordinate
  6318. * @param bottom defines the viewport bottom coordinate
  6319. * @param top defines the viewport top coordinate
  6320. * @param znear defines the near clip plane
  6321. * @param zfar defines the far clip plane
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6325. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6326. result.m[10] *= -1.0;
  6327. };
  6328. /**
  6329. * Creates a left-handed perspective projection matrix
  6330. * @param width defines the viewport width
  6331. * @param height defines the viewport height
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @returns a new matrix as a left-handed perspective projection matrix
  6335. */
  6336. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6337. var matrix = Matrix.Zero();
  6338. var n = znear;
  6339. var f = zfar;
  6340. var a = 2.0 * n / width;
  6341. var b = 2.0 * n / height;
  6342. var c = (f + n) / (f - n);
  6343. var d = -2.0 * f * n / (f - n);
  6344. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6345. return matrix;
  6346. };
  6347. /**
  6348. * Creates a left-handed perspective projection matrix
  6349. * @param fov defines the horizontal field of view
  6350. * @param aspect defines the aspect ratio
  6351. * @param znear defines the near clip plane
  6352. * @param zfar defines the far clip plane
  6353. * @returns a new matrix as a left-handed perspective projection matrix
  6354. */
  6355. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6356. var matrix = Matrix.Zero();
  6357. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6358. return matrix;
  6359. };
  6360. /**
  6361. * Stores a left-handed perspective projection into a given matrix
  6362. * @param fov defines the horizontal field of view
  6363. * @param aspect defines the aspect ratio
  6364. * @param znear defines the near clip plane
  6365. * @param zfar defines the far clip plane
  6366. * @param result defines the target matrix
  6367. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6368. */
  6369. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6370. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6371. var n = znear;
  6372. var f = zfar;
  6373. var t = 1.0 / (Math.tan(fov * 0.5));
  6374. var a = isVerticalFovFixed ? (t / aspect) : t;
  6375. var b = isVerticalFovFixed ? t : (t * aspect);
  6376. var c = (f + n) / (f - n);
  6377. var d = -2.0 * f * n / (f - n);
  6378. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6379. };
  6380. /**
  6381. * Creates a right-handed perspective projection matrix
  6382. * @param fov defines the horizontal field of view
  6383. * @param aspect defines the aspect ratio
  6384. * @param znear defines the near clip plane
  6385. * @param zfar defines the far clip plane
  6386. * @returns a new matrix as a right-handed perspective projection matrix
  6387. */
  6388. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6389. var matrix = Matrix.Zero();
  6390. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6391. return matrix;
  6392. };
  6393. /**
  6394. * Stores a right-handed perspective projection into a given matrix
  6395. * @param fov defines the horizontal field of view
  6396. * @param aspect defines the aspect ratio
  6397. * @param znear defines the near clip plane
  6398. * @param zfar defines the far clip plane
  6399. * @param result defines the target matrix
  6400. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6401. */
  6402. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6403. //alternatively this could be expressed as:
  6404. // m = PerspectiveFovLHToRef
  6405. // m[10] *= -1.0;
  6406. // m[11] *= -1.0;
  6407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6408. var n = znear;
  6409. var f = zfar;
  6410. var t = 1.0 / (Math.tan(fov * 0.5));
  6411. var a = isVerticalFovFixed ? (t / aspect) : t;
  6412. var b = isVerticalFovFixed ? t : (t * aspect);
  6413. var c = -(f + n) / (f - n);
  6414. var d = -2 * f * n / (f - n);
  6415. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6416. };
  6417. /**
  6418. * Stores a perspective projection for WebVR info a given matrix
  6419. * @param fov defines the field of view
  6420. * @param znear defines the near clip plane
  6421. * @param zfar defines the far clip plane
  6422. * @param result defines the target matrix
  6423. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6424. */
  6425. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6426. if (rightHanded === void 0) { rightHanded = false; }
  6427. var rightHandedFactor = rightHanded ? -1 : 1;
  6428. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6429. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6430. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6431. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6432. var xScale = 2.0 / (leftTan + rightTan);
  6433. var yScale = 2.0 / (upTan + downTan);
  6434. result.m[0] = xScale;
  6435. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6436. result.m[5] = yScale;
  6437. result.m[6] = result.m[7] = 0.0;
  6438. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6439. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6440. result.m[10] = -zfar / (znear - zfar);
  6441. result.m[11] = 1.0 * rightHandedFactor;
  6442. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6443. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6444. result._markAsUpdated();
  6445. };
  6446. /**
  6447. * Computes a complete transformation matrix
  6448. * @param viewport defines the viewport to use
  6449. * @param world defines the world matrix
  6450. * @param view defines the view matrix
  6451. * @param projection defines the projection matrix
  6452. * @param zmin defines the near clip plane
  6453. * @param zmax defines the far clip plane
  6454. * @returns the transformation matrix
  6455. */
  6456. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6457. var cw = viewport.width;
  6458. var ch = viewport.height;
  6459. var cx = viewport.x;
  6460. var cy = viewport.y;
  6461. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6462. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6463. };
  6464. /**
  6465. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6466. * @param matrix defines the matrix to use
  6467. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6468. */
  6469. Matrix.GetAsMatrix2x2 = function (matrix) {
  6470. return new Float32Array([
  6471. matrix.m[0], matrix.m[1],
  6472. matrix.m[4], matrix.m[5]
  6473. ]);
  6474. };
  6475. /**
  6476. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6477. * @param matrix defines the matrix to use
  6478. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6479. */
  6480. Matrix.GetAsMatrix3x3 = function (matrix) {
  6481. return new Float32Array([
  6482. matrix.m[0], matrix.m[1], matrix.m[2],
  6483. matrix.m[4], matrix.m[5], matrix.m[6],
  6484. matrix.m[8], matrix.m[9], matrix.m[10]
  6485. ]);
  6486. };
  6487. /**
  6488. * Compute the transpose of a given matrix
  6489. * @param matrix defines the matrix to transpose
  6490. * @returns the new matrix
  6491. */
  6492. Matrix.Transpose = function (matrix) {
  6493. var result = new Matrix();
  6494. Matrix.TransposeToRef(matrix, result);
  6495. return result;
  6496. };
  6497. /**
  6498. * Compute the transpose of a matrix and store it in a target matrix
  6499. * @param matrix defines the matrix to transpose
  6500. * @param result defines the target matrix
  6501. */
  6502. Matrix.TransposeToRef = function (matrix, result) {
  6503. result.m[0] = matrix.m[0];
  6504. result.m[1] = matrix.m[4];
  6505. result.m[2] = matrix.m[8];
  6506. result.m[3] = matrix.m[12];
  6507. result.m[4] = matrix.m[1];
  6508. result.m[5] = matrix.m[5];
  6509. result.m[6] = matrix.m[9];
  6510. result.m[7] = matrix.m[13];
  6511. result.m[8] = matrix.m[2];
  6512. result.m[9] = matrix.m[6];
  6513. result.m[10] = matrix.m[10];
  6514. result.m[11] = matrix.m[14];
  6515. result.m[12] = matrix.m[3];
  6516. result.m[13] = matrix.m[7];
  6517. result.m[14] = matrix.m[11];
  6518. result.m[15] = matrix.m[15];
  6519. };
  6520. /**
  6521. * Computes a reflection matrix from a plane
  6522. * @param plane defines the reflection plane
  6523. * @returns a new matrix
  6524. */
  6525. Matrix.Reflection = function (plane) {
  6526. var matrix = new Matrix();
  6527. Matrix.ReflectionToRef(plane, matrix);
  6528. return matrix;
  6529. };
  6530. /**
  6531. * Computes a reflection matrix from a plane
  6532. * @param plane defines the reflection plane
  6533. * @param result defines the target matrix
  6534. */
  6535. Matrix.ReflectionToRef = function (plane, result) {
  6536. plane.normalize();
  6537. var x = plane.normal.x;
  6538. var y = plane.normal.y;
  6539. var z = plane.normal.z;
  6540. var temp = -2 * x;
  6541. var temp2 = -2 * y;
  6542. var temp3 = -2 * z;
  6543. result.m[0] = (temp * x) + 1;
  6544. result.m[1] = temp2 * x;
  6545. result.m[2] = temp3 * x;
  6546. result.m[3] = 0.0;
  6547. result.m[4] = temp * y;
  6548. result.m[5] = (temp2 * y) + 1;
  6549. result.m[6] = temp3 * y;
  6550. result.m[7] = 0.0;
  6551. result.m[8] = temp * z;
  6552. result.m[9] = temp2 * z;
  6553. result.m[10] = (temp3 * z) + 1;
  6554. result.m[11] = 0.0;
  6555. result.m[12] = temp * plane.d;
  6556. result.m[13] = temp2 * plane.d;
  6557. result.m[14] = temp3 * plane.d;
  6558. result.m[15] = 1.0;
  6559. result._markAsUpdated();
  6560. };
  6561. /**
  6562. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6563. * @param xaxis defines the value of the 1st axis
  6564. * @param yaxis defines the value of the 2nd axis
  6565. * @param zaxis defines the value of the 3rd axis
  6566. * @param result defines the target matrix
  6567. */
  6568. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6569. result.m[0] = xaxis.x;
  6570. result.m[1] = xaxis.y;
  6571. result.m[2] = xaxis.z;
  6572. result.m[3] = 0.0;
  6573. result.m[4] = yaxis.x;
  6574. result.m[5] = yaxis.y;
  6575. result.m[6] = yaxis.z;
  6576. result.m[7] = 0.0;
  6577. result.m[8] = zaxis.x;
  6578. result.m[9] = zaxis.y;
  6579. result.m[10] = zaxis.z;
  6580. result.m[11] = 0.0;
  6581. result.m[12] = 0.0;
  6582. result.m[13] = 0.0;
  6583. result.m[14] = 0.0;
  6584. result.m[15] = 1.0;
  6585. result._markAsUpdated();
  6586. };
  6587. /**
  6588. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6589. * @param quat defines the quaternion to use
  6590. * @param result defines the target matrix
  6591. */
  6592. Matrix.FromQuaternionToRef = function (quat, result) {
  6593. var xx = quat.x * quat.x;
  6594. var yy = quat.y * quat.y;
  6595. var zz = quat.z * quat.z;
  6596. var xy = quat.x * quat.y;
  6597. var zw = quat.z * quat.w;
  6598. var zx = quat.z * quat.x;
  6599. var yw = quat.y * quat.w;
  6600. var yz = quat.y * quat.z;
  6601. var xw = quat.x * quat.w;
  6602. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6603. result.m[1] = 2.0 * (xy + zw);
  6604. result.m[2] = 2.0 * (zx - yw);
  6605. result.m[3] = 0.0;
  6606. result.m[4] = 2.0 * (xy - zw);
  6607. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6608. result.m[6] = 2.0 * (yz + xw);
  6609. result.m[7] = 0.0;
  6610. result.m[8] = 2.0 * (zx + yw);
  6611. result.m[9] = 2.0 * (yz - xw);
  6612. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6613. result.m[11] = 0.0;
  6614. result.m[12] = 0.0;
  6615. result.m[13] = 0.0;
  6616. result.m[14] = 0.0;
  6617. result.m[15] = 1.0;
  6618. result._markAsUpdated();
  6619. };
  6620. Matrix._tempQuaternion = new Quaternion();
  6621. Matrix._xAxis = Vector3.Zero();
  6622. Matrix._yAxis = Vector3.Zero();
  6623. Matrix._zAxis = Vector3.Zero();
  6624. Matrix._updateFlagSeed = 0;
  6625. Matrix._identityReadOnly = Matrix.Identity();
  6626. return Matrix;
  6627. }());
  6628. BABYLON.Matrix = Matrix;
  6629. var Plane = /** @class */ (function () {
  6630. /**
  6631. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6632. */
  6633. function Plane(a, b, c, d) {
  6634. this.normal = new Vector3(a, b, c);
  6635. this.d = d;
  6636. }
  6637. /**
  6638. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6639. */
  6640. Plane.prototype.asArray = function () {
  6641. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6642. };
  6643. // Methods
  6644. /**
  6645. * Returns a new plane copied from the current Plane.
  6646. */
  6647. Plane.prototype.clone = function () {
  6648. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6649. };
  6650. /**
  6651. * Returns the string "Plane".
  6652. */
  6653. Plane.prototype.getClassName = function () {
  6654. return "Plane";
  6655. };
  6656. /**
  6657. * Returns the Plane hash code.
  6658. */
  6659. Plane.prototype.getHashCode = function () {
  6660. var hash = this.normal.getHashCode();
  6661. hash = (hash * 397) ^ (this.d || 0);
  6662. return hash;
  6663. };
  6664. /**
  6665. * Normalize the current Plane in place.
  6666. * Returns the updated Plane.
  6667. */
  6668. Plane.prototype.normalize = function () {
  6669. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6670. var magnitude = 0.0;
  6671. if (norm !== 0) {
  6672. magnitude = 1.0 / norm;
  6673. }
  6674. this.normal.x *= magnitude;
  6675. this.normal.y *= magnitude;
  6676. this.normal.z *= magnitude;
  6677. this.d *= magnitude;
  6678. return this;
  6679. };
  6680. /**
  6681. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6682. */
  6683. Plane.prototype.transform = function (transformation) {
  6684. var transposedMatrix = Matrix.Transpose(transformation);
  6685. var x = this.normal.x;
  6686. var y = this.normal.y;
  6687. var z = this.normal.z;
  6688. var d = this.d;
  6689. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6690. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6691. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6692. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6693. return new Plane(normalX, normalY, normalZ, finalD);
  6694. };
  6695. /**
  6696. * Returns the dot product (float) of the point coordinates and the plane normal.
  6697. */
  6698. Plane.prototype.dotCoordinate = function (point) {
  6699. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6700. };
  6701. /**
  6702. * Updates the current Plane from the plane defined by the three given points.
  6703. * Returns the updated Plane.
  6704. */
  6705. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6706. var x1 = point2.x - point1.x;
  6707. var y1 = point2.y - point1.y;
  6708. var z1 = point2.z - point1.z;
  6709. var x2 = point3.x - point1.x;
  6710. var y2 = point3.y - point1.y;
  6711. var z2 = point3.z - point1.z;
  6712. var yz = (y1 * z2) - (z1 * y2);
  6713. var xz = (z1 * x2) - (x1 * z2);
  6714. var xy = (x1 * y2) - (y1 * x2);
  6715. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6716. var invPyth;
  6717. if (pyth !== 0) {
  6718. invPyth = 1.0 / pyth;
  6719. }
  6720. else {
  6721. invPyth = 0.0;
  6722. }
  6723. this.normal.x = yz * invPyth;
  6724. this.normal.y = xz * invPyth;
  6725. this.normal.z = xy * invPyth;
  6726. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6727. return this;
  6728. };
  6729. /**
  6730. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6731. */
  6732. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6733. var dot = Vector3.Dot(this.normal, direction);
  6734. return (dot <= epsilon);
  6735. };
  6736. /**
  6737. * Returns the signed distance (float) from the given point to the Plane.
  6738. */
  6739. Plane.prototype.signedDistanceTo = function (point) {
  6740. return Vector3.Dot(point, this.normal) + this.d;
  6741. };
  6742. // Statics
  6743. /**
  6744. * Returns a new Plane from the given array.
  6745. */
  6746. Plane.FromArray = function (array) {
  6747. return new Plane(array[0], array[1], array[2], array[3]);
  6748. };
  6749. /**
  6750. * Returns a new Plane defined by the three given points.
  6751. */
  6752. Plane.FromPoints = function (point1, point2, point3) {
  6753. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6754. result.copyFromPoints(point1, point2, point3);
  6755. return result;
  6756. };
  6757. /**
  6758. * Returns a new Plane the normal vector to this plane at the given origin point.
  6759. * Note : the vector "normal" is updated because normalized.
  6760. */
  6761. Plane.FromPositionAndNormal = function (origin, normal) {
  6762. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6763. normal.normalize();
  6764. result.normal = normal;
  6765. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6766. return result;
  6767. };
  6768. /**
  6769. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6770. */
  6771. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6772. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6773. return Vector3.Dot(point, normal) + d;
  6774. };
  6775. return Plane;
  6776. }());
  6777. BABYLON.Plane = Plane;
  6778. var Viewport = /** @class */ (function () {
  6779. /**
  6780. * Creates a Viewport object located at (x, y) and sized (width, height).
  6781. */
  6782. function Viewport(x, y, width, height) {
  6783. this.x = x;
  6784. this.y = y;
  6785. this.width = width;
  6786. this.height = height;
  6787. }
  6788. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6789. if (renderWidthOrEngine.getRenderWidth) {
  6790. var engine = renderWidthOrEngine;
  6791. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6792. }
  6793. var renderWidth = renderWidthOrEngine;
  6794. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6795. };
  6796. /**
  6797. * Returns a new Viewport copied from the current one.
  6798. */
  6799. Viewport.prototype.clone = function () {
  6800. return new Viewport(this.x, this.y, this.width, this.height);
  6801. };
  6802. return Viewport;
  6803. }());
  6804. BABYLON.Viewport = Viewport;
  6805. var Frustum = /** @class */ (function () {
  6806. function Frustum() {
  6807. }
  6808. /**
  6809. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6810. */
  6811. Frustum.GetPlanes = function (transform) {
  6812. var frustumPlanes = [];
  6813. for (var index = 0; index < 6; index++) {
  6814. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6815. }
  6816. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6817. return frustumPlanes;
  6818. };
  6819. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6820. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6821. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6822. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6823. frustumPlane.d = transform.m[15] + transform.m[14];
  6824. frustumPlane.normalize();
  6825. };
  6826. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6827. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6828. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6829. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6830. frustumPlane.d = transform.m[15] - transform.m[14];
  6831. frustumPlane.normalize();
  6832. };
  6833. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6834. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6835. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6836. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6837. frustumPlane.d = transform.m[15] + transform.m[12];
  6838. frustumPlane.normalize();
  6839. };
  6840. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6841. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6842. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6843. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6844. frustumPlane.d = transform.m[15] - transform.m[12];
  6845. frustumPlane.normalize();
  6846. };
  6847. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6848. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6849. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6850. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6851. frustumPlane.d = transform.m[15] - transform.m[13];
  6852. frustumPlane.normalize();
  6853. };
  6854. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6855. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6856. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6857. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6858. frustumPlane.d = transform.m[15] + transform.m[13];
  6859. frustumPlane.normalize();
  6860. };
  6861. /**
  6862. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6863. */
  6864. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6865. // Near
  6866. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6867. // Far
  6868. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6869. // Left
  6870. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6871. // Right
  6872. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6873. // Top
  6874. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6875. // Bottom
  6876. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6877. };
  6878. return Frustum;
  6879. }());
  6880. BABYLON.Frustum = Frustum;
  6881. /** Defines supported spaces */
  6882. var Space;
  6883. (function (Space) {
  6884. /** Local (object) space */
  6885. Space[Space["LOCAL"] = 0] = "LOCAL";
  6886. /** World space */
  6887. Space[Space["WORLD"] = 1] = "WORLD";
  6888. /** Bone space */
  6889. Space[Space["BONE"] = 2] = "BONE";
  6890. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6891. /** Defines the 3 main axes */
  6892. var Axis = /** @class */ (function () {
  6893. function Axis() {
  6894. }
  6895. /** X axis */
  6896. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6897. /** Y axis */
  6898. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6899. /** Z axis */
  6900. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6901. return Axis;
  6902. }());
  6903. BABYLON.Axis = Axis;
  6904. ;
  6905. var BezierCurve = /** @class */ (function () {
  6906. function BezierCurve() {
  6907. }
  6908. /**
  6909. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6910. */
  6911. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6912. // Extract X (which is equal to time here)
  6913. var f0 = 1 - 3 * x2 + 3 * x1;
  6914. var f1 = 3 * x2 - 6 * x1;
  6915. var f2 = 3 * x1;
  6916. var refinedT = t;
  6917. for (var i = 0; i < 5; i++) {
  6918. var refinedT2 = refinedT * refinedT;
  6919. var refinedT3 = refinedT2 * refinedT;
  6920. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6921. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6922. refinedT -= (x - t) * slope;
  6923. refinedT = Math.min(1, Math.max(0, refinedT));
  6924. }
  6925. // Resolve cubic bezier for the given x
  6926. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6927. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6928. Math.pow(refinedT, 3);
  6929. };
  6930. return BezierCurve;
  6931. }());
  6932. BABYLON.BezierCurve = BezierCurve;
  6933. /**
  6934. * Defines potential orientation for back face culling
  6935. */
  6936. var Orientation;
  6937. (function (Orientation) {
  6938. /**
  6939. * Clockwise
  6940. */
  6941. Orientation[Orientation["CW"] = 0] = "CW";
  6942. /** Counter clockwise */
  6943. Orientation[Orientation["CCW"] = 1] = "CCW";
  6944. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6945. /**
  6946. * Defines angle representation
  6947. */
  6948. var Angle = /** @class */ (function () {
  6949. /**
  6950. * Creates an Angle object of "radians" radians (float).
  6951. */
  6952. function Angle(radians) {
  6953. this._radians = radians;
  6954. if (this._radians < 0.0)
  6955. this._radians += (2.0 * Math.PI);
  6956. }
  6957. /**
  6958. * Get value in degrees
  6959. * @returns the Angle value in degrees (float)
  6960. */
  6961. Angle.prototype.degrees = function () {
  6962. return this._radians * 180.0 / Math.PI;
  6963. };
  6964. /**
  6965. * Get value in radians
  6966. * @returns the Angle value in radians (float)
  6967. */
  6968. Angle.prototype.radians = function () {
  6969. return this._radians;
  6970. };
  6971. /**
  6972. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6973. * @param a defines first vector
  6974. * @param b defines second vector
  6975. * @returns a new Angle
  6976. */
  6977. Angle.BetweenTwoPoints = function (a, b) {
  6978. var delta = b.subtract(a);
  6979. var theta = Math.atan2(delta.y, delta.x);
  6980. return new Angle(theta);
  6981. };
  6982. /**
  6983. * Gets a new Angle object from the given float in radians
  6984. * @param radians defines the angle value in radians
  6985. * @returns a new Angle
  6986. */
  6987. Angle.FromRadians = function (radians) {
  6988. return new Angle(radians);
  6989. };
  6990. /**
  6991. * Gets a new Angle object from the given float in degrees
  6992. * @param degrees defines the angle value in degrees
  6993. * @returns a new Angle
  6994. */
  6995. Angle.FromDegrees = function (degrees) {
  6996. return new Angle(degrees * Math.PI / 180.0);
  6997. };
  6998. return Angle;
  6999. }());
  7000. BABYLON.Angle = Angle;
  7001. var Arc2 = /** @class */ (function () {
  7002. /**
  7003. * Creates an Arc object from the three given points : start, middle and end.
  7004. */
  7005. function Arc2(startPoint, midPoint, endPoint) {
  7006. this.startPoint = startPoint;
  7007. this.midPoint = midPoint;
  7008. this.endPoint = endPoint;
  7009. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7010. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7011. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7012. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7013. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7014. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7015. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7016. var a1 = this.startAngle.degrees();
  7017. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7018. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7019. // angles correction
  7020. if (a2 - a1 > +180.0)
  7021. a2 -= 360.0;
  7022. if (a2 - a1 < -180.0)
  7023. a2 += 360.0;
  7024. if (a3 - a2 > +180.0)
  7025. a3 -= 360.0;
  7026. if (a3 - a2 < -180.0)
  7027. a3 += 360.0;
  7028. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7029. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7030. }
  7031. return Arc2;
  7032. }());
  7033. BABYLON.Arc2 = Arc2;
  7034. var Path2 = /** @class */ (function () {
  7035. /**
  7036. * Creates a Path2 object from the starting 2D coordinates x and y.
  7037. */
  7038. function Path2(x, y) {
  7039. this._points = new Array();
  7040. this._length = 0.0;
  7041. this.closed = false;
  7042. this._points.push(new Vector2(x, y));
  7043. }
  7044. /**
  7045. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7046. * Returns the updated Path2.
  7047. */
  7048. Path2.prototype.addLineTo = function (x, y) {
  7049. if (this.closed) {
  7050. return this;
  7051. }
  7052. var newPoint = new Vector2(x, y);
  7053. var previousPoint = this._points[this._points.length - 1];
  7054. this._points.push(newPoint);
  7055. this._length += newPoint.subtract(previousPoint).length();
  7056. return this;
  7057. };
  7058. /**
  7059. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7060. * Returns the updated Path2.
  7061. */
  7062. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7063. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7064. if (this.closed) {
  7065. return this;
  7066. }
  7067. var startPoint = this._points[this._points.length - 1];
  7068. var midPoint = new Vector2(midX, midY);
  7069. var endPoint = new Vector2(endX, endY);
  7070. var arc = new Arc2(startPoint, midPoint, endPoint);
  7071. var increment = arc.angle.radians() / numberOfSegments;
  7072. if (arc.orientation === Orientation.CW)
  7073. increment *= -1;
  7074. var currentAngle = arc.startAngle.radians() + increment;
  7075. for (var i = 0; i < numberOfSegments; i++) {
  7076. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7077. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7078. this.addLineTo(x, y);
  7079. currentAngle += increment;
  7080. }
  7081. return this;
  7082. };
  7083. /**
  7084. * Closes the Path2.
  7085. * Returns the Path2.
  7086. */
  7087. Path2.prototype.close = function () {
  7088. this.closed = true;
  7089. return this;
  7090. };
  7091. /**
  7092. * Returns the Path2 total length (float).
  7093. */
  7094. Path2.prototype.length = function () {
  7095. var result = this._length;
  7096. if (!this.closed) {
  7097. var lastPoint = this._points[this._points.length - 1];
  7098. var firstPoint = this._points[0];
  7099. result += (firstPoint.subtract(lastPoint).length());
  7100. }
  7101. return result;
  7102. };
  7103. /**
  7104. * Returns the Path2 internal array of points.
  7105. */
  7106. Path2.prototype.getPoints = function () {
  7107. return this._points;
  7108. };
  7109. /**
  7110. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7111. */
  7112. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7113. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7114. return Vector2.Zero();
  7115. }
  7116. var lengthPosition = normalizedLengthPosition * this.length();
  7117. var previousOffset = 0;
  7118. for (var i = 0; i < this._points.length; i++) {
  7119. var j = (i + 1) % this._points.length;
  7120. var a = this._points[i];
  7121. var b = this._points[j];
  7122. var bToA = b.subtract(a);
  7123. var nextOffset = (bToA.length() + previousOffset);
  7124. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7125. var dir = bToA.normalize();
  7126. var localOffset = lengthPosition - previousOffset;
  7127. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7128. }
  7129. previousOffset = nextOffset;
  7130. }
  7131. return Vector2.Zero();
  7132. };
  7133. /**
  7134. * Returns a new Path2 starting at the coordinates (x, y).
  7135. */
  7136. Path2.StartingAt = function (x, y) {
  7137. return new Path2(x, y);
  7138. };
  7139. return Path2;
  7140. }());
  7141. BABYLON.Path2 = Path2;
  7142. var Path3D = /** @class */ (function () {
  7143. /**
  7144. * new Path3D(path, normal, raw)
  7145. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7146. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7147. * path : an array of Vector3, the curve axis of the Path3D
  7148. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7149. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7150. */
  7151. function Path3D(path, firstNormal, raw) {
  7152. if (firstNormal === void 0) { firstNormal = null; }
  7153. this.path = path;
  7154. this._curve = new Array();
  7155. this._distances = new Array();
  7156. this._tangents = new Array();
  7157. this._normals = new Array();
  7158. this._binormals = new Array();
  7159. for (var p = 0; p < path.length; p++) {
  7160. this._curve[p] = path[p].clone(); // hard copy
  7161. }
  7162. this._raw = raw || false;
  7163. this._compute(firstNormal);
  7164. }
  7165. /**
  7166. * Returns the Path3D array of successive Vector3 designing its curve.
  7167. */
  7168. Path3D.prototype.getCurve = function () {
  7169. return this._curve;
  7170. };
  7171. /**
  7172. * Returns an array populated with tangent vectors on each Path3D curve point.
  7173. */
  7174. Path3D.prototype.getTangents = function () {
  7175. return this._tangents;
  7176. };
  7177. /**
  7178. * Returns an array populated with normal vectors on each Path3D curve point.
  7179. */
  7180. Path3D.prototype.getNormals = function () {
  7181. return this._normals;
  7182. };
  7183. /**
  7184. * Returns an array populated with binormal vectors on each Path3D curve point.
  7185. */
  7186. Path3D.prototype.getBinormals = function () {
  7187. return this._binormals;
  7188. };
  7189. /**
  7190. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7191. */
  7192. Path3D.prototype.getDistances = function () {
  7193. return this._distances;
  7194. };
  7195. /**
  7196. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7197. * Returns the same object updated.
  7198. */
  7199. Path3D.prototype.update = function (path, firstNormal) {
  7200. if (firstNormal === void 0) { firstNormal = null; }
  7201. for (var p = 0; p < path.length; p++) {
  7202. this._curve[p].x = path[p].x;
  7203. this._curve[p].y = path[p].y;
  7204. this._curve[p].z = path[p].z;
  7205. }
  7206. this._compute(firstNormal);
  7207. return this;
  7208. };
  7209. // private function compute() : computes tangents, normals and binormals
  7210. Path3D.prototype._compute = function (firstNormal) {
  7211. var l = this._curve.length;
  7212. // first and last tangents
  7213. this._tangents[0] = this._getFirstNonNullVector(0);
  7214. if (!this._raw) {
  7215. this._tangents[0].normalize();
  7216. }
  7217. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7218. if (!this._raw) {
  7219. this._tangents[l - 1].normalize();
  7220. }
  7221. // normals and binormals at first point : arbitrary vector with _normalVector()
  7222. var tg0 = this._tangents[0];
  7223. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7224. this._normals[0] = pp0;
  7225. if (!this._raw) {
  7226. this._normals[0].normalize();
  7227. }
  7228. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7229. if (!this._raw) {
  7230. this._binormals[0].normalize();
  7231. }
  7232. this._distances[0] = 0.0;
  7233. // normals and binormals : next points
  7234. var prev; // previous vector (segment)
  7235. var cur; // current vector (segment)
  7236. var curTang; // current tangent
  7237. // previous normal
  7238. var prevBinor; // previous binormal
  7239. for (var i = 1; i < l; i++) {
  7240. // tangents
  7241. prev = this._getLastNonNullVector(i);
  7242. if (i < l - 1) {
  7243. cur = this._getFirstNonNullVector(i);
  7244. this._tangents[i] = prev.add(cur);
  7245. this._tangents[i].normalize();
  7246. }
  7247. this._distances[i] = this._distances[i - 1] + prev.length();
  7248. // normals and binormals
  7249. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7250. curTang = this._tangents[i];
  7251. prevBinor = this._binormals[i - 1];
  7252. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7253. if (!this._raw) {
  7254. this._normals[i].normalize();
  7255. }
  7256. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7257. if (!this._raw) {
  7258. this._binormals[i].normalize();
  7259. }
  7260. }
  7261. };
  7262. // private function getFirstNonNullVector(index)
  7263. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7264. Path3D.prototype._getFirstNonNullVector = function (index) {
  7265. var i = 1;
  7266. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7267. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7268. i++;
  7269. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7270. }
  7271. return nNVector;
  7272. };
  7273. // private function getLastNonNullVector(index)
  7274. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7275. Path3D.prototype._getLastNonNullVector = function (index) {
  7276. var i = 1;
  7277. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7278. while (nLVector.length() === 0 && index > i + 1) {
  7279. i++;
  7280. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7281. }
  7282. return nLVector;
  7283. };
  7284. // private function normalVector(v0, vt, va) :
  7285. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7286. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7287. Path3D.prototype._normalVector = function (v0, vt, va) {
  7288. var normal0;
  7289. var tgl = vt.length();
  7290. if (tgl === 0.0) {
  7291. tgl = 1.0;
  7292. }
  7293. if (va === undefined || va === null) {
  7294. var point;
  7295. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7296. point = new Vector3(0.0, -1.0, 0.0);
  7297. }
  7298. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7299. point = new Vector3(1.0, 0.0, 0.0);
  7300. }
  7301. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7302. point = new Vector3(0.0, 0.0, 1.0);
  7303. }
  7304. else {
  7305. point = Vector3.Zero();
  7306. }
  7307. normal0 = Vector3.Cross(vt, point);
  7308. }
  7309. else {
  7310. normal0 = Vector3.Cross(vt, va);
  7311. Vector3.CrossToRef(normal0, vt, normal0);
  7312. }
  7313. normal0.normalize();
  7314. return normal0;
  7315. };
  7316. return Path3D;
  7317. }());
  7318. BABYLON.Path3D = Path3D;
  7319. var Curve3 = /** @class */ (function () {
  7320. /**
  7321. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7322. * A Curve3 is designed from a series of successive Vector3.
  7323. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7324. */
  7325. function Curve3(points) {
  7326. this._length = 0.0;
  7327. this._points = points;
  7328. this._length = this._computeLength(points);
  7329. }
  7330. /**
  7331. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7332. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7333. * @param v1 (Vector3) the control point
  7334. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7335. * @param nbPoints (integer) the wanted number of points in the curve
  7336. */
  7337. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7338. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7339. var bez = new Array();
  7340. var equation = function (t, val0, val1, val2) {
  7341. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7342. return res;
  7343. };
  7344. for (var i = 0; i <= nbPoints; i++) {
  7345. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7346. }
  7347. return new Curve3(bez);
  7348. };
  7349. /**
  7350. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7351. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7352. * @param v1 (Vector3) the first control point
  7353. * @param v2 (Vector3) the second control point
  7354. * @param v3 (Vector3) the end point of the Cubic Bezier
  7355. * @param nbPoints (integer) the wanted number of points in the curve
  7356. */
  7357. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7358. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7359. var bez = new Array();
  7360. var equation = function (t, val0, val1, val2, val3) {
  7361. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7362. return res;
  7363. };
  7364. for (var i = 0; i <= nbPoints; i++) {
  7365. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7366. }
  7367. return new Curve3(bez);
  7368. };
  7369. /**
  7370. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7371. * @param p1 (Vector3) the origin point of the Hermite Spline
  7372. * @param t1 (Vector3) the tangent vector at the origin point
  7373. * @param p2 (Vector3) the end point of the Hermite Spline
  7374. * @param t2 (Vector3) the tangent vector at the end point
  7375. * @param nbPoints (integer) the wanted number of points in the curve
  7376. */
  7377. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7378. var hermite = new Array();
  7379. var step = 1.0 / nbPoints;
  7380. for (var i = 0; i <= nbPoints; i++) {
  7381. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7382. }
  7383. return new Curve3(hermite);
  7384. };
  7385. /**
  7386. * Returns a Curve3 object along a CatmullRom Spline curve :
  7387. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7388. * @param nbPoints (integer) the wanted number of points between each curve control points
  7389. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7390. */
  7391. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7392. var catmullRom = new Array();
  7393. var step = 1.0 / nbPoints;
  7394. var amount = 0.0;
  7395. if (closed) {
  7396. var pointsCount = points.length;
  7397. for (var i = 0; i < pointsCount; i++) {
  7398. amount = 0;
  7399. for (var c = 0; c < nbPoints; c++) {
  7400. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7401. amount += step;
  7402. }
  7403. }
  7404. catmullRom.push(catmullRom[0]);
  7405. }
  7406. else {
  7407. var totalPoints = new Array();
  7408. totalPoints.push(points[0].clone());
  7409. Array.prototype.push.apply(totalPoints, points);
  7410. totalPoints.push(points[points.length - 1].clone());
  7411. for (var i = 0; i < totalPoints.length - 3; i++) {
  7412. amount = 0;
  7413. for (var c = 0; c < nbPoints; c++) {
  7414. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7415. amount += step;
  7416. }
  7417. }
  7418. i--;
  7419. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7420. }
  7421. return new Curve3(catmullRom);
  7422. };
  7423. /**
  7424. * Returns the Curve3 stored array of successive Vector3
  7425. */
  7426. Curve3.prototype.getPoints = function () {
  7427. return this._points;
  7428. };
  7429. /**
  7430. * Returns the computed length (float) of the curve.
  7431. */
  7432. Curve3.prototype.length = function () {
  7433. return this._length;
  7434. };
  7435. /**
  7436. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7437. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7438. * curveA and curveB keep unchanged.
  7439. */
  7440. Curve3.prototype.continue = function (curve) {
  7441. var lastPoint = this._points[this._points.length - 1];
  7442. var continuedPoints = this._points.slice();
  7443. var curvePoints = curve.getPoints();
  7444. for (var i = 1; i < curvePoints.length; i++) {
  7445. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7446. }
  7447. var continuedCurve = new Curve3(continuedPoints);
  7448. return continuedCurve;
  7449. };
  7450. Curve3.prototype._computeLength = function (path) {
  7451. var l = 0;
  7452. for (var i = 1; i < path.length; i++) {
  7453. l += (path[i].subtract(path[i - 1])).length();
  7454. }
  7455. return l;
  7456. };
  7457. return Curve3;
  7458. }());
  7459. BABYLON.Curve3 = Curve3;
  7460. // Vertex formats
  7461. var PositionNormalVertex = /** @class */ (function () {
  7462. function PositionNormalVertex(position, normal) {
  7463. if (position === void 0) { position = Vector3.Zero(); }
  7464. if (normal === void 0) { normal = Vector3.Up(); }
  7465. this.position = position;
  7466. this.normal = normal;
  7467. }
  7468. PositionNormalVertex.prototype.clone = function () {
  7469. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7470. };
  7471. return PositionNormalVertex;
  7472. }());
  7473. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7474. var PositionNormalTextureVertex = /** @class */ (function () {
  7475. function PositionNormalTextureVertex(position, normal, uv) {
  7476. if (position === void 0) { position = Vector3.Zero(); }
  7477. if (normal === void 0) { normal = Vector3.Up(); }
  7478. if (uv === void 0) { uv = Vector2.Zero(); }
  7479. this.position = position;
  7480. this.normal = normal;
  7481. this.uv = uv;
  7482. }
  7483. PositionNormalTextureVertex.prototype.clone = function () {
  7484. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7485. };
  7486. return PositionNormalTextureVertex;
  7487. }());
  7488. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7489. // Temporary pre-allocated objects for engine internal use
  7490. // usage in any internal function :
  7491. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7492. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7493. var Tmp = /** @class */ (function () {
  7494. function Tmp() {
  7495. }
  7496. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7497. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7498. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7499. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7500. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7501. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7502. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero(),
  7505. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7506. return Tmp;
  7507. }());
  7508. BABYLON.Tmp = Tmp;
  7509. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7510. var MathTmp = /** @class */ (function () {
  7511. function MathTmp() {
  7512. }
  7513. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7514. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7515. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7516. return MathTmp;
  7517. }());
  7518. })(BABYLON || (BABYLON = {}));
  7519. //# sourceMappingURL=babylon.math.js.map
  7520. var BABYLON;
  7521. (function (BABYLON) {
  7522. var Scalar = /** @class */ (function () {
  7523. function Scalar() {
  7524. }
  7525. /**
  7526. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7527. */
  7528. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7529. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7530. var num = a - b;
  7531. return -epsilon <= num && num <= epsilon;
  7532. };
  7533. /**
  7534. * Returns a string : the upper case translation of the number i to hexadecimal.
  7535. */
  7536. Scalar.ToHex = function (i) {
  7537. var str = i.toString(16);
  7538. if (i <= 15) {
  7539. return ("0" + str).toUpperCase();
  7540. }
  7541. return str.toUpperCase();
  7542. };
  7543. /**
  7544. * Returns -1 if value is negative and +1 is value is positive.
  7545. * Returns the value itself if it's equal to zero.
  7546. */
  7547. Scalar.Sign = function (value) {
  7548. value = +value; // convert to a number
  7549. if (value === 0 || isNaN(value))
  7550. return value;
  7551. return value > 0 ? 1 : -1;
  7552. };
  7553. /**
  7554. * Returns the value itself if it's between min and max.
  7555. * Returns min if the value is lower than min.
  7556. * Returns max if the value is greater than max.
  7557. */
  7558. Scalar.Clamp = function (value, min, max) {
  7559. if (min === void 0) { min = 0; }
  7560. if (max === void 0) { max = 1; }
  7561. return Math.min(max, Math.max(min, value));
  7562. };
  7563. /**
  7564. * Returns the log2 of value.
  7565. */
  7566. Scalar.Log2 = function (value) {
  7567. return Math.log(value) * Math.LOG2E;
  7568. };
  7569. /**
  7570. * Loops the value, so that it is never larger than length and never smaller than 0.
  7571. *
  7572. * This is similar to the modulo operator but it works with floating point numbers.
  7573. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7574. * With t = 5 and length = 2.5, the result would be 0.0.
  7575. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7576. */
  7577. Scalar.Repeat = function (value, length) {
  7578. return value - Math.floor(value / length) * length;
  7579. };
  7580. /**
  7581. * Normalize the value between 0.0 and 1.0 using min and max values
  7582. */
  7583. Scalar.Normalize = function (value, min, max) {
  7584. return (value - min) / (max - min);
  7585. };
  7586. /**
  7587. * Denormalize the value from 0.0 and 1.0 using min and max values
  7588. */
  7589. Scalar.Denormalize = function (normalized, min, max) {
  7590. return (normalized * (max - min) + min);
  7591. };
  7592. /**
  7593. * Calculates the shortest difference between two given angles given in degrees.
  7594. */
  7595. Scalar.DeltaAngle = function (current, target) {
  7596. var num = Scalar.Repeat(target - current, 360.0);
  7597. if (num > 180.0) {
  7598. num -= 360.0;
  7599. }
  7600. return num;
  7601. };
  7602. /**
  7603. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7604. *
  7605. * The returned value will move back and forth between 0 and length
  7606. */
  7607. Scalar.PingPong = function (tx, length) {
  7608. var t = Scalar.Repeat(tx, length * 2.0);
  7609. return length - Math.abs(t - length);
  7610. };
  7611. /**
  7612. * Interpolates between min and max with smoothing at the limits.
  7613. *
  7614. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7615. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7616. */
  7617. Scalar.SmoothStep = function (from, to, tx) {
  7618. var t = Scalar.Clamp(tx);
  7619. t = -2.0 * t * t * t + 3.0 * t * t;
  7620. return to * t + from * (1.0 - t);
  7621. };
  7622. /**
  7623. * Moves a value current towards target.
  7624. *
  7625. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7626. * Negative values of maxDelta pushes the value away from target.
  7627. */
  7628. Scalar.MoveTowards = function (current, target, maxDelta) {
  7629. var result = 0;
  7630. if (Math.abs(target - current) <= maxDelta) {
  7631. result = target;
  7632. }
  7633. else {
  7634. result = current + Scalar.Sign(target - current) * maxDelta;
  7635. }
  7636. return result;
  7637. };
  7638. /**
  7639. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7640. *
  7641. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7642. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7643. */
  7644. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7645. var num = Scalar.DeltaAngle(current, target);
  7646. var result = 0;
  7647. if (-maxDelta < num && num < maxDelta) {
  7648. result = target;
  7649. }
  7650. else {
  7651. target = current + num;
  7652. result = Scalar.MoveTowards(current, target, maxDelta);
  7653. }
  7654. return result;
  7655. };
  7656. /**
  7657. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7658. */
  7659. Scalar.Lerp = function (start, end, amount) {
  7660. return start + ((end - start) * amount);
  7661. };
  7662. /**
  7663. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7664. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7665. */
  7666. Scalar.LerpAngle = function (start, end, amount) {
  7667. var num = Scalar.Repeat(end - start, 360.0);
  7668. if (num > 180.0) {
  7669. num -= 360.0;
  7670. }
  7671. return start + num * Scalar.Clamp(amount);
  7672. };
  7673. /**
  7674. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7675. */
  7676. Scalar.InverseLerp = function (a, b, value) {
  7677. var result = 0;
  7678. if (a != b) {
  7679. result = Scalar.Clamp((value - a) / (b - a));
  7680. }
  7681. else {
  7682. result = 0.0;
  7683. }
  7684. return result;
  7685. };
  7686. /**
  7687. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7688. */
  7689. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7690. var squared = amount * amount;
  7691. var cubed = amount * squared;
  7692. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7693. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7694. var part3 = (cubed - (2.0 * squared)) + amount;
  7695. var part4 = cubed - squared;
  7696. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7697. };
  7698. /**
  7699. * Returns a random float number between and min and max values
  7700. */
  7701. Scalar.RandomRange = function (min, max) {
  7702. if (min === max)
  7703. return min;
  7704. return ((Math.random() * (max - min)) + min);
  7705. };
  7706. /**
  7707. * This function returns percentage of a number in a given range.
  7708. *
  7709. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7710. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7711. */
  7712. Scalar.RangeToPercent = function (number, min, max) {
  7713. return ((number - min) / (max - min));
  7714. };
  7715. /**
  7716. * This function returns number that corresponds to the percentage in a given range.
  7717. *
  7718. * PercentToRange(0.34,0,100) will return 34.
  7719. */
  7720. Scalar.PercentToRange = function (percent, min, max) {
  7721. return ((max - min) * percent + min);
  7722. };
  7723. /**
  7724. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7725. * @param angle The angle to normalize in radian.
  7726. * @return The converted angle.
  7727. */
  7728. Scalar.NormalizeRadians = function (angle) {
  7729. // More precise but slower version kept for reference.
  7730. // angle = angle % Tools.TwoPi;
  7731. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7732. //if (angle > Math.PI) {
  7733. // angle -= Tools.TwoPi;
  7734. //}
  7735. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7736. return angle;
  7737. };
  7738. /**
  7739. * Two pi constants convenient for computation.
  7740. */
  7741. Scalar.TwoPi = Math.PI * 2;
  7742. return Scalar;
  7743. }());
  7744. BABYLON.Scalar = Scalar;
  7745. })(BABYLON || (BABYLON = {}));
  7746. //# sourceMappingURL=babylon.math.scalar.js.map
  7747. //# sourceMappingURL=babylon.mixins.js.map
  7748. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7749. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7750. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7751. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7752. //# sourceMappingURL=babylon.webgl2.js.map
  7753. var BABYLON;
  7754. (function (BABYLON) {
  7755. var __decoratorInitialStore = {};
  7756. var __mergedStore = {};
  7757. var _copySource = function (creationFunction, source, instanciate) {
  7758. var destination = creationFunction();
  7759. // Tags
  7760. if (BABYLON.Tags) {
  7761. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7762. }
  7763. var classStore = getMergedStore(destination);
  7764. // Properties
  7765. for (var property in classStore) {
  7766. var propertyDescriptor = classStore[property];
  7767. var sourceProperty = source[property];
  7768. var propertyType = propertyDescriptor.type;
  7769. if (sourceProperty !== undefined && sourceProperty !== null) {
  7770. switch (propertyType) {
  7771. case 0: // Value
  7772. case 6: // Mesh reference
  7773. case 11: // Camera reference
  7774. destination[property] = sourceProperty;
  7775. break;
  7776. case 1: // Texture
  7777. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7778. break;
  7779. case 2: // Color3
  7780. case 3: // FresnelParameters
  7781. case 4: // Vector2
  7782. case 5: // Vector3
  7783. case 7: // Color Curves
  7784. case 10: // Quaternion
  7785. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7786. break;
  7787. }
  7788. }
  7789. }
  7790. return destination;
  7791. };
  7792. function getDirectStore(target) {
  7793. var classKey = target.getClassName();
  7794. if (!__decoratorInitialStore[classKey]) {
  7795. __decoratorInitialStore[classKey] = {};
  7796. }
  7797. return __decoratorInitialStore[classKey];
  7798. }
  7799. /**
  7800. * Return the list of properties flagged as serializable
  7801. * @param target: host object
  7802. */
  7803. function getMergedStore(target) {
  7804. var classKey = target.getClassName();
  7805. if (__mergedStore[classKey]) {
  7806. return __mergedStore[classKey];
  7807. }
  7808. __mergedStore[classKey] = {};
  7809. var store = __mergedStore[classKey];
  7810. var currentTarget = target;
  7811. var currentKey = classKey;
  7812. while (currentKey) {
  7813. var initialStore = __decoratorInitialStore[currentKey];
  7814. for (var property in initialStore) {
  7815. store[property] = initialStore[property];
  7816. }
  7817. var parent_1 = void 0;
  7818. var done = false;
  7819. do {
  7820. parent_1 = Object.getPrototypeOf(currentTarget);
  7821. if (!parent_1.getClassName) {
  7822. done = true;
  7823. break;
  7824. }
  7825. if (parent_1.getClassName() !== currentKey) {
  7826. break;
  7827. }
  7828. currentTarget = parent_1;
  7829. } while (parent_1);
  7830. if (done) {
  7831. break;
  7832. }
  7833. currentKey = parent_1.getClassName();
  7834. currentTarget = parent_1;
  7835. }
  7836. return store;
  7837. }
  7838. function generateSerializableMember(type, sourceName) {
  7839. return function (target, propertyKey) {
  7840. var classStore = getDirectStore(target);
  7841. if (!classStore[propertyKey]) {
  7842. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7843. }
  7844. };
  7845. }
  7846. function generateExpandMember(setCallback, targetKey) {
  7847. if (targetKey === void 0) { targetKey = null; }
  7848. return function (target, propertyKey) {
  7849. var key = targetKey || ("_" + propertyKey);
  7850. Object.defineProperty(target, propertyKey, {
  7851. get: function () {
  7852. return this[key];
  7853. },
  7854. set: function (value) {
  7855. if (this[key] === value) {
  7856. return;
  7857. }
  7858. this[key] = value;
  7859. target[setCallback].apply(this);
  7860. },
  7861. enumerable: true,
  7862. configurable: true
  7863. });
  7864. };
  7865. }
  7866. function expandToProperty(callback, targetKey) {
  7867. if (targetKey === void 0) { targetKey = null; }
  7868. return generateExpandMember(callback, targetKey);
  7869. }
  7870. BABYLON.expandToProperty = expandToProperty;
  7871. function serialize(sourceName) {
  7872. return generateSerializableMember(0, sourceName); // value member
  7873. }
  7874. BABYLON.serialize = serialize;
  7875. function serializeAsTexture(sourceName) {
  7876. return generateSerializableMember(1, sourceName); // texture member
  7877. }
  7878. BABYLON.serializeAsTexture = serializeAsTexture;
  7879. function serializeAsColor3(sourceName) {
  7880. return generateSerializableMember(2, sourceName); // color3 member
  7881. }
  7882. BABYLON.serializeAsColor3 = serializeAsColor3;
  7883. function serializeAsFresnelParameters(sourceName) {
  7884. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7885. }
  7886. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7887. function serializeAsVector2(sourceName) {
  7888. return generateSerializableMember(4, sourceName); // vector2 member
  7889. }
  7890. BABYLON.serializeAsVector2 = serializeAsVector2;
  7891. function serializeAsVector3(sourceName) {
  7892. return generateSerializableMember(5, sourceName); // vector3 member
  7893. }
  7894. BABYLON.serializeAsVector3 = serializeAsVector3;
  7895. function serializeAsMeshReference(sourceName) {
  7896. return generateSerializableMember(6, sourceName); // mesh reference member
  7897. }
  7898. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7899. function serializeAsColorCurves(sourceName) {
  7900. return generateSerializableMember(7, sourceName); // color curves
  7901. }
  7902. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7903. function serializeAsColor4(sourceName) {
  7904. return generateSerializableMember(8, sourceName); // color 4
  7905. }
  7906. BABYLON.serializeAsColor4 = serializeAsColor4;
  7907. function serializeAsImageProcessingConfiguration(sourceName) {
  7908. return generateSerializableMember(9, sourceName); // image processing
  7909. }
  7910. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7911. function serializeAsQuaternion(sourceName) {
  7912. return generateSerializableMember(10, sourceName); // quaternion member
  7913. }
  7914. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7915. /**
  7916. * Decorator used to define property that can be serialized as reference to a camera
  7917. * @param sourceName defines the name of the property to decorate
  7918. */
  7919. function serializeAsCameraReference(sourceName) {
  7920. return generateSerializableMember(11, sourceName); // camera reference member
  7921. }
  7922. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7923. var SerializationHelper = /** @class */ (function () {
  7924. function SerializationHelper() {
  7925. }
  7926. SerializationHelper.Serialize = function (entity, serializationObject) {
  7927. if (!serializationObject) {
  7928. serializationObject = {};
  7929. }
  7930. // Tags
  7931. if (BABYLON.Tags) {
  7932. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7933. }
  7934. var serializedProperties = getMergedStore(entity);
  7935. // Properties
  7936. for (var property in serializedProperties) {
  7937. var propertyDescriptor = serializedProperties[property];
  7938. var targetPropertyName = propertyDescriptor.sourceName || property;
  7939. var propertyType = propertyDescriptor.type;
  7940. var sourceProperty = entity[property];
  7941. if (sourceProperty !== undefined && sourceProperty !== null) {
  7942. switch (propertyType) {
  7943. case 0: // Value
  7944. serializationObject[targetPropertyName] = sourceProperty;
  7945. break;
  7946. case 1: // Texture
  7947. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7948. break;
  7949. case 2: // Color3
  7950. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7951. break;
  7952. case 3: // FresnelParameters
  7953. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7954. break;
  7955. case 4: // Vector2
  7956. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7957. break;
  7958. case 5: // Vector3
  7959. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7960. break;
  7961. case 6: // Mesh reference
  7962. serializationObject[targetPropertyName] = sourceProperty.id;
  7963. break;
  7964. case 7: // Color Curves
  7965. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7966. break;
  7967. case 8: // Color 4
  7968. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7969. break;
  7970. case 9: // Image Processing
  7971. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7972. break;
  7973. case 10: // Quaternion
  7974. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7975. break;
  7976. case 11: // Camera reference
  7977. serializationObject[targetPropertyName] = sourceProperty.id;
  7978. break;
  7979. }
  7980. }
  7981. }
  7982. return serializationObject;
  7983. };
  7984. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7985. if (rootUrl === void 0) { rootUrl = null; }
  7986. var destination = creationFunction();
  7987. if (!rootUrl) {
  7988. rootUrl = "";
  7989. }
  7990. // Tags
  7991. if (BABYLON.Tags) {
  7992. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7993. }
  7994. var classStore = getMergedStore(destination);
  7995. // Properties
  7996. for (var property in classStore) {
  7997. var propertyDescriptor = classStore[property];
  7998. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7999. var propertyType = propertyDescriptor.type;
  8000. if (sourceProperty !== undefined && sourceProperty !== null) {
  8001. var dest = destination;
  8002. switch (propertyType) {
  8003. case 0: // Value
  8004. dest[property] = sourceProperty;
  8005. break;
  8006. case 1: // Texture
  8007. if (scene) {
  8008. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8009. }
  8010. break;
  8011. case 2: // Color3
  8012. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8013. break;
  8014. case 3: // FresnelParameters
  8015. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8016. break;
  8017. case 4: // Vector2
  8018. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8019. break;
  8020. case 5: // Vector3
  8021. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8022. break;
  8023. case 6: // Mesh reference
  8024. if (scene) {
  8025. dest[property] = scene.getLastMeshByID(sourceProperty);
  8026. }
  8027. break;
  8028. case 7: // Color Curves
  8029. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8030. break;
  8031. case 8: // Color 4
  8032. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8033. break;
  8034. case 9: // Image Processing
  8035. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8036. break;
  8037. case 10: // Quaternion
  8038. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8039. break;
  8040. case 11: // Camera reference
  8041. if (scene) {
  8042. dest[property] = scene.getCameraByID(sourceProperty);
  8043. }
  8044. break;
  8045. }
  8046. }
  8047. }
  8048. return destination;
  8049. };
  8050. SerializationHelper.Clone = function (creationFunction, source) {
  8051. return _copySource(creationFunction, source, false);
  8052. };
  8053. SerializationHelper.Instanciate = function (creationFunction, source) {
  8054. return _copySource(creationFunction, source, true);
  8055. };
  8056. return SerializationHelper;
  8057. }());
  8058. BABYLON.SerializationHelper = SerializationHelper;
  8059. })(BABYLON || (BABYLON = {}));
  8060. //# sourceMappingURL=babylon.decorators.js.map
  8061. var BABYLON;
  8062. (function (BABYLON) {
  8063. /**
  8064. * Wrapper class for promise with external resolve and reject.
  8065. */
  8066. var Deferred = /** @class */ (function () {
  8067. /**
  8068. * Constructor for this deferred object.
  8069. */
  8070. function Deferred() {
  8071. var _this = this;
  8072. this.promise = new Promise(function (resolve, reject) {
  8073. _this._resolve = resolve;
  8074. _this._reject = reject;
  8075. });
  8076. }
  8077. Object.defineProperty(Deferred.prototype, "resolve", {
  8078. /**
  8079. * The resolve method of the promise associated with this deferred object.
  8080. */
  8081. get: function () {
  8082. return this._resolve;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Deferred.prototype, "reject", {
  8088. /**
  8089. * The reject method of the promise associated with this deferred object.
  8090. */
  8091. get: function () {
  8092. return this._reject;
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. return Deferred;
  8098. }());
  8099. BABYLON.Deferred = Deferred;
  8100. })(BABYLON || (BABYLON = {}));
  8101. //# sourceMappingURL=babylon.deferred.js.map
  8102. var BABYLON;
  8103. (function (BABYLON) {
  8104. /**
  8105. * A class serves as a medium between the observable and its observers
  8106. */
  8107. var EventState = /** @class */ (function () {
  8108. /**
  8109. * Create a new EventState
  8110. * @param mask defines the mask associated with this state
  8111. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8112. * @param target defines the original target of the state
  8113. * @param currentTarget defines the current target of the state
  8114. */
  8115. function EventState(mask, skipNextObservers, target, currentTarget) {
  8116. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8117. this.initalize(mask, skipNextObservers, target, currentTarget);
  8118. }
  8119. /**
  8120. * Initialize the current event state
  8121. * @param mask defines the mask associated with this state
  8122. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8123. * @param target defines the original target of the state
  8124. * @param currentTarget defines the current target of the state
  8125. * @returns the current event state
  8126. */
  8127. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8128. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8129. this.mask = mask;
  8130. this.skipNextObservers = skipNextObservers;
  8131. this.target = target;
  8132. this.currentTarget = currentTarget;
  8133. return this;
  8134. };
  8135. return EventState;
  8136. }());
  8137. BABYLON.EventState = EventState;
  8138. /**
  8139. * Represent an Observer registered to a given Observable object.
  8140. */
  8141. var Observer = /** @class */ (function () {
  8142. /**
  8143. * Creates a new observer
  8144. * @param callback defines the callback to call when the observer is notified
  8145. * @param mask defines the mask of the observer (used to filter notifications)
  8146. * @param scope defines the current scope used to restore the JS context
  8147. */
  8148. function Observer(
  8149. /**
  8150. * Defines the callback to call when the observer is notified
  8151. */
  8152. callback,
  8153. /**
  8154. * Defines the mask of the observer (used to filter notifications)
  8155. */
  8156. mask,
  8157. /**
  8158. * Defines the current scope used to restore the JS context
  8159. */
  8160. scope) {
  8161. if (scope === void 0) { scope = null; }
  8162. this.callback = callback;
  8163. this.mask = mask;
  8164. this.scope = scope;
  8165. /** @hidden */
  8166. this._willBeUnregistered = false;
  8167. /**
  8168. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8169. */
  8170. this.unregisterOnNextCall = false;
  8171. }
  8172. return Observer;
  8173. }());
  8174. BABYLON.Observer = Observer;
  8175. /**
  8176. * Represent a list of observers registered to multiple Observables object.
  8177. */
  8178. var MultiObserver = /** @class */ (function () {
  8179. function MultiObserver() {
  8180. }
  8181. /**
  8182. * Release associated resources
  8183. */
  8184. MultiObserver.prototype.dispose = function () {
  8185. if (this._observers && this._observables) {
  8186. for (var index = 0; index < this._observers.length; index++) {
  8187. this._observables[index].remove(this._observers[index]);
  8188. }
  8189. }
  8190. this._observers = null;
  8191. this._observables = null;
  8192. };
  8193. /**
  8194. * Raise a callback when one of the observable will notify
  8195. * @param observables defines a list of observables to watch
  8196. * @param callback defines the callback to call on notification
  8197. * @param mask defines the mask used to filter notifications
  8198. * @param scope defines the current scope used to restore the JS context
  8199. * @returns the new MultiObserver
  8200. */
  8201. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8202. if (mask === void 0) { mask = -1; }
  8203. if (scope === void 0) { scope = null; }
  8204. var result = new MultiObserver();
  8205. result._observers = new Array();
  8206. result._observables = observables;
  8207. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8208. var observable = observables_1[_i];
  8209. var observer = observable.add(callback, mask, false, scope);
  8210. if (observer) {
  8211. result._observers.push(observer);
  8212. }
  8213. }
  8214. return result;
  8215. };
  8216. return MultiObserver;
  8217. }());
  8218. BABYLON.MultiObserver = MultiObserver;
  8219. /**
  8220. * The Observable class is a simple implementation of the Observable pattern.
  8221. *
  8222. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8223. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8224. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8225. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8226. */
  8227. var Observable = /** @class */ (function () {
  8228. /**
  8229. * Creates a new observable
  8230. * @param onObserverAdded defines a callback to call when a new observer is added
  8231. */
  8232. function Observable(onObserverAdded) {
  8233. this._observers = new Array();
  8234. this._eventState = new EventState(0);
  8235. if (onObserverAdded) {
  8236. this._onObserverAdded = onObserverAdded;
  8237. }
  8238. }
  8239. /**
  8240. * Create a new Observer with the specified callback
  8241. * @param callback the callback that will be executed for that Observer
  8242. * @param mask the mask used to filter observers
  8243. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8244. * @param scope optional scope for the callback to be called from
  8245. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8246. * @returns the new observer created for the callback
  8247. */
  8248. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8249. if (mask === void 0) { mask = -1; }
  8250. if (insertFirst === void 0) { insertFirst = false; }
  8251. if (scope === void 0) { scope = null; }
  8252. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8253. if (!callback) {
  8254. return null;
  8255. }
  8256. var observer = new Observer(callback, mask, scope);
  8257. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8258. if (insertFirst) {
  8259. this._observers.unshift(observer);
  8260. }
  8261. else {
  8262. this._observers.push(observer);
  8263. }
  8264. if (this._onObserverAdded) {
  8265. this._onObserverAdded(observer);
  8266. }
  8267. return observer;
  8268. };
  8269. /**
  8270. * Create a new Observer with the specified callback and unregisters after the next notification
  8271. * @param callback the callback that will be executed for that Observer
  8272. * @returns the new observer created for the callback
  8273. */
  8274. Observable.prototype.addOnce = function (callback) {
  8275. return this.add(callback, undefined, undefined, undefined, true);
  8276. };
  8277. /**
  8278. * Remove an Observer from the Observable object
  8279. * @param observer the instance of the Observer to remove
  8280. * @returns false if it doesn't belong to this Observable
  8281. */
  8282. Observable.prototype.remove = function (observer) {
  8283. if (!observer) {
  8284. return false;
  8285. }
  8286. var index = this._observers.indexOf(observer);
  8287. if (index !== -1) {
  8288. this._observers.splice(index, 1);
  8289. return true;
  8290. }
  8291. return false;
  8292. };
  8293. /**
  8294. * Remove a callback from the Observable object
  8295. * @param callback the callback to remove
  8296. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8297. * @returns false if it doesn't belong to this Observable
  8298. */
  8299. Observable.prototype.removeCallback = function (callback, scope) {
  8300. for (var index = 0; index < this._observers.length; index++) {
  8301. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8302. this._observers.splice(index, 1);
  8303. return true;
  8304. }
  8305. }
  8306. return false;
  8307. };
  8308. Observable.prototype._deferUnregister = function (observer) {
  8309. var _this = this;
  8310. observer.unregisterOnNextCall = false;
  8311. observer._willBeUnregistered = true;
  8312. BABYLON.Tools.SetImmediate(function () {
  8313. _this.remove(observer);
  8314. });
  8315. };
  8316. /**
  8317. * Notify all Observers by calling their respective callback with the given data
  8318. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8319. * @param eventData defines the data to send to all observers
  8320. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8321. * @param target defines the original target of the state
  8322. * @param currentTarget defines the current target of the state
  8323. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8324. */
  8325. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8326. if (mask === void 0) { mask = -1; }
  8327. if (!this._observers.length) {
  8328. return true;
  8329. }
  8330. var state = this._eventState;
  8331. state.mask = mask;
  8332. state.target = target;
  8333. state.currentTarget = currentTarget;
  8334. state.skipNextObservers = false;
  8335. state.lastReturnValue = eventData;
  8336. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8337. var obs = _a[_i];
  8338. if (obs._willBeUnregistered) {
  8339. continue;
  8340. }
  8341. if (obs.mask & mask) {
  8342. if (obs.scope) {
  8343. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8344. }
  8345. else {
  8346. state.lastReturnValue = obs.callback(eventData, state);
  8347. }
  8348. if (obs.unregisterOnNextCall) {
  8349. this._deferUnregister(obs);
  8350. }
  8351. }
  8352. if (state.skipNextObservers) {
  8353. return false;
  8354. }
  8355. }
  8356. return true;
  8357. };
  8358. /**
  8359. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8360. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8361. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8362. * and it is crucial that all callbacks will be executed.
  8363. * The order of the callbacks is kept, callbacks are not executed parallel.
  8364. *
  8365. * @param eventData The data to be sent to each callback
  8366. * @param mask is used to filter observers defaults to -1
  8367. * @param target defines the callback target (see EventState)
  8368. * @param currentTarget defines he current object in the bubbling phase
  8369. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8370. */
  8371. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8372. var _this = this;
  8373. if (mask === void 0) { mask = -1; }
  8374. // create an empty promise
  8375. var p = Promise.resolve(eventData);
  8376. // no observers? return this promise.
  8377. if (!this._observers.length) {
  8378. return p;
  8379. }
  8380. var state = this._eventState;
  8381. state.mask = mask;
  8382. state.target = target;
  8383. state.currentTarget = currentTarget;
  8384. state.skipNextObservers = false;
  8385. // execute one callback after another (not using Promise.all, the order is important)
  8386. this._observers.forEach(function (obs) {
  8387. if (state.skipNextObservers) {
  8388. return;
  8389. }
  8390. if (obs._willBeUnregistered) {
  8391. return;
  8392. }
  8393. if (obs.mask & mask) {
  8394. if (obs.scope) {
  8395. p = p.then(function (lastReturnedValue) {
  8396. state.lastReturnValue = lastReturnedValue;
  8397. return obs.callback.apply(obs.scope, [eventData, state]);
  8398. });
  8399. }
  8400. else {
  8401. p = p.then(function (lastReturnedValue) {
  8402. state.lastReturnValue = lastReturnedValue;
  8403. return obs.callback(eventData, state);
  8404. });
  8405. }
  8406. if (obs.unregisterOnNextCall) {
  8407. _this._deferUnregister(obs);
  8408. }
  8409. }
  8410. });
  8411. // return the eventData
  8412. return p.then(function () { return eventData; });
  8413. };
  8414. /**
  8415. * Notify a specific observer
  8416. * @param observer defines the observer to notify
  8417. * @param eventData defines the data to be sent to each callback
  8418. * @param mask is used to filter observers defaults to -1
  8419. */
  8420. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8421. if (mask === void 0) { mask = -1; }
  8422. var state = this._eventState;
  8423. state.mask = mask;
  8424. state.skipNextObservers = false;
  8425. observer.callback(eventData, state);
  8426. };
  8427. /**
  8428. * Gets a boolean indicating if the observable has at least one observer
  8429. * @returns true is the Observable has at least one Observer registered
  8430. */
  8431. Observable.prototype.hasObservers = function () {
  8432. return this._observers.length > 0;
  8433. };
  8434. /**
  8435. * Clear the list of observers
  8436. */
  8437. Observable.prototype.clear = function () {
  8438. this._observers = new Array();
  8439. this._onObserverAdded = null;
  8440. };
  8441. /**
  8442. * Clone the current observable
  8443. * @returns a new observable
  8444. */
  8445. Observable.prototype.clone = function () {
  8446. var result = new Observable();
  8447. result._observers = this._observers.slice(0);
  8448. return result;
  8449. };
  8450. /**
  8451. * Does this observable handles observer registered with a given mask
  8452. * @param mask defines the mask to be tested
  8453. * @return whether or not one observer registered with the given mask is handeled
  8454. **/
  8455. Observable.prototype.hasSpecificMask = function (mask) {
  8456. if (mask === void 0) { mask = -1; }
  8457. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8458. var obs = _a[_i];
  8459. if (obs.mask & mask || obs.mask === mask) {
  8460. return true;
  8461. }
  8462. }
  8463. return false;
  8464. };
  8465. return Observable;
  8466. }());
  8467. BABYLON.Observable = Observable;
  8468. })(BABYLON || (BABYLON = {}));
  8469. //# sourceMappingURL=babylon.observable.js.map
  8470. var BABYLON;
  8471. (function (BABYLON) {
  8472. var SmartArray = /** @class */ (function () {
  8473. function SmartArray(capacity) {
  8474. this.length = 0;
  8475. this.data = new Array(capacity);
  8476. this._id = SmartArray._GlobalId++;
  8477. }
  8478. SmartArray.prototype.push = function (value) {
  8479. this.data[this.length++] = value;
  8480. if (this.length > this.data.length) {
  8481. this.data.length *= 2;
  8482. }
  8483. };
  8484. SmartArray.prototype.forEach = function (func) {
  8485. for (var index = 0; index < this.length; index++) {
  8486. func(this.data[index]);
  8487. }
  8488. };
  8489. SmartArray.prototype.sort = function (compareFn) {
  8490. this.data.sort(compareFn);
  8491. };
  8492. SmartArray.prototype.reset = function () {
  8493. this.length = 0;
  8494. };
  8495. SmartArray.prototype.dispose = function () {
  8496. this.reset();
  8497. if (this.data) {
  8498. this.data.length = 0;
  8499. this.data = [];
  8500. }
  8501. };
  8502. SmartArray.prototype.concat = function (array) {
  8503. if (array.length === 0) {
  8504. return;
  8505. }
  8506. if (this.length + array.length > this.data.length) {
  8507. this.data.length = (this.length + array.length) * 2;
  8508. }
  8509. for (var index = 0; index < array.length; index++) {
  8510. this.data[this.length++] = (array.data || array)[index];
  8511. }
  8512. };
  8513. SmartArray.prototype.indexOf = function (value) {
  8514. var position = this.data.indexOf(value);
  8515. if (position >= this.length) {
  8516. return -1;
  8517. }
  8518. return position;
  8519. };
  8520. SmartArray.prototype.contains = function (value) {
  8521. return this.data.indexOf(value) !== -1;
  8522. };
  8523. // Statics
  8524. SmartArray._GlobalId = 0;
  8525. return SmartArray;
  8526. }());
  8527. BABYLON.SmartArray = SmartArray;
  8528. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8529. __extends(SmartArrayNoDuplicate, _super);
  8530. function SmartArrayNoDuplicate() {
  8531. var _this = _super !== null && _super.apply(this, arguments) || this;
  8532. _this._duplicateId = 0;
  8533. return _this;
  8534. }
  8535. SmartArrayNoDuplicate.prototype.push = function (value) {
  8536. _super.prototype.push.call(this, value);
  8537. if (!value.__smartArrayFlags) {
  8538. value.__smartArrayFlags = {};
  8539. }
  8540. value.__smartArrayFlags[this._id] = this._duplicateId;
  8541. };
  8542. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8543. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8544. return false;
  8545. }
  8546. this.push(value);
  8547. return true;
  8548. };
  8549. SmartArrayNoDuplicate.prototype.reset = function () {
  8550. _super.prototype.reset.call(this);
  8551. this._duplicateId++;
  8552. };
  8553. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8554. if (array.length === 0) {
  8555. return;
  8556. }
  8557. if (this.length + array.length > this.data.length) {
  8558. this.data.length = (this.length + array.length) * 2;
  8559. }
  8560. for (var index = 0; index < array.length; index++) {
  8561. var item = (array.data || array)[index];
  8562. this.pushNoDuplicate(item);
  8563. }
  8564. };
  8565. return SmartArrayNoDuplicate;
  8566. }(SmartArray));
  8567. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8568. })(BABYLON || (BABYLON = {}));
  8569. //# sourceMappingURL=babylon.smartArray.js.map
  8570. var BABYLON;
  8571. (function (BABYLON) {
  8572. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8573. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8574. var LoadFileError = /** @class */ (function (_super) {
  8575. __extends(LoadFileError, _super);
  8576. function LoadFileError(message, request) {
  8577. var _this = _super.call(this, message) || this;
  8578. _this.request = request;
  8579. _this.name = "LoadFileError";
  8580. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8581. return _this;
  8582. }
  8583. // Polyfill for Object.setPrototypeOf if necessary.
  8584. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8585. return LoadFileError;
  8586. }(Error));
  8587. BABYLON.LoadFileError = LoadFileError;
  8588. var RetryStrategy = /** @class */ (function () {
  8589. function RetryStrategy() {
  8590. }
  8591. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8592. if (maxRetries === void 0) { maxRetries = 3; }
  8593. if (baseInterval === void 0) { baseInterval = 500; }
  8594. return function (url, request, retryIndex) {
  8595. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8596. return -1;
  8597. }
  8598. return Math.pow(2, retryIndex) * baseInterval;
  8599. };
  8600. };
  8601. return RetryStrategy;
  8602. }());
  8603. BABYLON.RetryStrategy = RetryStrategy;
  8604. // Screenshots
  8605. var screenshotCanvas;
  8606. var cloneValue = function (source, destinationObject) {
  8607. if (!source)
  8608. return null;
  8609. if (source instanceof BABYLON.Mesh) {
  8610. return null;
  8611. }
  8612. if (source instanceof BABYLON.SubMesh) {
  8613. return source.clone(destinationObject);
  8614. }
  8615. else if (source.clone) {
  8616. return source.clone();
  8617. }
  8618. return null;
  8619. };
  8620. var Tools = /** @class */ (function () {
  8621. function Tools() {
  8622. }
  8623. /**
  8624. * Interpolates between a and b via alpha
  8625. * @param a The lower value (returned when alpha = 0)
  8626. * @param b The upper value (returned when alpha = 1)
  8627. * @param alpha The interpolation-factor
  8628. * @return The mixed value
  8629. */
  8630. Tools.Mix = function (a, b, alpha) {
  8631. return a * (1 - alpha) + b * alpha;
  8632. };
  8633. Tools.Instantiate = function (className) {
  8634. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8635. return Tools.RegisteredExternalClasses[className];
  8636. }
  8637. var arr = className.split(".");
  8638. var fn = (window || this);
  8639. for (var i = 0, len = arr.length; i < len; i++) {
  8640. fn = fn[arr[i]];
  8641. }
  8642. if (typeof fn !== "function") {
  8643. return null;
  8644. }
  8645. return fn;
  8646. };
  8647. /**
  8648. * Provides a slice function that will work even on IE
  8649. * @param data defines the array to slice
  8650. * @param start defines the start of the data (optional)
  8651. * @param end defines the end of the data (optional)
  8652. * @returns the new sliced array
  8653. */
  8654. Tools.Slice = function (data, start, end) {
  8655. if (data.slice) {
  8656. return data.slice(start, end);
  8657. }
  8658. return Array.prototype.slice.call(data, start, end);
  8659. };
  8660. Tools.SetImmediate = function (action) {
  8661. if (window.setImmediate) {
  8662. window.setImmediate(action);
  8663. }
  8664. else {
  8665. setTimeout(action, 1);
  8666. }
  8667. };
  8668. Tools.IsExponentOfTwo = function (value) {
  8669. var count = 1;
  8670. do {
  8671. count *= 2;
  8672. } while (count < value);
  8673. return count === value;
  8674. };
  8675. /**
  8676. * Returns the nearest 32-bit single precision float representation of a Number
  8677. * @param value A Number. If the parameter is of a different type, it will get converted
  8678. * to a number or to NaN if it cannot be converted
  8679. * @returns number
  8680. */
  8681. Tools.FloatRound = function (value) {
  8682. if (Math.fround) {
  8683. return Math.fround(value);
  8684. }
  8685. return (Tools._tmpFloatArray[0] = value);
  8686. };
  8687. /**
  8688. * Find the next highest power of two.
  8689. * @param x Number to start search from.
  8690. * @return Next highest power of two.
  8691. */
  8692. Tools.CeilingPOT = function (x) {
  8693. x--;
  8694. x |= x >> 1;
  8695. x |= x >> 2;
  8696. x |= x >> 4;
  8697. x |= x >> 8;
  8698. x |= x >> 16;
  8699. x++;
  8700. return x;
  8701. };
  8702. /**
  8703. * Find the next lowest power of two.
  8704. * @param x Number to start search from.
  8705. * @return Next lowest power of two.
  8706. */
  8707. Tools.FloorPOT = function (x) {
  8708. x = x | (x >> 1);
  8709. x = x | (x >> 2);
  8710. x = x | (x >> 4);
  8711. x = x | (x >> 8);
  8712. x = x | (x >> 16);
  8713. return x - (x >> 1);
  8714. };
  8715. /**
  8716. * Find the nearest power of two.
  8717. * @param x Number to start search from.
  8718. * @return Next nearest power of two.
  8719. */
  8720. Tools.NearestPOT = function (x) {
  8721. var c = Tools.CeilingPOT(x);
  8722. var f = Tools.FloorPOT(x);
  8723. return (c - x) > (x - f) ? f : c;
  8724. };
  8725. Tools.GetExponentOfTwo = function (value, max, mode) {
  8726. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8727. var pot;
  8728. switch (mode) {
  8729. case BABYLON.Engine.SCALEMODE_FLOOR:
  8730. pot = Tools.FloorPOT(value);
  8731. break;
  8732. case BABYLON.Engine.SCALEMODE_NEAREST:
  8733. pot = Tools.NearestPOT(value);
  8734. break;
  8735. case BABYLON.Engine.SCALEMODE_CEILING:
  8736. default:
  8737. pot = Tools.CeilingPOT(value);
  8738. break;
  8739. }
  8740. return Math.min(pot, max);
  8741. };
  8742. Tools.GetFilename = function (path) {
  8743. var index = path.lastIndexOf("/");
  8744. if (index < 0)
  8745. return path;
  8746. return path.substring(index + 1);
  8747. };
  8748. /**
  8749. * Extracts the "folder" part of a path (everything before the filename).
  8750. * @param uri The URI to extract the info from
  8751. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8752. * @returns The "folder" part of the path
  8753. */
  8754. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8755. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8756. var index = uri.lastIndexOf("/");
  8757. if (index < 0) {
  8758. if (returnUnchangedIfNoSlash) {
  8759. return uri;
  8760. }
  8761. return "";
  8762. }
  8763. return uri.substring(0, index + 1);
  8764. };
  8765. Tools.GetDOMTextContent = function (element) {
  8766. var result = "";
  8767. var child = element.firstChild;
  8768. while (child) {
  8769. if (child.nodeType === 3) {
  8770. result += child.textContent;
  8771. }
  8772. child = child.nextSibling;
  8773. }
  8774. return result;
  8775. };
  8776. Tools.ToDegrees = function (angle) {
  8777. return angle * 180 / Math.PI;
  8778. };
  8779. Tools.ToRadians = function (angle) {
  8780. return angle * Math.PI / 180;
  8781. };
  8782. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8783. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8784. var output = "";
  8785. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8786. var i = 0;
  8787. var bytes = new Uint8Array(buffer);
  8788. while (i < bytes.length) {
  8789. chr1 = bytes[i++];
  8790. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8791. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8792. enc1 = chr1 >> 2;
  8793. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8794. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8795. enc4 = chr3 & 63;
  8796. if (isNaN(chr2)) {
  8797. enc3 = enc4 = 64;
  8798. }
  8799. else if (isNaN(chr3)) {
  8800. enc4 = 64;
  8801. }
  8802. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8803. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8804. }
  8805. return "data:image/png;base64," + output;
  8806. };
  8807. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8808. if (bias === void 0) { bias = null; }
  8809. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8810. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8811. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8812. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8813. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8814. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8815. }
  8816. if (bias) {
  8817. minimum.x -= minimum.x * bias.x + bias.y;
  8818. minimum.y -= minimum.y * bias.x + bias.y;
  8819. minimum.z -= minimum.z * bias.x + bias.y;
  8820. maximum.x += maximum.x * bias.x + bias.y;
  8821. maximum.y += maximum.y * bias.x + bias.y;
  8822. maximum.z += maximum.z * bias.x + bias.y;
  8823. }
  8824. return {
  8825. minimum: minimum,
  8826. maximum: maximum
  8827. };
  8828. };
  8829. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8830. if (bias === void 0) { bias = null; }
  8831. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8832. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8833. if (!stride) {
  8834. stride = 3;
  8835. }
  8836. for (var index = start; index < start + count; index++) {
  8837. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8838. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8839. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8840. }
  8841. if (bias) {
  8842. minimum.x -= minimum.x * bias.x + bias.y;
  8843. minimum.y -= minimum.y * bias.x + bias.y;
  8844. minimum.z -= minimum.z * bias.x + bias.y;
  8845. maximum.x += maximum.x * bias.x + bias.y;
  8846. maximum.y += maximum.y * bias.x + bias.y;
  8847. maximum.z += maximum.z * bias.x + bias.y;
  8848. }
  8849. return {
  8850. minimum: minimum,
  8851. maximum: maximum
  8852. };
  8853. };
  8854. Tools.Vector2ArrayFeeder = function (array) {
  8855. return function (index) {
  8856. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8857. var length = isFloatArray ? array.length / 2 : array.length;
  8858. if (index >= length) {
  8859. return null;
  8860. }
  8861. if (isFloatArray) {
  8862. var fa = array;
  8863. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8864. }
  8865. var a = array;
  8866. return a[index];
  8867. };
  8868. };
  8869. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8870. if (bias === void 0) { bias = null; }
  8871. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8872. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8873. var i = 0;
  8874. var cur = feeder(i++);
  8875. while (cur) {
  8876. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8877. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8878. cur = feeder(i++);
  8879. }
  8880. if (bias) {
  8881. minimum.x -= minimum.x * bias.x + bias.y;
  8882. minimum.y -= minimum.y * bias.x + bias.y;
  8883. maximum.x += maximum.x * bias.x + bias.y;
  8884. maximum.y += maximum.y * bias.x + bias.y;
  8885. }
  8886. return {
  8887. minimum: minimum,
  8888. maximum: maximum
  8889. };
  8890. };
  8891. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8892. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8893. return null;
  8894. return Array.isArray(obj) ? obj : [obj];
  8895. };
  8896. // Misc.
  8897. Tools.GetPointerPrefix = function () {
  8898. var eventPrefix = "pointer";
  8899. // Check if pointer events are supported
  8900. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8901. eventPrefix = "mouse";
  8902. }
  8903. return eventPrefix;
  8904. };
  8905. /**
  8906. * @param func - the function to be called
  8907. * @param requester - the object that will request the next frame. Falls back to window.
  8908. */
  8909. Tools.QueueNewFrame = function (func, requester) {
  8910. if (!Tools.IsWindowObjectExist()) {
  8911. return setTimeout(func, 16);
  8912. }
  8913. if (!requester) {
  8914. requester = window;
  8915. }
  8916. if (requester.requestAnimationFrame) {
  8917. return requester.requestAnimationFrame(func);
  8918. }
  8919. else if (requester.msRequestAnimationFrame) {
  8920. return requester.msRequestAnimationFrame(func);
  8921. }
  8922. else if (requester.webkitRequestAnimationFrame) {
  8923. return requester.webkitRequestAnimationFrame(func);
  8924. }
  8925. else if (requester.mozRequestAnimationFrame) {
  8926. return requester.mozRequestAnimationFrame(func);
  8927. }
  8928. else if (requester.oRequestAnimationFrame) {
  8929. return requester.oRequestAnimationFrame(func);
  8930. }
  8931. else {
  8932. return window.setTimeout(func, 16);
  8933. }
  8934. };
  8935. Tools.RequestFullscreen = function (element) {
  8936. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8937. if (!requestFunction)
  8938. return;
  8939. requestFunction.call(element);
  8940. };
  8941. Tools.ExitFullscreen = function () {
  8942. if (document.exitFullscreen) {
  8943. document.exitFullscreen();
  8944. }
  8945. else if (document.mozCancelFullScreen) {
  8946. document.mozCancelFullScreen();
  8947. }
  8948. else if (document.webkitCancelFullScreen) {
  8949. document.webkitCancelFullScreen();
  8950. }
  8951. else if (document.msCancelFullScreen) {
  8952. document.msCancelFullScreen();
  8953. }
  8954. };
  8955. Tools.SetCorsBehavior = function (url, element) {
  8956. if (url && url.indexOf("data:") === 0) {
  8957. return;
  8958. }
  8959. if (Tools.CorsBehavior) {
  8960. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8961. element.crossOrigin = Tools.CorsBehavior;
  8962. }
  8963. else {
  8964. var result = Tools.CorsBehavior(url);
  8965. if (result) {
  8966. element.crossOrigin = result;
  8967. }
  8968. }
  8969. }
  8970. };
  8971. // External files
  8972. Tools.CleanUrl = function (url) {
  8973. url = url.replace(/#/mg, "%23");
  8974. return url;
  8975. };
  8976. /**
  8977. * Loads an image as an HTMLImageElement.
  8978. * @param input url string, ArrayBuffer, or Blob to load
  8979. * @param onLoad callback called when the image successfully loads
  8980. * @param onError callback called when the image fails to load
  8981. * @param database database for caching
  8982. * @returns the HTMLImageElement of the loaded image
  8983. */
  8984. Tools.LoadImage = function (input, onLoad, onError, database) {
  8985. var url;
  8986. var usingObjectURL = false;
  8987. if (input instanceof ArrayBuffer) {
  8988. url = URL.createObjectURL(new Blob([input]));
  8989. usingObjectURL = true;
  8990. }
  8991. else if (input instanceof Blob) {
  8992. url = URL.createObjectURL(input);
  8993. usingObjectURL = true;
  8994. }
  8995. else {
  8996. url = Tools.CleanUrl(input);
  8997. url = Tools.PreprocessUrl(input);
  8998. }
  8999. var img = new Image();
  9000. Tools.SetCorsBehavior(url, img);
  9001. var loadHandler = function () {
  9002. if (usingObjectURL && img.src) {
  9003. URL.revokeObjectURL(img.src);
  9004. }
  9005. img.removeEventListener("load", loadHandler);
  9006. img.removeEventListener("error", errorHandler);
  9007. onLoad(img);
  9008. };
  9009. var errorHandler = function (err) {
  9010. if (usingObjectURL && img.src) {
  9011. URL.revokeObjectURL(img.src);
  9012. }
  9013. img.removeEventListener("load", loadHandler);
  9014. img.removeEventListener("error", errorHandler);
  9015. Tools.Error("Error while trying to load image: " + input);
  9016. if (onError) {
  9017. onError("Error while trying to load image: " + input, err);
  9018. }
  9019. };
  9020. img.addEventListener("load", loadHandler);
  9021. img.addEventListener("error", errorHandler);
  9022. var noIndexedDB = function () {
  9023. img.src = url;
  9024. };
  9025. var loadFromIndexedDB = function () {
  9026. if (database) {
  9027. database.loadImageFromDB(url, img);
  9028. }
  9029. };
  9030. //ANY database to do!
  9031. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9032. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9033. }
  9034. else {
  9035. if (url.indexOf("file:") !== -1) {
  9036. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9037. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9038. try {
  9039. var blobURL;
  9040. try {
  9041. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9042. }
  9043. catch (ex) {
  9044. // Chrome doesn't support oneTimeOnly parameter
  9045. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9046. }
  9047. img.src = blobURL;
  9048. usingObjectURL = true;
  9049. }
  9050. catch (e) {
  9051. img.src = "";
  9052. }
  9053. return img;
  9054. }
  9055. }
  9056. noIndexedDB();
  9057. }
  9058. return img;
  9059. };
  9060. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9061. url = Tools.CleanUrl(url);
  9062. url = Tools.PreprocessUrl(url);
  9063. // If file and file input are set
  9064. if (url.indexOf("file:") !== -1) {
  9065. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9066. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9067. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9068. }
  9069. }
  9070. var loadUrl = Tools.BaseUrl + url;
  9071. var aborted = false;
  9072. var fileRequest = {
  9073. onCompleteObservable: new BABYLON.Observable(),
  9074. abort: function () { return aborted = true; },
  9075. };
  9076. var requestFile = function () {
  9077. var request = new XMLHttpRequest();
  9078. var retryHandle = null;
  9079. fileRequest.abort = function () {
  9080. aborted = true;
  9081. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9082. request.abort();
  9083. }
  9084. if (retryHandle !== null) {
  9085. clearTimeout(retryHandle);
  9086. retryHandle = null;
  9087. }
  9088. };
  9089. var retryLoop = function (retryIndex) {
  9090. request.open('GET', loadUrl, true);
  9091. if (useArrayBuffer) {
  9092. request.responseType = "arraybuffer";
  9093. }
  9094. if (onProgress) {
  9095. request.addEventListener("progress", onProgress);
  9096. }
  9097. var onLoadEnd = function () {
  9098. request.removeEventListener("loadend", onLoadEnd);
  9099. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9100. fileRequest.onCompleteObservable.clear();
  9101. };
  9102. request.addEventListener("loadend", onLoadEnd);
  9103. var onReadyStateChange = function () {
  9104. if (aborted) {
  9105. return;
  9106. }
  9107. // In case of undefined state in some browsers.
  9108. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9109. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9110. request.removeEventListener("readystatechange", onReadyStateChange);
  9111. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9112. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9113. return;
  9114. }
  9115. var retryStrategy = Tools.DefaultRetryStrategy;
  9116. if (retryStrategy) {
  9117. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9118. if (waitTime !== -1) {
  9119. // Prevent the request from completing for retry.
  9120. request.removeEventListener("loadend", onLoadEnd);
  9121. request = new XMLHttpRequest();
  9122. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9123. return;
  9124. }
  9125. }
  9126. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9127. if (onError) {
  9128. onError(request, e);
  9129. }
  9130. else {
  9131. throw e;
  9132. }
  9133. }
  9134. };
  9135. request.addEventListener("readystatechange", onReadyStateChange);
  9136. request.send();
  9137. };
  9138. retryLoop(0);
  9139. };
  9140. // Caching all files
  9141. if (database && database.enableSceneOffline) {
  9142. var noIndexedDB_1 = function () {
  9143. if (!aborted) {
  9144. requestFile();
  9145. }
  9146. };
  9147. var loadFromIndexedDB = function () {
  9148. // TODO: database needs to support aborting and should return a IFileRequest
  9149. if (aborted) {
  9150. return;
  9151. }
  9152. if (database) {
  9153. database.loadFileFromDB(url, function (data) {
  9154. if (!aborted) {
  9155. onSuccess(data);
  9156. }
  9157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9158. }, onProgress ? function (event) {
  9159. if (!aborted) {
  9160. onProgress(event);
  9161. }
  9162. } : undefined, noIndexedDB_1, useArrayBuffer);
  9163. }
  9164. };
  9165. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9166. }
  9167. else {
  9168. requestFile();
  9169. }
  9170. return fileRequest;
  9171. };
  9172. /**
  9173. * Load a script (identified by an url). When the url returns, the
  9174. * content of this file is added into a new script element, attached to the DOM (body element)
  9175. */
  9176. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9177. var head = document.getElementsByTagName('head')[0];
  9178. var script = document.createElement('script');
  9179. script.type = 'text/javascript';
  9180. script.src = scriptUrl;
  9181. script.onload = function () {
  9182. if (onSuccess) {
  9183. onSuccess();
  9184. }
  9185. };
  9186. script.onerror = function (e) {
  9187. if (onError) {
  9188. onError("Unable to load script '" + scriptUrl + "'", e);
  9189. }
  9190. };
  9191. head.appendChild(script);
  9192. };
  9193. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9194. var reader = new FileReader();
  9195. var request = {
  9196. onCompleteObservable: new BABYLON.Observable(),
  9197. abort: function () { return reader.abort(); },
  9198. };
  9199. reader.onloadend = function (e) {
  9200. request.onCompleteObservable.notifyObservers(request);
  9201. };
  9202. reader.onload = function (e) {
  9203. //target doesn't have result from ts 1.3
  9204. callback(e.target['result']);
  9205. };
  9206. reader.onprogress = progressCallback;
  9207. reader.readAsDataURL(fileToLoad);
  9208. return request;
  9209. };
  9210. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9211. var reader = new FileReader();
  9212. var request = {
  9213. onCompleteObservable: new BABYLON.Observable(),
  9214. abort: function () { return reader.abort(); },
  9215. };
  9216. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9217. reader.onerror = function (e) {
  9218. Tools.Log("Error while reading file: " + fileToLoad.name);
  9219. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9220. };
  9221. reader.onload = function (e) {
  9222. //target doesn't have result from ts 1.3
  9223. callback(e.target['result']);
  9224. };
  9225. if (progressCallBack) {
  9226. reader.onprogress = progressCallBack;
  9227. }
  9228. if (!useArrayBuffer) {
  9229. // Asynchronous read
  9230. reader.readAsText(fileToLoad);
  9231. }
  9232. else {
  9233. reader.readAsArrayBuffer(fileToLoad);
  9234. }
  9235. return request;
  9236. };
  9237. //returns a downloadable url to a file content.
  9238. Tools.FileAsURL = function (content) {
  9239. var fileBlob = new Blob([content]);
  9240. var url = window.URL || window.webkitURL;
  9241. var link = url.createObjectURL(fileBlob);
  9242. return link;
  9243. };
  9244. // Misc.
  9245. Tools.Format = function (value, decimals) {
  9246. if (decimals === void 0) { decimals = 2; }
  9247. return value.toFixed(decimals);
  9248. };
  9249. Tools.CheckExtends = function (v, min, max) {
  9250. if (v.x < min.x)
  9251. min.x = v.x;
  9252. if (v.y < min.y)
  9253. min.y = v.y;
  9254. if (v.z < min.z)
  9255. min.z = v.z;
  9256. if (v.x > max.x)
  9257. max.x = v.x;
  9258. if (v.y > max.y)
  9259. max.y = v.y;
  9260. if (v.z > max.z)
  9261. max.z = v.z;
  9262. };
  9263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9264. for (var prop in source) {
  9265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9266. continue;
  9267. }
  9268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9269. continue;
  9270. }
  9271. var sourceValue = source[prop];
  9272. var typeOfSourceValue = typeof sourceValue;
  9273. if (typeOfSourceValue === "function") {
  9274. continue;
  9275. }
  9276. try {
  9277. if (typeOfSourceValue === "object") {
  9278. if (sourceValue instanceof Array) {
  9279. destination[prop] = [];
  9280. if (sourceValue.length > 0) {
  9281. if (typeof sourceValue[0] == "object") {
  9282. for (var index = 0; index < sourceValue.length; index++) {
  9283. var clonedValue = cloneValue(sourceValue[index], destination);
  9284. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9285. destination[prop].push(clonedValue);
  9286. }
  9287. }
  9288. }
  9289. else {
  9290. destination[prop] = sourceValue.slice(0);
  9291. }
  9292. }
  9293. }
  9294. else {
  9295. destination[prop] = cloneValue(sourceValue, destination);
  9296. }
  9297. }
  9298. else {
  9299. destination[prop] = sourceValue;
  9300. }
  9301. }
  9302. catch (e) {
  9303. // Just ignore error (it could be because of a read-only property)
  9304. }
  9305. }
  9306. };
  9307. Tools.IsEmpty = function (obj) {
  9308. for (var i in obj) {
  9309. if (obj.hasOwnProperty(i)) {
  9310. return false;
  9311. }
  9312. }
  9313. return true;
  9314. };
  9315. Tools.RegisterTopRootEvents = function (events) {
  9316. for (var index = 0; index < events.length; index++) {
  9317. var event = events[index];
  9318. window.addEventListener(event.name, event.handler, false);
  9319. try {
  9320. if (window.parent) {
  9321. window.parent.addEventListener(event.name, event.handler, false);
  9322. }
  9323. }
  9324. catch (e) {
  9325. // Silently fails...
  9326. }
  9327. }
  9328. };
  9329. Tools.UnregisterTopRootEvents = function (events) {
  9330. for (var index = 0; index < events.length; index++) {
  9331. var event = events[index];
  9332. window.removeEventListener(event.name, event.handler);
  9333. try {
  9334. if (window.parent) {
  9335. window.parent.removeEventListener(event.name, event.handler);
  9336. }
  9337. }
  9338. catch (e) {
  9339. // Silently fails...
  9340. }
  9341. }
  9342. };
  9343. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9344. if (mimeType === void 0) { mimeType = "image/png"; }
  9345. // Read the contents of the framebuffer
  9346. var numberOfChannelsByLine = width * 4;
  9347. var halfHeight = height / 2;
  9348. //Reading datas from WebGL
  9349. var data = engine.readPixels(0, 0, width, height);
  9350. //To flip image on Y axis.
  9351. for (var i = 0; i < halfHeight; i++) {
  9352. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9353. var currentCell = j + i * numberOfChannelsByLine;
  9354. var targetLine = height - i - 1;
  9355. var targetCell = j + targetLine * numberOfChannelsByLine;
  9356. var temp = data[currentCell];
  9357. data[currentCell] = data[targetCell];
  9358. data[targetCell] = temp;
  9359. }
  9360. }
  9361. // Create a 2D canvas to store the result
  9362. if (!screenshotCanvas) {
  9363. screenshotCanvas = document.createElement('canvas');
  9364. }
  9365. screenshotCanvas.width = width;
  9366. screenshotCanvas.height = height;
  9367. var context = screenshotCanvas.getContext('2d');
  9368. if (context) {
  9369. // Copy the pixels to a 2D canvas
  9370. var imageData = context.createImageData(width, height);
  9371. var castData = (imageData.data);
  9372. castData.set(data);
  9373. context.putImageData(imageData, 0, 0);
  9374. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9375. }
  9376. };
  9377. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9378. if (mimeType === void 0) { mimeType = "image/png"; }
  9379. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9380. if (successCallback) {
  9381. successCallback(base64Image);
  9382. }
  9383. else {
  9384. // We need HTMLCanvasElement.toBlob for HD screenshots
  9385. if (!screenshotCanvas.toBlob) {
  9386. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9387. screenshotCanvas.toBlob = function (callback, type, quality) {
  9388. var _this = this;
  9389. setTimeout(function () {
  9390. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9391. for (var i = 0; i < len; i++) {
  9392. arr[i] = binStr.charCodeAt(i);
  9393. }
  9394. callback(new Blob([arr], { type: type || 'image/png' }));
  9395. });
  9396. };
  9397. }
  9398. screenshotCanvas.toBlob(function (blob) {
  9399. var url = URL.createObjectURL(blob);
  9400. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9401. if (("download" in document.createElement("a"))) {
  9402. var a = window.document.createElement("a");
  9403. a.href = url;
  9404. if (fileName) {
  9405. a.setAttribute("download", fileName);
  9406. }
  9407. else {
  9408. var date = new Date();
  9409. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9410. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9411. }
  9412. window.document.body.appendChild(a);
  9413. a.addEventListener("click", function () {
  9414. if (a.parentElement) {
  9415. a.parentElement.removeChild(a);
  9416. }
  9417. });
  9418. a.click();
  9419. }
  9420. else {
  9421. var newWindow = window.open("");
  9422. if (!newWindow)
  9423. return;
  9424. var img = newWindow.document.createElement("img");
  9425. img.onload = function () {
  9426. // no longer need to read the blob so it's revoked
  9427. URL.revokeObjectURL(url);
  9428. };
  9429. img.src = url;
  9430. newWindow.document.body.appendChild(img);
  9431. }
  9432. });
  9433. }
  9434. };
  9435. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9436. if (mimeType === void 0) { mimeType = "image/png"; }
  9437. var width;
  9438. var height;
  9439. // If a precision value is specified
  9440. if (size.precision) {
  9441. width = Math.round(engine.getRenderWidth() * size.precision);
  9442. height = Math.round(width / engine.getAspectRatio(camera));
  9443. }
  9444. else if (size.width && size.height) {
  9445. width = size.width;
  9446. height = size.height;
  9447. }
  9448. //If passing only width, computing height to keep display canvas ratio.
  9449. else if (size.width && !size.height) {
  9450. width = size.width;
  9451. height = Math.round(width / engine.getAspectRatio(camera));
  9452. }
  9453. //If passing only height, computing width to keep display canvas ratio.
  9454. else if (size.height && !size.width) {
  9455. height = size.height;
  9456. width = Math.round(height * engine.getAspectRatio(camera));
  9457. }
  9458. //Assuming here that "size" parameter is a number
  9459. else if (!isNaN(size)) {
  9460. height = size;
  9461. width = size;
  9462. }
  9463. else {
  9464. Tools.Error("Invalid 'size' parameter !");
  9465. return;
  9466. }
  9467. if (!screenshotCanvas) {
  9468. screenshotCanvas = document.createElement('canvas');
  9469. }
  9470. screenshotCanvas.width = width;
  9471. screenshotCanvas.height = height;
  9472. var renderContext = screenshotCanvas.getContext("2d");
  9473. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9474. var newWidth = width;
  9475. var newHeight = newWidth / ratio;
  9476. if (newHeight > height) {
  9477. newHeight = height;
  9478. newWidth = newHeight * ratio;
  9479. }
  9480. var offsetX = Math.max(0, width - newWidth) / 2;
  9481. var offsetY = Math.max(0, height - newHeight) / 2;
  9482. var renderingCanvas = engine.getRenderingCanvas();
  9483. if (renderContext && renderingCanvas) {
  9484. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9485. }
  9486. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9487. };
  9488. /**
  9489. * Generates an image screenshot from the specified camera.
  9490. *
  9491. * @param engine The engine to use for rendering
  9492. * @param camera The camera to use for rendering
  9493. * @param size This parameter can be set to a single number or to an object with the
  9494. * following (optional) properties: precision, width, height. If a single number is passed,
  9495. * it will be used for both width and height. If an object is passed, the screenshot size
  9496. * will be derived from the parameters. The precision property is a multiplier allowing
  9497. * rendering at a higher or lower resolution.
  9498. * @param successCallback The callback receives a single parameter which contains the
  9499. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9500. * src parameter of an <img> to display it.
  9501. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9502. * Check your browser for supported MIME types.
  9503. * @param samples Texture samples (default: 1)
  9504. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9505. * @param fileName A name for for the downloaded file.
  9506. * @constructor
  9507. */
  9508. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9509. if (mimeType === void 0) { mimeType = "image/png"; }
  9510. if (samples === void 0) { samples = 1; }
  9511. if (antialiasing === void 0) { antialiasing = false; }
  9512. var width;
  9513. var height;
  9514. //If a precision value is specified
  9515. if (size.precision) {
  9516. width = Math.round(engine.getRenderWidth() * size.precision);
  9517. height = Math.round(width / engine.getAspectRatio(camera));
  9518. size = { width: width, height: height };
  9519. }
  9520. else if (size.width && size.height) {
  9521. width = size.width;
  9522. height = size.height;
  9523. }
  9524. //If passing only width, computing height to keep display canvas ratio.
  9525. else if (size.width && !size.height) {
  9526. width = size.width;
  9527. height = Math.round(width / engine.getAspectRatio(camera));
  9528. size = { width: width, height: height };
  9529. }
  9530. //If passing only height, computing width to keep display canvas ratio.
  9531. else if (size.height && !size.width) {
  9532. height = size.height;
  9533. width = Math.round(height * engine.getAspectRatio(camera));
  9534. size = { width: width, height: height };
  9535. }
  9536. //Assuming here that "size" parameter is a number
  9537. else if (!isNaN(size)) {
  9538. height = size;
  9539. width = size;
  9540. }
  9541. else {
  9542. Tools.Error("Invalid 'size' parameter !");
  9543. return;
  9544. }
  9545. var scene = camera.getScene();
  9546. var previousCamera = null;
  9547. if (scene.activeCamera !== camera) {
  9548. previousCamera = scene.activeCamera;
  9549. scene.activeCamera = camera;
  9550. }
  9551. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9552. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9553. texture.renderList = null;
  9554. texture.samples = samples;
  9555. if (antialiasing) {
  9556. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9557. }
  9558. texture.onAfterRenderObservable.add(function () {
  9559. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9560. });
  9561. scene.incrementRenderId();
  9562. scene.resetCachedMaterial();
  9563. texture.render(true);
  9564. texture.dispose();
  9565. if (previousCamera) {
  9566. scene.activeCamera = previousCamera;
  9567. }
  9568. camera.getProjectionMatrix(true); // Force cache refresh;
  9569. };
  9570. // XHR response validator for local file scenario
  9571. Tools.ValidateXHRData = function (xhr, dataType) {
  9572. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9573. if (dataType === void 0) { dataType = 7; }
  9574. try {
  9575. if (dataType & 1) {
  9576. if (xhr.responseText && xhr.responseText.length > 0) {
  9577. return true;
  9578. }
  9579. else if (dataType === 1) {
  9580. return false;
  9581. }
  9582. }
  9583. if (dataType & 2) {
  9584. // Check header width and height since there is no "TGA" magic number
  9585. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9586. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9587. return true;
  9588. }
  9589. else if (dataType === 2) {
  9590. return false;
  9591. }
  9592. }
  9593. if (dataType & 4) {
  9594. // Check for the "DDS" magic number
  9595. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9596. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9597. return true;
  9598. }
  9599. else {
  9600. return false;
  9601. }
  9602. }
  9603. }
  9604. catch (e) {
  9605. // Global protection
  9606. }
  9607. return false;
  9608. };
  9609. /**
  9610. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9611. * Be aware Math.random() could cause collisions, but:
  9612. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9613. */
  9614. Tools.RandomId = function () {
  9615. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9616. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9617. return v.toString(16);
  9618. });
  9619. };
  9620. /**
  9621. * Test if the given uri is a base64 string.
  9622. * @param uri The uri to test
  9623. * @return True if the uri is a base64 string or false otherwise.
  9624. */
  9625. Tools.IsBase64 = function (uri) {
  9626. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9627. };
  9628. /**
  9629. * Decode the given base64 uri.
  9630. * @param uri The uri to decode
  9631. * @return The decoded base64 data.
  9632. */
  9633. Tools.DecodeBase64 = function (uri) {
  9634. var decodedString = atob(uri.split(",")[1]);
  9635. var bufferLength = decodedString.length;
  9636. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9637. for (var i = 0; i < bufferLength; i++) {
  9638. bufferView[i] = decodedString.charCodeAt(i);
  9639. }
  9640. return bufferView.buffer;
  9641. };
  9642. Object.defineProperty(Tools, "NoneLogLevel", {
  9643. get: function () {
  9644. return Tools._NoneLogLevel;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. Object.defineProperty(Tools, "MessageLogLevel", {
  9650. get: function () {
  9651. return Tools._MessageLogLevel;
  9652. },
  9653. enumerable: true,
  9654. configurable: true
  9655. });
  9656. Object.defineProperty(Tools, "WarningLogLevel", {
  9657. get: function () {
  9658. return Tools._WarningLogLevel;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(Tools, "ErrorLogLevel", {
  9664. get: function () {
  9665. return Tools._ErrorLogLevel;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(Tools, "AllLogLevel", {
  9671. get: function () {
  9672. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Tools._AddLogEntry = function (entry) {
  9678. Tools._LogCache = entry + Tools._LogCache;
  9679. if (Tools.OnNewCacheEntry) {
  9680. Tools.OnNewCacheEntry(entry);
  9681. }
  9682. };
  9683. Tools._FormatMessage = function (message) {
  9684. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9685. var date = new Date();
  9686. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9687. };
  9688. Tools._LogDisabled = function (message) {
  9689. // nothing to do
  9690. };
  9691. Tools._LogEnabled = function (message) {
  9692. var formattedMessage = Tools._FormatMessage(message);
  9693. console.log("BJS - " + formattedMessage);
  9694. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9695. Tools._AddLogEntry(entry);
  9696. };
  9697. Tools._WarnDisabled = function (message) {
  9698. // nothing to do
  9699. };
  9700. Tools._WarnEnabled = function (message) {
  9701. var formattedMessage = Tools._FormatMessage(message);
  9702. console.warn("BJS - " + formattedMessage);
  9703. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9704. Tools._AddLogEntry(entry);
  9705. };
  9706. Tools._ErrorDisabled = function (message) {
  9707. // nothing to do
  9708. };
  9709. Tools._ErrorEnabled = function (message) {
  9710. Tools.errorsCount++;
  9711. var formattedMessage = Tools._FormatMessage(message);
  9712. console.error("BJS - " + formattedMessage);
  9713. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9714. Tools._AddLogEntry(entry);
  9715. };
  9716. Object.defineProperty(Tools, "LogCache", {
  9717. get: function () {
  9718. return Tools._LogCache;
  9719. },
  9720. enumerable: true,
  9721. configurable: true
  9722. });
  9723. Tools.ClearLogCache = function () {
  9724. Tools._LogCache = "";
  9725. Tools.errorsCount = 0;
  9726. };
  9727. Object.defineProperty(Tools, "LogLevels", {
  9728. set: function (level) {
  9729. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9730. Tools.Log = Tools._LogEnabled;
  9731. }
  9732. else {
  9733. Tools.Log = Tools._LogDisabled;
  9734. }
  9735. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9736. Tools.Warn = Tools._WarnEnabled;
  9737. }
  9738. else {
  9739. Tools.Warn = Tools._WarnDisabled;
  9740. }
  9741. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9742. Tools.Error = Tools._ErrorEnabled;
  9743. }
  9744. else {
  9745. Tools.Error = Tools._ErrorDisabled;
  9746. }
  9747. },
  9748. enumerable: true,
  9749. configurable: true
  9750. });
  9751. Tools.IsWindowObjectExist = function () {
  9752. return (typeof window) !== "undefined";
  9753. };
  9754. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9755. get: function () {
  9756. return Tools._PerformanceNoneLogLevel;
  9757. },
  9758. enumerable: true,
  9759. configurable: true
  9760. });
  9761. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9762. get: function () {
  9763. return Tools._PerformanceUserMarkLogLevel;
  9764. },
  9765. enumerable: true,
  9766. configurable: true
  9767. });
  9768. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9769. get: function () {
  9770. return Tools._PerformanceConsoleLogLevel;
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9776. set: function (level) {
  9777. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9778. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9779. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9780. return;
  9781. }
  9782. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9783. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9784. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9785. return;
  9786. }
  9787. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9788. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9789. },
  9790. enumerable: true,
  9791. configurable: true
  9792. });
  9793. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9794. };
  9795. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9796. };
  9797. Tools._StartUserMark = function (counterName, condition) {
  9798. if (condition === void 0) { condition = true; }
  9799. if (!Tools._performance) {
  9800. if (!Tools.IsWindowObjectExist()) {
  9801. return;
  9802. }
  9803. Tools._performance = window.performance;
  9804. }
  9805. if (!condition || !Tools._performance.mark) {
  9806. return;
  9807. }
  9808. Tools._performance.mark(counterName + "-Begin");
  9809. };
  9810. Tools._EndUserMark = function (counterName, condition) {
  9811. if (condition === void 0) { condition = true; }
  9812. if (!condition || !Tools._performance.mark) {
  9813. return;
  9814. }
  9815. Tools._performance.mark(counterName + "-End");
  9816. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9817. };
  9818. Tools._StartPerformanceConsole = function (counterName, condition) {
  9819. if (condition === void 0) { condition = true; }
  9820. if (!condition) {
  9821. return;
  9822. }
  9823. Tools._StartUserMark(counterName, condition);
  9824. if (console.time) {
  9825. console.time(counterName);
  9826. }
  9827. };
  9828. Tools._EndPerformanceConsole = function (counterName, condition) {
  9829. if (condition === void 0) { condition = true; }
  9830. if (!condition) {
  9831. return;
  9832. }
  9833. Tools._EndUserMark(counterName, condition);
  9834. if (console.time) {
  9835. console.timeEnd(counterName);
  9836. }
  9837. };
  9838. Object.defineProperty(Tools, "Now", {
  9839. get: function () {
  9840. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9841. return window.performance.now();
  9842. }
  9843. return Date.now();
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. /**
  9849. * This method will return the name of the class used to create the instance of the given object.
  9850. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9851. * @param object the object to get the class name from
  9852. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9853. */
  9854. Tools.GetClassName = function (object, isType) {
  9855. if (isType === void 0) { isType = false; }
  9856. var name = null;
  9857. if (!isType && object.getClassName) {
  9858. name = object.getClassName();
  9859. }
  9860. else {
  9861. if (object instanceof Object) {
  9862. var classObj = isType ? object : Object.getPrototypeOf(object);
  9863. name = classObj.constructor["__bjsclassName__"];
  9864. }
  9865. if (!name) {
  9866. name = typeof object;
  9867. }
  9868. }
  9869. return name;
  9870. };
  9871. Tools.First = function (array, predicate) {
  9872. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9873. var el = array_1[_i];
  9874. if (predicate(el)) {
  9875. return el;
  9876. }
  9877. }
  9878. return null;
  9879. };
  9880. /**
  9881. * This method will return the name of the full name of the class, including its owning module (if any).
  9882. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9883. * @param object the object to get the class name from
  9884. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9885. */
  9886. Tools.getFullClassName = function (object, isType) {
  9887. if (isType === void 0) { isType = false; }
  9888. var className = null;
  9889. var moduleName = null;
  9890. if (!isType && object.getClassName) {
  9891. className = object.getClassName();
  9892. }
  9893. else {
  9894. if (object instanceof Object) {
  9895. var classObj = isType ? object : Object.getPrototypeOf(object);
  9896. className = classObj.constructor["__bjsclassName__"];
  9897. moduleName = classObj.constructor["__bjsmoduleName__"];
  9898. }
  9899. if (!className) {
  9900. className = typeof object;
  9901. }
  9902. }
  9903. if (!className) {
  9904. return null;
  9905. }
  9906. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9907. };
  9908. /**
  9909. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9910. * @param array
  9911. */
  9912. Tools.arrayOrStringFeeder = function (array) {
  9913. return function (index) {
  9914. if (index >= array.length) {
  9915. return null;
  9916. }
  9917. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9918. if (val && val.getHashCode) {
  9919. val = val.getHashCode();
  9920. }
  9921. if (typeof val === "string") {
  9922. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9923. }
  9924. return val;
  9925. };
  9926. };
  9927. /**
  9928. * Compute the hashCode of a stream of number
  9929. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9930. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9931. * @return the hash code computed
  9932. */
  9933. Tools.hashCodeFromStream = function (feeder) {
  9934. // Based from here: http://stackoverflow.com/a/7616484/802124
  9935. var hash = 0;
  9936. var index = 0;
  9937. var chr = feeder(index++);
  9938. while (chr != null) {
  9939. hash = ((hash << 5) - hash) + chr;
  9940. hash |= 0; // Convert to 32bit integer
  9941. chr = feeder(index++);
  9942. }
  9943. return hash;
  9944. };
  9945. /**
  9946. * Returns a promise that resolves after the given amount of time.
  9947. * @param delay Number of milliseconds to delay
  9948. * @returns Promise that resolves after the given amount of time
  9949. */
  9950. Tools.DelayAsync = function (delay) {
  9951. return new Promise(function (resolve) {
  9952. setTimeout(function () {
  9953. resolve();
  9954. }, delay);
  9955. });
  9956. };
  9957. Tools.BaseUrl = "";
  9958. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9959. /**
  9960. * Default behaviour for cors in the application.
  9961. * It can be a string if the expected behavior is identical in the entire app.
  9962. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9963. */
  9964. Tools.CorsBehavior = "anonymous";
  9965. Tools.UseFallbackTexture = true;
  9966. /**
  9967. * Use this object to register external classes like custom textures or material
  9968. * to allow the laoders to instantiate them
  9969. */
  9970. Tools.RegisteredExternalClasses = {};
  9971. // Used in case of a texture loading problem
  9972. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9973. Tools._tmpFloatArray = new Float32Array(1);
  9974. Tools.PreprocessUrl = function (url) {
  9975. return url;
  9976. };
  9977. // Logs
  9978. Tools._NoneLogLevel = 0;
  9979. Tools._MessageLogLevel = 1;
  9980. Tools._WarningLogLevel = 2;
  9981. Tools._ErrorLogLevel = 4;
  9982. Tools._LogCache = "";
  9983. Tools.errorsCount = 0;
  9984. Tools.Log = Tools._LogEnabled;
  9985. Tools.Warn = Tools._WarnEnabled;
  9986. Tools.Error = Tools._ErrorEnabled;
  9987. // Performances
  9988. Tools._PerformanceNoneLogLevel = 0;
  9989. Tools._PerformanceUserMarkLogLevel = 1;
  9990. Tools._PerformanceConsoleLogLevel = 2;
  9991. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9992. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9993. return Tools;
  9994. }());
  9995. BABYLON.Tools = Tools;
  9996. /**
  9997. * This class is used to track a performance counter which is number based.
  9998. * The user has access to many properties which give statistics of different nature
  9999. *
  10000. * The implementer can track two kinds of Performance Counter: time and count
  10001. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  10002. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  10003. */
  10004. var PerfCounter = /** @class */ (function () {
  10005. function PerfCounter() {
  10006. this._startMonitoringTime = 0;
  10007. this._min = 0;
  10008. this._max = 0;
  10009. this._average = 0;
  10010. this._lastSecAverage = 0;
  10011. this._current = 0;
  10012. this._totalValueCount = 0;
  10013. this._totalAccumulated = 0;
  10014. this._lastSecAccumulated = 0;
  10015. this._lastSecTime = 0;
  10016. this._lastSecValueCount = 0;
  10017. }
  10018. Object.defineProperty(PerfCounter.prototype, "min", {
  10019. /**
  10020. * Returns the smallest value ever
  10021. */
  10022. get: function () {
  10023. return this._min;
  10024. },
  10025. enumerable: true,
  10026. configurable: true
  10027. });
  10028. Object.defineProperty(PerfCounter.prototype, "max", {
  10029. /**
  10030. * Returns the biggest value ever
  10031. */
  10032. get: function () {
  10033. return this._max;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(PerfCounter.prototype, "average", {
  10039. /**
  10040. * Returns the average value since the performance counter is running
  10041. */
  10042. get: function () {
  10043. return this._average;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10049. /**
  10050. * Returns the average value of the last second the counter was monitored
  10051. */
  10052. get: function () {
  10053. return this._lastSecAverage;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(PerfCounter.prototype, "current", {
  10059. /**
  10060. * Returns the current value
  10061. */
  10062. get: function () {
  10063. return this._current;
  10064. },
  10065. enumerable: true,
  10066. configurable: true
  10067. });
  10068. Object.defineProperty(PerfCounter.prototype, "total", {
  10069. get: function () {
  10070. return this._totalAccumulated;
  10071. },
  10072. enumerable: true,
  10073. configurable: true
  10074. });
  10075. Object.defineProperty(PerfCounter.prototype, "count", {
  10076. get: function () {
  10077. return this._totalValueCount;
  10078. },
  10079. enumerable: true,
  10080. configurable: true
  10081. });
  10082. /**
  10083. * Call this method to start monitoring a new frame.
  10084. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  10085. */
  10086. PerfCounter.prototype.fetchNewFrame = function () {
  10087. this._totalValueCount++;
  10088. this._current = 0;
  10089. this._lastSecValueCount++;
  10090. };
  10091. /**
  10092. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10093. * @param newCount the count value to add to the monitored count
  10094. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  10095. */
  10096. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10097. if (!PerfCounter.Enabled) {
  10098. return;
  10099. }
  10100. this._current += newCount;
  10101. if (fetchResult) {
  10102. this._fetchResult();
  10103. }
  10104. };
  10105. /**
  10106. * Start monitoring this performance counter
  10107. */
  10108. PerfCounter.prototype.beginMonitoring = function () {
  10109. if (!PerfCounter.Enabled) {
  10110. return;
  10111. }
  10112. this._startMonitoringTime = Tools.Now;
  10113. };
  10114. /**
  10115. * Compute the time lapsed since the previous beginMonitoring() call.
  10116. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  10117. */
  10118. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10119. if (newFrame === void 0) { newFrame = true; }
  10120. if (!PerfCounter.Enabled) {
  10121. return;
  10122. }
  10123. if (newFrame) {
  10124. this.fetchNewFrame();
  10125. }
  10126. var currentTime = Tools.Now;
  10127. this._current = currentTime - this._startMonitoringTime;
  10128. if (newFrame) {
  10129. this._fetchResult();
  10130. }
  10131. };
  10132. PerfCounter.prototype._fetchResult = function () {
  10133. this._totalAccumulated += this._current;
  10134. this._lastSecAccumulated += this._current;
  10135. // Min/Max update
  10136. this._min = Math.min(this._min, this._current);
  10137. this._max = Math.max(this._max, this._current);
  10138. this._average = this._totalAccumulated / this._totalValueCount;
  10139. // Reset last sec?
  10140. var now = Tools.Now;
  10141. if ((now - this._lastSecTime) > 1000) {
  10142. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10143. this._lastSecTime = now;
  10144. this._lastSecAccumulated = 0;
  10145. this._lastSecValueCount = 0;
  10146. }
  10147. };
  10148. PerfCounter.Enabled = true;
  10149. return PerfCounter;
  10150. }());
  10151. BABYLON.PerfCounter = PerfCounter;
  10152. /**
  10153. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10154. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10155. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10156. * @param name The name of the class, case should be preserved
  10157. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10158. */
  10159. function className(name, module) {
  10160. return function (target) {
  10161. target["__bjsclassName__"] = name;
  10162. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10163. };
  10164. }
  10165. BABYLON.className = className;
  10166. /**
  10167. * An implementation of a loop for asynchronous functions.
  10168. */
  10169. var AsyncLoop = /** @class */ (function () {
  10170. /**
  10171. * Constroctor.
  10172. * @param iterations the number of iterations.
  10173. * @param _fn the function to run each iteration
  10174. * @param _successCallback the callback that will be called upon succesful execution
  10175. * @param offset starting offset.
  10176. */
  10177. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10178. if (offset === void 0) { offset = 0; }
  10179. this.iterations = iterations;
  10180. this._fn = _fn;
  10181. this._successCallback = _successCallback;
  10182. this.index = offset - 1;
  10183. this._done = false;
  10184. }
  10185. /**
  10186. * Execute the next iteration. Must be called after the last iteration was finished.
  10187. */
  10188. AsyncLoop.prototype.executeNext = function () {
  10189. if (!this._done) {
  10190. if (this.index + 1 < this.iterations) {
  10191. ++this.index;
  10192. this._fn(this);
  10193. }
  10194. else {
  10195. this.breakLoop();
  10196. }
  10197. }
  10198. };
  10199. /**
  10200. * Break the loop and run the success callback.
  10201. */
  10202. AsyncLoop.prototype.breakLoop = function () {
  10203. this._done = true;
  10204. this._successCallback();
  10205. };
  10206. /**
  10207. * Helper function
  10208. */
  10209. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10210. if (offset === void 0) { offset = 0; }
  10211. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10212. loop.executeNext();
  10213. return loop;
  10214. };
  10215. /**
  10216. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10217. * @param iterations total number of iterations
  10218. * @param syncedIterations number of synchronous iterations in each async iteration.
  10219. * @param fn the function to call each iteration.
  10220. * @param callback a success call back that will be called when iterating stops.
  10221. * @param breakFunction a break condition (optional)
  10222. * @param timeout timeout settings for the setTimeout function. default - 0.
  10223. * @constructor
  10224. */
  10225. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10226. if (timeout === void 0) { timeout = 0; }
  10227. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10228. if (breakFunction && breakFunction())
  10229. loop.breakLoop();
  10230. else {
  10231. setTimeout(function () {
  10232. for (var i = 0; i < syncedIterations; ++i) {
  10233. var iteration = (loop.index * syncedIterations) + i;
  10234. if (iteration >= iterations)
  10235. break;
  10236. fn(iteration);
  10237. if (breakFunction && breakFunction()) {
  10238. loop.breakLoop();
  10239. break;
  10240. }
  10241. }
  10242. loop.executeNext();
  10243. }, timeout);
  10244. }
  10245. }, callback);
  10246. };
  10247. return AsyncLoop;
  10248. }());
  10249. BABYLON.AsyncLoop = AsyncLoop;
  10250. })(BABYLON || (BABYLON = {}));
  10251. //# sourceMappingURL=babylon.tools.js.map
  10252. var BABYLON;
  10253. (function (BABYLON) {
  10254. var PromiseStates;
  10255. (function (PromiseStates) {
  10256. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10257. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10258. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10259. })(PromiseStates || (PromiseStates = {}));
  10260. var FulFillmentAgregator = /** @class */ (function () {
  10261. function FulFillmentAgregator() {
  10262. this.count = 0;
  10263. this.target = 0;
  10264. this.results = [];
  10265. }
  10266. return FulFillmentAgregator;
  10267. }());
  10268. var InternalPromise = /** @class */ (function () {
  10269. function InternalPromise(resolver) {
  10270. var _this = this;
  10271. this._state = PromiseStates.Pending;
  10272. this._children = new Array();
  10273. this._rejectWasConsumed = false;
  10274. if (!resolver) {
  10275. return;
  10276. }
  10277. try {
  10278. resolver(function (value) {
  10279. _this._resolve(value);
  10280. }, function (reason) {
  10281. _this._reject(reason);
  10282. });
  10283. }
  10284. catch (e) {
  10285. this._reject(e);
  10286. }
  10287. }
  10288. Object.defineProperty(InternalPromise.prototype, "_result", {
  10289. get: function () {
  10290. return this._resultValue;
  10291. },
  10292. set: function (value) {
  10293. this._resultValue = value;
  10294. if (this._parent && this._parent._result === undefined) {
  10295. this._parent._result = value;
  10296. }
  10297. },
  10298. enumerable: true,
  10299. configurable: true
  10300. });
  10301. InternalPromise.prototype.catch = function (onRejected) {
  10302. return this.then(undefined, onRejected);
  10303. };
  10304. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10305. var _this = this;
  10306. var newPromise = new InternalPromise();
  10307. newPromise._onFulfilled = onFulfilled;
  10308. newPromise._onRejected = onRejected;
  10309. // Composition
  10310. this._children.push(newPromise);
  10311. newPromise._parent = this;
  10312. if (this._state !== PromiseStates.Pending) {
  10313. BABYLON.Tools.SetImmediate(function () {
  10314. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10315. var returnedValue = newPromise._resolve(_this._result);
  10316. if (returnedValue !== undefined && returnedValue !== null) {
  10317. if (returnedValue._state !== undefined) {
  10318. var returnedPromise = returnedValue;
  10319. newPromise._children.push(returnedPromise);
  10320. returnedPromise._parent = newPromise;
  10321. newPromise = returnedPromise;
  10322. }
  10323. else {
  10324. newPromise._result = returnedValue;
  10325. }
  10326. }
  10327. }
  10328. else {
  10329. newPromise._reject(_this._reason);
  10330. }
  10331. });
  10332. }
  10333. return newPromise;
  10334. };
  10335. InternalPromise.prototype._moveChildren = function (children) {
  10336. var _this = this;
  10337. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10338. this._children.forEach(function (child) {
  10339. child._parent = _this;
  10340. });
  10341. if (this._state === PromiseStates.Fulfilled) {
  10342. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10343. var child = _b[_i];
  10344. child._resolve(this._result);
  10345. }
  10346. }
  10347. else if (this._state === PromiseStates.Rejected) {
  10348. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10349. var child = _d[_c];
  10350. child._reject(this._reason);
  10351. }
  10352. }
  10353. var _a;
  10354. };
  10355. InternalPromise.prototype._resolve = function (value) {
  10356. try {
  10357. this._state = PromiseStates.Fulfilled;
  10358. var returnedValue = null;
  10359. if (this._onFulfilled) {
  10360. returnedValue = this._onFulfilled(value);
  10361. }
  10362. if (returnedValue !== undefined && returnedValue !== null) {
  10363. if (returnedValue._state !== undefined) {
  10364. // Transmit children
  10365. var returnedPromise = returnedValue;
  10366. returnedPromise._parent = this;
  10367. returnedPromise._moveChildren(this._children);
  10368. value = returnedPromise._result;
  10369. }
  10370. else {
  10371. value = returnedValue;
  10372. }
  10373. }
  10374. this._result = value;
  10375. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10376. var child = _a[_i];
  10377. child._resolve(value);
  10378. }
  10379. this._children.length = 0;
  10380. delete this._onFulfilled;
  10381. delete this._onRejected;
  10382. }
  10383. catch (e) {
  10384. this._reject(e, true);
  10385. }
  10386. };
  10387. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10388. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10389. this._state = PromiseStates.Rejected;
  10390. this._reason = reason;
  10391. if (this._onRejected && !onLocalThrow) {
  10392. try {
  10393. this._onRejected(reason);
  10394. this._rejectWasConsumed = true;
  10395. }
  10396. catch (e) {
  10397. reason = e;
  10398. }
  10399. }
  10400. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10401. var child = _a[_i];
  10402. if (this._rejectWasConsumed) {
  10403. child._resolve(null);
  10404. }
  10405. else {
  10406. child._reject(reason);
  10407. }
  10408. }
  10409. this._children.length = 0;
  10410. delete this._onFulfilled;
  10411. delete this._onRejected;
  10412. };
  10413. InternalPromise.resolve = function (value) {
  10414. var newPromise = new InternalPromise();
  10415. newPromise._resolve(value);
  10416. return newPromise;
  10417. };
  10418. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10419. promise.then(function (value) {
  10420. agregator.results[index] = value;
  10421. agregator.count++;
  10422. if (agregator.count === agregator.target) {
  10423. agregator.rootPromise._resolve(agregator.results);
  10424. }
  10425. return null;
  10426. }, function (reason) {
  10427. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10428. agregator.rootPromise._reject(reason);
  10429. }
  10430. });
  10431. };
  10432. InternalPromise.all = function (promises) {
  10433. var newPromise = new InternalPromise();
  10434. var agregator = new FulFillmentAgregator();
  10435. agregator.target = promises.length;
  10436. agregator.rootPromise = newPromise;
  10437. if (promises.length) {
  10438. for (var index = 0; index < promises.length; index++) {
  10439. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10440. }
  10441. }
  10442. else {
  10443. newPromise._resolve([]);
  10444. }
  10445. return newPromise;
  10446. };
  10447. InternalPromise.race = function (promises) {
  10448. var newPromise = new InternalPromise();
  10449. if (promises.length) {
  10450. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10451. var promise = promises_1[_i];
  10452. promise.then(function (value) {
  10453. if (newPromise) {
  10454. newPromise._resolve(value);
  10455. newPromise = null;
  10456. }
  10457. return null;
  10458. }, function (reason) {
  10459. if (newPromise) {
  10460. newPromise._reject(reason);
  10461. newPromise = null;
  10462. }
  10463. });
  10464. }
  10465. }
  10466. return newPromise;
  10467. };
  10468. return InternalPromise;
  10469. }());
  10470. /**
  10471. * Helper class that provides a small promise polyfill
  10472. */
  10473. var PromisePolyfill = /** @class */ (function () {
  10474. function PromisePolyfill() {
  10475. }
  10476. /**
  10477. * Static function used to check if the polyfill is required
  10478. * If this is the case then the function will inject the polyfill to window.Promise
  10479. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10480. */
  10481. PromisePolyfill.Apply = function (force) {
  10482. if (force === void 0) { force = false; }
  10483. if (force || typeof Promise === 'undefined') {
  10484. var root = window;
  10485. root.Promise = InternalPromise;
  10486. }
  10487. };
  10488. return PromisePolyfill;
  10489. }());
  10490. BABYLON.PromisePolyfill = PromisePolyfill;
  10491. })(BABYLON || (BABYLON = {}));
  10492. //# sourceMappingURL=babylon.promise.js.map
  10493. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10494. var BABYLON;
  10495. (function (BABYLON) {
  10496. /**
  10497. * Helper class to push actions to a pool of workers.
  10498. */
  10499. var WorkerPool = /** @class */ (function () {
  10500. /**
  10501. * Constructor
  10502. * @param workers Array of workers to use for actions
  10503. */
  10504. function WorkerPool(workers) {
  10505. this._pendingActions = new Array();
  10506. this._workerInfos = workers.map(function (worker) { return ({
  10507. worker: worker,
  10508. active: false
  10509. }); });
  10510. }
  10511. /**
  10512. * Terminates all workers and clears any pending actions.
  10513. */
  10514. WorkerPool.prototype.dispose = function () {
  10515. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10516. var workerInfo = _a[_i];
  10517. workerInfo.worker.terminate();
  10518. }
  10519. delete this._workerInfos;
  10520. delete this._pendingActions;
  10521. };
  10522. /**
  10523. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10524. * pended until a worker has completed its action.
  10525. * @param action The action to perform. Call onComplete when the action is complete.
  10526. */
  10527. WorkerPool.prototype.push = function (action) {
  10528. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10529. var workerInfo = _a[_i];
  10530. if (!workerInfo.active) {
  10531. this._execute(workerInfo, action);
  10532. return;
  10533. }
  10534. }
  10535. this._pendingActions.push(action);
  10536. };
  10537. WorkerPool.prototype._execute = function (workerInfo, action) {
  10538. var _this = this;
  10539. workerInfo.active = true;
  10540. action(workerInfo.worker, function () {
  10541. workerInfo.active = false;
  10542. var nextAction = _this._pendingActions.shift();
  10543. if (nextAction) {
  10544. _this._execute(workerInfo, nextAction);
  10545. }
  10546. });
  10547. };
  10548. return WorkerPool;
  10549. }());
  10550. BABYLON.WorkerPool = WorkerPool;
  10551. })(BABYLON || (BABYLON = {}));
  10552. //# sourceMappingURL=babylon.workerPool.js.map
  10553. var BABYLON;
  10554. (function (BABYLON) {
  10555. /**
  10556. * @hidden
  10557. **/
  10558. var _AlphaState = /** @class */ (function () {
  10559. /**
  10560. * Initializes the state.
  10561. */
  10562. function _AlphaState() {
  10563. this._isAlphaBlendDirty = false;
  10564. this._isBlendFunctionParametersDirty = false;
  10565. this._isBlendEquationParametersDirty = false;
  10566. this._isBlendConstantsDirty = false;
  10567. this._alphaBlend = false;
  10568. this._blendFunctionParameters = new Array(4);
  10569. this._blendEquationParameters = new Array(2);
  10570. this._blendConstants = new Array(4);
  10571. this.reset();
  10572. }
  10573. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10574. get: function () {
  10575. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10576. },
  10577. enumerable: true,
  10578. configurable: true
  10579. });
  10580. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10581. get: function () {
  10582. return this._alphaBlend;
  10583. },
  10584. set: function (value) {
  10585. if (this._alphaBlend === value) {
  10586. return;
  10587. }
  10588. this._alphaBlend = value;
  10589. this._isAlphaBlendDirty = true;
  10590. },
  10591. enumerable: true,
  10592. configurable: true
  10593. });
  10594. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10595. if (this._blendConstants[0] === r &&
  10596. this._blendConstants[1] === g &&
  10597. this._blendConstants[2] === b &&
  10598. this._blendConstants[3] === a) {
  10599. return;
  10600. }
  10601. this._blendConstants[0] = r;
  10602. this._blendConstants[1] = g;
  10603. this._blendConstants[2] = b;
  10604. this._blendConstants[3] = a;
  10605. this._isBlendConstantsDirty = true;
  10606. };
  10607. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10608. if (this._blendFunctionParameters[0] === value0 &&
  10609. this._blendFunctionParameters[1] === value1 &&
  10610. this._blendFunctionParameters[2] === value2 &&
  10611. this._blendFunctionParameters[3] === value3) {
  10612. return;
  10613. }
  10614. this._blendFunctionParameters[0] = value0;
  10615. this._blendFunctionParameters[1] = value1;
  10616. this._blendFunctionParameters[2] = value2;
  10617. this._blendFunctionParameters[3] = value3;
  10618. this._isBlendFunctionParametersDirty = true;
  10619. };
  10620. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10621. if (this._blendEquationParameters[0] === rgb &&
  10622. this._blendEquationParameters[1] === alpha) {
  10623. return;
  10624. }
  10625. this._blendEquationParameters[0] = rgb;
  10626. this._blendEquationParameters[1] = alpha;
  10627. this._isBlendEquationParametersDirty = true;
  10628. };
  10629. _AlphaState.prototype.reset = function () {
  10630. this._alphaBlend = false;
  10631. this._blendFunctionParameters[0] = null;
  10632. this._blendFunctionParameters[1] = null;
  10633. this._blendFunctionParameters[2] = null;
  10634. this._blendFunctionParameters[3] = null;
  10635. this._blendEquationParameters[0] = null;
  10636. this._blendEquationParameters[1] = null;
  10637. this._blendConstants[0] = null;
  10638. this._blendConstants[1] = null;
  10639. this._blendConstants[2] = null;
  10640. this._blendConstants[3] = null;
  10641. this._isAlphaBlendDirty = true;
  10642. this._isBlendFunctionParametersDirty = false;
  10643. this._isBlendEquationParametersDirty = false;
  10644. this._isBlendConstantsDirty = false;
  10645. };
  10646. _AlphaState.prototype.apply = function (gl) {
  10647. if (!this.isDirty) {
  10648. return;
  10649. }
  10650. // Alpha blend
  10651. if (this._isAlphaBlendDirty) {
  10652. if (this._alphaBlend) {
  10653. gl.enable(gl.BLEND);
  10654. }
  10655. else {
  10656. gl.disable(gl.BLEND);
  10657. }
  10658. this._isAlphaBlendDirty = false;
  10659. }
  10660. // Alpha function
  10661. if (this._isBlendFunctionParametersDirty) {
  10662. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10663. this._isBlendFunctionParametersDirty = false;
  10664. }
  10665. // Alpha equation
  10666. if (this._isBlendEquationParametersDirty) {
  10667. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10668. this._isBlendEquationParametersDirty = false;
  10669. }
  10670. // Constants
  10671. if (this._isBlendConstantsDirty) {
  10672. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10673. this._isBlendConstantsDirty = false;
  10674. }
  10675. };
  10676. return _AlphaState;
  10677. }());
  10678. BABYLON._AlphaState = _AlphaState;
  10679. })(BABYLON || (BABYLON = {}));
  10680. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10681. var BABYLON;
  10682. (function (BABYLON) {
  10683. /**
  10684. * @hidden
  10685. **/
  10686. var _DepthCullingState = /** @class */ (function () {
  10687. /**
  10688. * Initializes the state.
  10689. */
  10690. function _DepthCullingState() {
  10691. this._isDepthTestDirty = false;
  10692. this._isDepthMaskDirty = false;
  10693. this._isDepthFuncDirty = false;
  10694. this._isCullFaceDirty = false;
  10695. this._isCullDirty = false;
  10696. this._isZOffsetDirty = false;
  10697. this._isFrontFaceDirty = false;
  10698. this.reset();
  10699. }
  10700. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10701. get: function () {
  10702. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10703. },
  10704. enumerable: true,
  10705. configurable: true
  10706. });
  10707. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10708. get: function () {
  10709. return this._zOffset;
  10710. },
  10711. set: function (value) {
  10712. if (this._zOffset === value) {
  10713. return;
  10714. }
  10715. this._zOffset = value;
  10716. this._isZOffsetDirty = true;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10722. get: function () {
  10723. return this._cullFace;
  10724. },
  10725. set: function (value) {
  10726. if (this._cullFace === value) {
  10727. return;
  10728. }
  10729. this._cullFace = value;
  10730. this._isCullFaceDirty = true;
  10731. },
  10732. enumerable: true,
  10733. configurable: true
  10734. });
  10735. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10736. get: function () {
  10737. return this._cull;
  10738. },
  10739. set: function (value) {
  10740. if (this._cull === value) {
  10741. return;
  10742. }
  10743. this._cull = value;
  10744. this._isCullDirty = true;
  10745. },
  10746. enumerable: true,
  10747. configurable: true
  10748. });
  10749. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10750. get: function () {
  10751. return this._depthFunc;
  10752. },
  10753. set: function (value) {
  10754. if (this._depthFunc === value) {
  10755. return;
  10756. }
  10757. this._depthFunc = value;
  10758. this._isDepthFuncDirty = true;
  10759. },
  10760. enumerable: true,
  10761. configurable: true
  10762. });
  10763. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10764. get: function () {
  10765. return this._depthMask;
  10766. },
  10767. set: function (value) {
  10768. if (this._depthMask === value) {
  10769. return;
  10770. }
  10771. this._depthMask = value;
  10772. this._isDepthMaskDirty = true;
  10773. },
  10774. enumerable: true,
  10775. configurable: true
  10776. });
  10777. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10778. get: function () {
  10779. return this._depthTest;
  10780. },
  10781. set: function (value) {
  10782. if (this._depthTest === value) {
  10783. return;
  10784. }
  10785. this._depthTest = value;
  10786. this._isDepthTestDirty = true;
  10787. },
  10788. enumerable: true,
  10789. configurable: true
  10790. });
  10791. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10792. get: function () {
  10793. return this._frontFace;
  10794. },
  10795. set: function (value) {
  10796. if (this._frontFace === value) {
  10797. return;
  10798. }
  10799. this._frontFace = value;
  10800. this._isFrontFaceDirty = true;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. _DepthCullingState.prototype.reset = function () {
  10806. this._depthMask = true;
  10807. this._depthTest = true;
  10808. this._depthFunc = null;
  10809. this._cullFace = null;
  10810. this._cull = null;
  10811. this._zOffset = 0;
  10812. this._frontFace = null;
  10813. this._isDepthTestDirty = true;
  10814. this._isDepthMaskDirty = true;
  10815. this._isDepthFuncDirty = false;
  10816. this._isCullFaceDirty = false;
  10817. this._isCullDirty = false;
  10818. this._isZOffsetDirty = false;
  10819. this._isFrontFaceDirty = false;
  10820. };
  10821. _DepthCullingState.prototype.apply = function (gl) {
  10822. if (!this.isDirty) {
  10823. return;
  10824. }
  10825. // Cull
  10826. if (this._isCullDirty) {
  10827. if (this.cull) {
  10828. gl.enable(gl.CULL_FACE);
  10829. }
  10830. else {
  10831. gl.disable(gl.CULL_FACE);
  10832. }
  10833. this._isCullDirty = false;
  10834. }
  10835. // Cull face
  10836. if (this._isCullFaceDirty) {
  10837. gl.cullFace(this.cullFace);
  10838. this._isCullFaceDirty = false;
  10839. }
  10840. // Depth mask
  10841. if (this._isDepthMaskDirty) {
  10842. gl.depthMask(this.depthMask);
  10843. this._isDepthMaskDirty = false;
  10844. }
  10845. // Depth test
  10846. if (this._isDepthTestDirty) {
  10847. if (this.depthTest) {
  10848. gl.enable(gl.DEPTH_TEST);
  10849. }
  10850. else {
  10851. gl.disable(gl.DEPTH_TEST);
  10852. }
  10853. this._isDepthTestDirty = false;
  10854. }
  10855. // Depth func
  10856. if (this._isDepthFuncDirty) {
  10857. gl.depthFunc(this.depthFunc);
  10858. this._isDepthFuncDirty = false;
  10859. }
  10860. // zOffset
  10861. if (this._isZOffsetDirty) {
  10862. if (this.zOffset) {
  10863. gl.enable(gl.POLYGON_OFFSET_FILL);
  10864. gl.polygonOffset(this.zOffset, 0);
  10865. }
  10866. else {
  10867. gl.disable(gl.POLYGON_OFFSET_FILL);
  10868. }
  10869. this._isZOffsetDirty = false;
  10870. }
  10871. // Front face
  10872. if (this._isFrontFaceDirty) {
  10873. gl.frontFace(this.frontFace);
  10874. this._isFrontFaceDirty = false;
  10875. }
  10876. };
  10877. return _DepthCullingState;
  10878. }());
  10879. BABYLON._DepthCullingState = _DepthCullingState;
  10880. })(BABYLON || (BABYLON = {}));
  10881. //# sourceMappingURL=babylon.depthCullingState.js.map
  10882. var BABYLON;
  10883. (function (BABYLON) {
  10884. /**
  10885. * @hidden
  10886. **/
  10887. var _StencilState = /** @class */ (function () {
  10888. function _StencilState() {
  10889. this._isStencilTestDirty = false;
  10890. this._isStencilMaskDirty = false;
  10891. this._isStencilFuncDirty = false;
  10892. this._isStencilOpDirty = false;
  10893. this.reset();
  10894. }
  10895. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10896. get: function () {
  10897. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10903. get: function () {
  10904. return this._stencilFunc;
  10905. },
  10906. set: function (value) {
  10907. if (this._stencilFunc === value) {
  10908. return;
  10909. }
  10910. this._stencilFunc = value;
  10911. this._isStencilFuncDirty = true;
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10917. get: function () {
  10918. return this._stencilFuncRef;
  10919. },
  10920. set: function (value) {
  10921. if (this._stencilFuncRef === value) {
  10922. return;
  10923. }
  10924. this._stencilFuncRef = value;
  10925. this._isStencilFuncDirty = true;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10931. get: function () {
  10932. return this._stencilFuncMask;
  10933. },
  10934. set: function (value) {
  10935. if (this._stencilFuncMask === value) {
  10936. return;
  10937. }
  10938. this._stencilFuncMask = value;
  10939. this._isStencilFuncDirty = true;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10945. get: function () {
  10946. return this._stencilOpStencilFail;
  10947. },
  10948. set: function (value) {
  10949. if (this._stencilOpStencilFail === value) {
  10950. return;
  10951. }
  10952. this._stencilOpStencilFail = value;
  10953. this._isStencilOpDirty = true;
  10954. },
  10955. enumerable: true,
  10956. configurable: true
  10957. });
  10958. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10959. get: function () {
  10960. return this._stencilOpDepthFail;
  10961. },
  10962. set: function (value) {
  10963. if (this._stencilOpDepthFail === value) {
  10964. return;
  10965. }
  10966. this._stencilOpDepthFail = value;
  10967. this._isStencilOpDirty = true;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10973. get: function () {
  10974. return this._stencilOpStencilDepthPass;
  10975. },
  10976. set: function (value) {
  10977. if (this._stencilOpStencilDepthPass === value) {
  10978. return;
  10979. }
  10980. this._stencilOpStencilDepthPass = value;
  10981. this._isStencilOpDirty = true;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10987. get: function () {
  10988. return this._stencilMask;
  10989. },
  10990. set: function (value) {
  10991. if (this._stencilMask === value) {
  10992. return;
  10993. }
  10994. this._stencilMask = value;
  10995. this._isStencilMaskDirty = true;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11001. get: function () {
  11002. return this._stencilTest;
  11003. },
  11004. set: function (value) {
  11005. if (this._stencilTest === value) {
  11006. return;
  11007. }
  11008. this._stencilTest = value;
  11009. this._isStencilTestDirty = true;
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. _StencilState.prototype.reset = function () {
  11015. this._stencilTest = false;
  11016. this._stencilMask = 0xFF;
  11017. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11018. this._stencilFuncRef = 1;
  11019. this._stencilFuncMask = 0xFF;
  11020. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11021. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11022. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11023. this._isStencilTestDirty = true;
  11024. this._isStencilMaskDirty = true;
  11025. this._isStencilFuncDirty = true;
  11026. this._isStencilOpDirty = true;
  11027. };
  11028. _StencilState.prototype.apply = function (gl) {
  11029. if (!this.isDirty) {
  11030. return;
  11031. }
  11032. // Stencil test
  11033. if (this._isStencilTestDirty) {
  11034. if (this.stencilTest) {
  11035. gl.enable(gl.STENCIL_TEST);
  11036. }
  11037. else {
  11038. gl.disable(gl.STENCIL_TEST);
  11039. }
  11040. this._isStencilTestDirty = false;
  11041. }
  11042. // Stencil mask
  11043. if (this._isStencilMaskDirty) {
  11044. gl.stencilMask(this.stencilMask);
  11045. this._isStencilMaskDirty = false;
  11046. }
  11047. // Stencil func
  11048. if (this._isStencilFuncDirty) {
  11049. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11050. this._isStencilFuncDirty = false;
  11051. }
  11052. // Stencil op
  11053. if (this._isStencilOpDirty) {
  11054. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11055. this._isStencilOpDirty = false;
  11056. }
  11057. };
  11058. return _StencilState;
  11059. }());
  11060. BABYLON._StencilState = _StencilState;
  11061. })(BABYLON || (BABYLON = {}));
  11062. //# sourceMappingURL=babylon.stencilState.js.map
  11063. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11064. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11065. s = arguments[i];
  11066. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11067. t[p] = s[p];
  11068. }
  11069. return t;
  11070. };
  11071. var BABYLON;
  11072. (function (BABYLON) {
  11073. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11074. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11075. };
  11076. var compileRawShader = function (gl, source, type) {
  11077. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11078. gl.shaderSource(shader, source);
  11079. gl.compileShader(shader);
  11080. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11081. var log = gl.getShaderInfoLog(shader);
  11082. if (log) {
  11083. throw new Error(log);
  11084. }
  11085. }
  11086. if (!shader) {
  11087. throw new Error("Something went wrong while compile the shader.");
  11088. }
  11089. return shader;
  11090. };
  11091. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11092. var magFilter = gl.NEAREST;
  11093. var minFilter = gl.NEAREST;
  11094. switch (samplingMode) {
  11095. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11096. magFilter = gl.LINEAR;
  11097. if (generateMipMaps) {
  11098. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11099. }
  11100. else {
  11101. minFilter = gl.LINEAR;
  11102. }
  11103. break;
  11104. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11105. magFilter = gl.LINEAR;
  11106. if (generateMipMaps) {
  11107. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11108. }
  11109. else {
  11110. minFilter = gl.LINEAR;
  11111. }
  11112. break;
  11113. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11114. magFilter = gl.NEAREST;
  11115. if (generateMipMaps) {
  11116. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11117. }
  11118. else {
  11119. minFilter = gl.NEAREST;
  11120. }
  11121. break;
  11122. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11123. magFilter = gl.NEAREST;
  11124. if (generateMipMaps) {
  11125. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11126. }
  11127. else {
  11128. minFilter = gl.NEAREST;
  11129. }
  11130. break;
  11131. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11132. magFilter = gl.NEAREST;
  11133. if (generateMipMaps) {
  11134. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11135. }
  11136. else {
  11137. minFilter = gl.LINEAR;
  11138. }
  11139. break;
  11140. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11141. magFilter = gl.NEAREST;
  11142. if (generateMipMaps) {
  11143. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11144. }
  11145. else {
  11146. minFilter = gl.LINEAR;
  11147. }
  11148. break;
  11149. case BABYLON.Texture.NEAREST_LINEAR:
  11150. magFilter = gl.NEAREST;
  11151. minFilter = gl.LINEAR;
  11152. break;
  11153. case BABYLON.Texture.NEAREST_NEAREST:
  11154. magFilter = gl.NEAREST;
  11155. minFilter = gl.NEAREST;
  11156. break;
  11157. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11158. magFilter = gl.LINEAR;
  11159. if (generateMipMaps) {
  11160. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11161. }
  11162. else {
  11163. minFilter = gl.NEAREST;
  11164. }
  11165. break;
  11166. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11167. magFilter = gl.LINEAR;
  11168. if (generateMipMaps) {
  11169. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11170. }
  11171. else {
  11172. minFilter = gl.NEAREST;
  11173. }
  11174. break;
  11175. case BABYLON.Texture.LINEAR_LINEAR:
  11176. magFilter = gl.LINEAR;
  11177. minFilter = gl.LINEAR;
  11178. break;
  11179. case BABYLON.Texture.LINEAR_NEAREST:
  11180. magFilter = gl.LINEAR;
  11181. minFilter = gl.NEAREST;
  11182. break;
  11183. }
  11184. return {
  11185. min: minFilter,
  11186. mag: magFilter
  11187. };
  11188. };
  11189. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11190. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11191. var img;
  11192. var onload = function () {
  11193. loadedImages[index] = img;
  11194. loadedImages._internalCount++;
  11195. if (scene) {
  11196. scene._removePendingData(img);
  11197. }
  11198. if (loadedImages._internalCount === 6) {
  11199. onfinish(loadedImages);
  11200. }
  11201. };
  11202. var onerror = function (message, exception) {
  11203. if (scene) {
  11204. scene._removePendingData(img);
  11205. }
  11206. if (onErrorCallBack) {
  11207. onErrorCallBack(message, exception);
  11208. }
  11209. };
  11210. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11211. if (scene) {
  11212. scene._addPendingData(img);
  11213. }
  11214. };
  11215. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11216. if (onError === void 0) { onError = null; }
  11217. var loadedImages = [];
  11218. loadedImages._internalCount = 0;
  11219. for (var index = 0; index < 6; index++) {
  11220. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11221. }
  11222. };
  11223. var BufferPointer = /** @class */ (function () {
  11224. function BufferPointer() {
  11225. }
  11226. return BufferPointer;
  11227. }());
  11228. /**
  11229. * Interface for attribute information associated with buffer instanciation
  11230. */
  11231. var InstancingAttributeInfo = /** @class */ (function () {
  11232. function InstancingAttributeInfo() {
  11233. }
  11234. return InstancingAttributeInfo;
  11235. }());
  11236. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11237. /**
  11238. * Define options used to create a render target texture
  11239. */
  11240. var RenderTargetCreationOptions = /** @class */ (function () {
  11241. function RenderTargetCreationOptions() {
  11242. }
  11243. return RenderTargetCreationOptions;
  11244. }());
  11245. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11246. /**
  11247. * Define options used to create a depth texture
  11248. */
  11249. var DepthTextureCreationOptions = /** @class */ (function () {
  11250. function DepthTextureCreationOptions() {
  11251. }
  11252. return DepthTextureCreationOptions;
  11253. }());
  11254. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11255. /**
  11256. * Class used to describe the capabilities of the engine relatively to the current browser
  11257. */
  11258. var EngineCapabilities = /** @class */ (function () {
  11259. function EngineCapabilities() {
  11260. }
  11261. return EngineCapabilities;
  11262. }());
  11263. BABYLON.EngineCapabilities = EngineCapabilities;
  11264. /**
  11265. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11266. */
  11267. var Engine = /** @class */ (function () {
  11268. /**
  11269. * Creates a new engine
  11270. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11271. * @param antialias defines enable antialiasing (default: false)
  11272. * @param options defines further options to be sent to the getContext() function
  11273. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11274. */
  11275. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11276. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11277. var _this = this;
  11278. // Public members
  11279. /**
  11280. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11281. */
  11282. this.forcePOTTextures = false;
  11283. /**
  11284. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11285. */
  11286. this.isFullscreen = false;
  11287. /**
  11288. * Gets a boolean indicating if the pointer is currently locked
  11289. */
  11290. this.isPointerLock = false;
  11291. /**
  11292. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11293. */
  11294. this.cullBackFaces = true;
  11295. /**
  11296. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11297. */
  11298. this.renderEvenInBackground = true;
  11299. /**
  11300. * Gets or sets a boolean indicating that cache can be kept between frames
  11301. */
  11302. this.preventCacheWipeBetweenFrames = false;
  11303. /**
  11304. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11305. **/
  11306. this.enableOfflineSupport = false;
  11307. /**
  11308. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11309. **/
  11310. this.disableManifestCheck = false;
  11311. /**
  11312. * Gets the list of created scenes
  11313. */
  11314. this.scenes = new Array();
  11315. /**
  11316. * Gets the list of created postprocesses
  11317. */
  11318. this.postProcesses = new Array();
  11319. // Observables
  11320. /**
  11321. * Observable event triggered each time the rendering canvas is resized
  11322. */
  11323. this.onResizeObservable = new BABYLON.Observable();
  11324. /**
  11325. * Observable event triggered each time the canvas loses focus
  11326. */
  11327. this.onCanvasBlurObservable = new BABYLON.Observable();
  11328. /**
  11329. * Observable event triggered each time the canvas gains focus
  11330. */
  11331. this.onCanvasFocusObservable = new BABYLON.Observable();
  11332. /**
  11333. * Observable event triggered each time the canvas receives pointerout event
  11334. */
  11335. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11336. /**
  11337. * Observable event triggered before each texture is initialized
  11338. */
  11339. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11340. //WebVR
  11341. this._vrDisplay = undefined;
  11342. this._vrSupported = false;
  11343. this._vrExclusivePointerMode = false;
  11344. // Uniform buffers list
  11345. /**
  11346. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11347. */
  11348. this.disableUniformBuffers = false;
  11349. /** @hidden */
  11350. this._uniformBuffers = new Array();
  11351. // Observables
  11352. /**
  11353. * Observable raised when the engine begins a new frame
  11354. */
  11355. this.onBeginFrameObservable = new BABYLON.Observable();
  11356. /**
  11357. * Observable raised when the engine ends the current frame
  11358. */
  11359. this.onEndFrameObservable = new BABYLON.Observable();
  11360. /**
  11361. * Observable raised when the engine is about to compile a shader
  11362. */
  11363. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11364. /**
  11365. * Observable raised when the engine has jsut compiled a shader
  11366. */
  11367. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11368. this._windowIsBackground = false;
  11369. this._webGLVersion = 1.0;
  11370. /** @hidden */
  11371. this._badOS = false;
  11372. /** @hidden */
  11373. this._badDesktopOS = false;
  11374. /**
  11375. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11376. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11377. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11378. */
  11379. this.disableTextureBindingOptimization = false;
  11380. /**
  11381. * Observable signaled when VR display mode changes
  11382. */
  11383. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable signaled when VR request present is complete
  11386. */
  11387. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11388. /**
  11389. * Observable signaled when VR request present starts
  11390. */
  11391. this.onVRRequestPresentStart = new BABYLON.Observable();
  11392. this._colorWrite = true;
  11393. /** @hidden */
  11394. this._drawCalls = new BABYLON.PerfCounter();
  11395. /** @hidden */
  11396. this._textureCollisions = new BABYLON.PerfCounter();
  11397. this._renderingQueueLaunched = false;
  11398. this._activeRenderLoops = new Array();
  11399. // Deterministic lockstepMaxSteps
  11400. this._deterministicLockstep = false;
  11401. this._lockstepMaxSteps = 4;
  11402. // Lost context
  11403. /**
  11404. * Observable signaled when a context lost event is raised
  11405. */
  11406. this.onContextLostObservable = new BABYLON.Observable();
  11407. /**
  11408. * Observable signaled when a context restored event is raised
  11409. */
  11410. this.onContextRestoredObservable = new BABYLON.Observable();
  11411. this._contextWasLost = false;
  11412. this._doNotHandleContextLost = false;
  11413. // FPS
  11414. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11415. this._fps = 60;
  11416. this._deltaTime = 0;
  11417. /**
  11418. * Turn this value on if you want to pause FPS computation when in background
  11419. */
  11420. this.disablePerformanceMonitorInBackground = false;
  11421. // States
  11422. /** @hidden */
  11423. this._depthCullingState = new BABYLON._DepthCullingState();
  11424. /** @hidden */
  11425. this._stencilState = new BABYLON._StencilState();
  11426. /** @hidden */
  11427. this._alphaState = new BABYLON._AlphaState();
  11428. /** @hidden */
  11429. this._alphaMode = Engine.ALPHA_DISABLE;
  11430. // Cache
  11431. this._internalTexturesCache = new Array();
  11432. /** @hidden */
  11433. this._activeChannel = 0;
  11434. this._currentTextureChannel = -1;
  11435. /** @hidden */
  11436. this._boundTexturesCache = {};
  11437. this._compiledEffects = {};
  11438. this._vertexAttribArraysEnabled = [];
  11439. this._uintIndicesCurrentlySet = false;
  11440. this._currentBoundBuffer = new Array();
  11441. this._currentBufferPointers = new Array();
  11442. this._currentInstanceLocations = new Array();
  11443. this._currentInstanceBuffers = new Array();
  11444. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11445. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11446. this._vaoRecordInProgress = false;
  11447. this._mustWipeVertexAttributes = false;
  11448. this._nextFreeTextureSlots = new Array();
  11449. this._maxSimultaneousTextures = 0;
  11450. this._activeRequests = new Array();
  11451. // Hardware supported Compressed Textures
  11452. this._texturesSupported = new Array();
  11453. this._onVRFullScreenTriggered = function () {
  11454. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11455. //get the old size before we change
  11456. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11457. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11458. //get the width and height, change the render size
  11459. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11460. _this.setHardwareScalingLevel(1);
  11461. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11462. }
  11463. else {
  11464. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11465. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11466. }
  11467. };
  11468. this._boundUniforms = {};
  11469. // Register promises
  11470. BABYLON.PromisePolyfill.Apply();
  11471. var canvas = null;
  11472. Engine.Instances.push(this);
  11473. if (!canvasOrContext) {
  11474. return;
  11475. }
  11476. options = options || {};
  11477. if (canvasOrContext.getContext) {
  11478. canvas = canvasOrContext;
  11479. this._renderingCanvas = canvas;
  11480. if (antialias != null) {
  11481. options.antialias = antialias;
  11482. }
  11483. if (options.deterministicLockstep === undefined) {
  11484. options.deterministicLockstep = false;
  11485. }
  11486. if (options.lockstepMaxSteps === undefined) {
  11487. options.lockstepMaxSteps = 4;
  11488. }
  11489. if (options.preserveDrawingBuffer === undefined) {
  11490. options.preserveDrawingBuffer = false;
  11491. }
  11492. if (options.audioEngine === undefined) {
  11493. options.audioEngine = true;
  11494. }
  11495. if (options.stencil === undefined) {
  11496. options.stencil = true;
  11497. }
  11498. this._deterministicLockstep = options.deterministicLockstep;
  11499. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11500. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11501. // Exceptions
  11502. if (navigator && navigator.userAgent) {
  11503. var ua = navigator.userAgent;
  11504. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11505. var exception = _a[_i];
  11506. var key = exception.key;
  11507. var targets = exception.targets;
  11508. if (ua.indexOf(key) > -1) {
  11509. if (exception.capture && exception.captureConstraint) {
  11510. var capture = exception.capture;
  11511. var constraint = exception.captureConstraint;
  11512. var regex = new RegExp(capture);
  11513. var matches = regex.exec(ua);
  11514. if (matches && matches.length > 0) {
  11515. var capturedValue = parseInt(matches[matches.length - 1]);
  11516. if (capturedValue >= constraint) {
  11517. continue;
  11518. }
  11519. }
  11520. }
  11521. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11522. var target = targets_1[_b];
  11523. switch (target) {
  11524. case "uniformBuffer":
  11525. this.disableUniformBuffers = true;
  11526. break;
  11527. case "textureBindingOptimization":
  11528. this.disableTextureBindingOptimization = true;
  11529. break;
  11530. }
  11531. }
  11532. }
  11533. }
  11534. }
  11535. // GL
  11536. if (!options.disableWebGL2Support) {
  11537. try {
  11538. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11539. if (this._gl) {
  11540. this._webGLVersion = 2.0;
  11541. }
  11542. }
  11543. catch (e) {
  11544. // Do nothing
  11545. }
  11546. }
  11547. if (!this._gl) {
  11548. if (!canvas) {
  11549. throw new Error("The provided canvas is null or undefined.");
  11550. }
  11551. try {
  11552. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11553. }
  11554. catch (e) {
  11555. throw new Error("WebGL not supported");
  11556. }
  11557. }
  11558. if (!this._gl) {
  11559. throw new Error("WebGL not supported");
  11560. }
  11561. this._onCanvasFocus = function () {
  11562. _this.onCanvasFocusObservable.notifyObservers(_this);
  11563. };
  11564. this._onCanvasBlur = function () {
  11565. _this.onCanvasBlurObservable.notifyObservers(_this);
  11566. };
  11567. canvas.addEventListener("focus", this._onCanvasFocus);
  11568. canvas.addEventListener("blur", this._onCanvasBlur);
  11569. this._onBlur = function () {
  11570. if (_this.disablePerformanceMonitorInBackground) {
  11571. _this._performanceMonitor.disable();
  11572. }
  11573. _this._windowIsBackground = true;
  11574. };
  11575. this._onFocus = function () {
  11576. if (_this.disablePerformanceMonitorInBackground) {
  11577. _this._performanceMonitor.enable();
  11578. }
  11579. _this._windowIsBackground = false;
  11580. };
  11581. this._onCanvasPointerOut = function (ev) {
  11582. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11583. };
  11584. window.addEventListener("blur", this._onBlur);
  11585. window.addEventListener("focus", this._onFocus);
  11586. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11587. // Context lost
  11588. if (!this._doNotHandleContextLost) {
  11589. this._onContextLost = function (evt) {
  11590. evt.preventDefault();
  11591. _this._contextWasLost = true;
  11592. BABYLON.Tools.Warn("WebGL context lost.");
  11593. _this.onContextLostObservable.notifyObservers(_this);
  11594. };
  11595. this._onContextRestored = function (evt) {
  11596. // Adding a timeout to avoid race condition at browser level
  11597. setTimeout(function () {
  11598. // Rebuild gl context
  11599. _this._initGLContext();
  11600. // Rebuild effects
  11601. _this._rebuildEffects();
  11602. // Rebuild textures
  11603. _this._rebuildInternalTextures();
  11604. // Rebuild buffers
  11605. _this._rebuildBuffers();
  11606. // Cache
  11607. _this.wipeCaches(true);
  11608. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11609. _this.onContextRestoredObservable.notifyObservers(_this);
  11610. _this._contextWasLost = false;
  11611. }, 0);
  11612. };
  11613. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11614. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11615. }
  11616. }
  11617. else {
  11618. this._gl = canvasOrContext;
  11619. this._renderingCanvas = this._gl.canvas;
  11620. if (this._gl.renderbufferStorageMultisample) {
  11621. this._webGLVersion = 2.0;
  11622. }
  11623. options.stencil = this._gl.getContextAttributes().stencil;
  11624. }
  11625. // Viewport
  11626. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11627. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11628. this.resize();
  11629. this._isStencilEnable = options.stencil ? true : false;
  11630. this._initGLContext();
  11631. if (canvas) {
  11632. // Fullscreen
  11633. this._onFullscreenChange = function () {
  11634. if (document.fullscreen !== undefined) {
  11635. _this.isFullscreen = document.fullscreen;
  11636. }
  11637. else if (document.mozFullScreen !== undefined) {
  11638. _this.isFullscreen = document.mozFullScreen;
  11639. }
  11640. else if (document.webkitIsFullScreen !== undefined) {
  11641. _this.isFullscreen = document.webkitIsFullScreen;
  11642. }
  11643. else if (document.msIsFullScreen !== undefined) {
  11644. _this.isFullscreen = document.msIsFullScreen;
  11645. }
  11646. // Pointer lock
  11647. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11648. canvas.requestPointerLock = canvas.requestPointerLock ||
  11649. canvas.msRequestPointerLock ||
  11650. canvas.mozRequestPointerLock ||
  11651. canvas.webkitRequestPointerLock;
  11652. if (canvas.requestPointerLock) {
  11653. canvas.requestPointerLock();
  11654. }
  11655. }
  11656. };
  11657. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11658. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11659. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11660. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11661. // Pointer lock
  11662. this._onPointerLockChange = function () {
  11663. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11664. document.webkitPointerLockElement === canvas ||
  11665. document.msPointerLockElement === canvas ||
  11666. document.pointerLockElement === canvas);
  11667. };
  11668. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11669. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11670. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11671. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11672. this._onVRDisplayPointerRestricted = function () {
  11673. if (canvas) {
  11674. canvas.requestPointerLock();
  11675. }
  11676. };
  11677. this._onVRDisplayPointerUnrestricted = function () {
  11678. document.exitPointerLock();
  11679. };
  11680. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11681. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11682. }
  11683. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11684. Engine.audioEngine = new BABYLON.AudioEngine();
  11685. }
  11686. // Prepare buffer pointers
  11687. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11688. this._currentBufferPointers[i] = new BufferPointer();
  11689. }
  11690. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11691. // Load WebVR Devices
  11692. if (options.autoEnableWebVR) {
  11693. this.initWebVR();
  11694. }
  11695. // Detect if we are running on a faulty buggy OS.
  11696. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11697. // Detect if we are running on a faulty buggy desktop OS.
  11698. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11699. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11700. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11701. }
  11702. Object.defineProperty(Engine, "LastCreatedEngine", {
  11703. /**
  11704. * Gets the latest created engine
  11705. */
  11706. get: function () {
  11707. if (Engine.Instances.length === 0) {
  11708. return null;
  11709. }
  11710. return Engine.Instances[Engine.Instances.length - 1];
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine, "LastCreatedScene", {
  11716. /**
  11717. * Gets the latest created scene
  11718. */
  11719. get: function () {
  11720. var lastCreatedEngine = Engine.LastCreatedEngine;
  11721. if (!lastCreatedEngine) {
  11722. return null;
  11723. }
  11724. if (lastCreatedEngine.scenes.length === 0) {
  11725. return null;
  11726. }
  11727. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. /**
  11733. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11734. * @param flag defines which part of the materials must be marked as dirty
  11735. * @param predicate defines a predicate used to filter which materials should be affected
  11736. */
  11737. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11738. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11739. var engine = Engine.Instances[engineIndex];
  11740. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11741. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11742. }
  11743. }
  11744. };
  11745. Object.defineProperty(Engine, "NEVER", {
  11746. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11747. get: function () {
  11748. return Engine._NEVER;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "ALWAYS", {
  11754. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  11755. get: function () {
  11756. return Engine._ALWAYS;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine, "LESS", {
  11762. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11763. get: function () {
  11764. return Engine._LESS;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "EQUAL", {
  11770. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11771. get: function () {
  11772. return Engine._EQUAL;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "LEQUAL", {
  11778. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  11779. get: function () {
  11780. return Engine._LEQUAL;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "GREATER", {
  11786. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11787. get: function () {
  11788. return Engine._GREATER;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "GEQUAL", {
  11794. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  11795. get: function () {
  11796. return Engine._GEQUAL;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "NOTEQUAL", {
  11802. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  11803. get: function () {
  11804. return Engine._NOTEQUAL;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine, "KEEP", {
  11810. /** Passed to stencilOperation to specify that stencil value must be kept */
  11811. get: function () {
  11812. return Engine._KEEP;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine, "REPLACE", {
  11818. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11819. get: function () {
  11820. return Engine._REPLACE;
  11821. },
  11822. enumerable: true,
  11823. configurable: true
  11824. });
  11825. Object.defineProperty(Engine, "INCR", {
  11826. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11827. get: function () {
  11828. return Engine._INCR;
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(Engine, "DECR", {
  11834. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11835. get: function () {
  11836. return Engine._DECR;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine, "INVERT", {
  11842. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11843. get: function () {
  11844. return Engine._INVERT;
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(Engine, "INCR_WRAP", {
  11850. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11851. get: function () {
  11852. return Engine._INCR_WRAP;
  11853. },
  11854. enumerable: true,
  11855. configurable: true
  11856. });
  11857. Object.defineProperty(Engine, "DECR_WRAP", {
  11858. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11859. get: function () {
  11860. return Engine._DECR_WRAP;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11866. // Alpha
  11867. /** Defines that alpha blending is disabled */
  11868. get: function () {
  11869. return Engine._ALPHA_DISABLE;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11875. /** Defines that alpha blending to SRC + DEST */
  11876. get: function () {
  11877. return Engine._ALPHA_ONEONE;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine, "ALPHA_ADD", {
  11883. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11884. get: function () {
  11885. return Engine._ALPHA_ADD;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11891. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11892. get: function () {
  11893. return Engine._ALPHA_COMBINE;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11899. /** Defines that alpha blending to DEST - SRC * DEST */
  11900. get: function () {
  11901. return Engine._ALPHA_SUBTRACT;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11907. /** Defines that alpha blending to SRC * DEST */
  11908. get: function () {
  11909. return Engine._ALPHA_MULTIPLY;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11915. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11916. get: function () {
  11917. return Engine._ALPHA_MAXIMIZED;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11923. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11924. get: function () {
  11925. return Engine._ALPHA_PREMULTIPLIED;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11931. /**
  11932. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11933. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11934. */
  11935. get: function () {
  11936. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11942. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11943. get: function () {
  11944. return Engine._ALPHA_INTERPOLATE;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11950. /**
  11951. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11952. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11953. */
  11954. get: function () {
  11955. return Engine._ALPHA_SCREENMODE;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11961. // Delays
  11962. /** Defines that the ressource is not delayed*/
  11963. get: function () {
  11964. return Engine._DELAYLOADSTATE_NONE;
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11970. /** Defines that the ressource was successfully delay loaded */
  11971. get: function () {
  11972. return Engine._DELAYLOADSTATE_LOADED;
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11978. /** Defines that the ressource is currently delay loading */
  11979. get: function () {
  11980. return Engine._DELAYLOADSTATE_LOADING;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11986. /** Defines that the ressource is delayed and has not started loading */
  11987. get: function () {
  11988. return Engine._DELAYLOADSTATE_NOTLOADED;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11994. /** ALPHA */
  11995. get: function () {
  11996. return Engine._TEXTUREFORMAT_ALPHA;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12002. /** LUMINANCE */
  12003. get: function () {
  12004. return Engine._TEXTUREFORMAT_LUMINANCE;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  12010. /**
  12011. * R32F
  12012. */
  12013. get: function () {
  12014. return Engine._TEXTUREFORMAT_R32F;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  12020. /**
  12021. * RG32F
  12022. */
  12023. get: function () {
  12024. return Engine._TEXTUREFORMAT_RG32F;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  12030. /**
  12031. * RGB32F
  12032. */
  12033. get: function () {
  12034. return Engine._TEXTUREFORMAT_RGB32F;
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  12040. /**
  12041. * RGBA32F
  12042. */
  12043. get: function () {
  12044. return Engine._TEXTUREFORMAT_RGBA32F;
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12050. /** LUMINANCE_ALPHA */
  12051. get: function () {
  12052. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12053. },
  12054. enumerable: true,
  12055. configurable: true
  12056. });
  12057. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12058. /** RGB */
  12059. get: function () {
  12060. return Engine._TEXTUREFORMAT_RGB;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12066. /** RGBA */
  12067. get: function () {
  12068. return Engine._TEXTUREFORMAT_RGBA;
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12074. /** UNSIGNED_INT */
  12075. get: function () {
  12076. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12082. /** FLOAT */
  12083. get: function () {
  12084. return Engine._TEXTURETYPE_FLOAT;
  12085. },
  12086. enumerable: true,
  12087. configurable: true
  12088. });
  12089. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12090. /** HALF_FLOAT */
  12091. get: function () {
  12092. return Engine._TEXTURETYPE_HALF_FLOAT;
  12093. },
  12094. enumerable: true,
  12095. configurable: true
  12096. });
  12097. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12098. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12099. get: function () {
  12100. return Engine._SCALEMODE_FLOOR;
  12101. },
  12102. enumerable: true,
  12103. configurable: true
  12104. });
  12105. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12106. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12107. get: function () {
  12108. return Engine._SCALEMODE_NEAREST;
  12109. },
  12110. enumerable: true,
  12111. configurable: true
  12112. });
  12113. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12114. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12115. get: function () {
  12116. return Engine._SCALEMODE_CEILING;
  12117. },
  12118. enumerable: true,
  12119. configurable: true
  12120. });
  12121. Object.defineProperty(Engine, "Version", {
  12122. /**
  12123. * Returns the current version of the framework
  12124. */
  12125. get: function () {
  12126. return "3.3.0-alpha.2";
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12132. /**
  12133. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12134. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12135. */
  12136. get: function () {
  12137. return this._vrExclusivePointerMode;
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12143. /**
  12144. * Gets a boolean indicating that the engine supports uniform buffers
  12145. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12146. */
  12147. get: function () {
  12148. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12154. /**
  12155. * Gets a boolean indicating that only power of 2 textures are supported
  12156. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12157. */
  12158. get: function () {
  12159. return this._webGLVersion < 2 || this.forcePOTTextures;
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12165. /**
  12166. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12167. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12168. */
  12169. get: function () {
  12170. return this._doNotHandleContextLost;
  12171. },
  12172. set: function (value) {
  12173. this._doNotHandleContextLost = value;
  12174. },
  12175. enumerable: true,
  12176. configurable: true
  12177. });
  12178. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12179. /**
  12180. * Gets the performance monitor attached to this engine
  12181. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12182. */
  12183. get: function () {
  12184. return this._performanceMonitor;
  12185. },
  12186. enumerable: true,
  12187. configurable: true
  12188. });
  12189. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12190. /**
  12191. * Gets the list of texture formats supported
  12192. */
  12193. get: function () {
  12194. return this._texturesSupported;
  12195. },
  12196. enumerable: true,
  12197. configurable: true
  12198. });
  12199. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12200. /**
  12201. * Gets the list of texture formats in use
  12202. */
  12203. get: function () {
  12204. return this._textureFormatInUse;
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(Engine.prototype, "currentViewport", {
  12210. /**
  12211. * Gets the current viewport
  12212. */
  12213. get: function () {
  12214. return this._cachedViewport;
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12220. /**
  12221. * Gets the default empty texture
  12222. */
  12223. get: function () {
  12224. if (!this._emptyTexture) {
  12225. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12226. }
  12227. return this._emptyTexture;
  12228. },
  12229. enumerable: true,
  12230. configurable: true
  12231. });
  12232. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12233. /**
  12234. * Gets the default empty 3D texture
  12235. */
  12236. get: function () {
  12237. if (!this._emptyTexture3D) {
  12238. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12239. }
  12240. return this._emptyTexture3D;
  12241. },
  12242. enumerable: true,
  12243. configurable: true
  12244. });
  12245. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12246. /**
  12247. * Gets the default empty cube texture
  12248. */
  12249. get: function () {
  12250. if (!this._emptyCubeTexture) {
  12251. var faceData = new Uint8Array(4);
  12252. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12253. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12254. }
  12255. return this._emptyCubeTexture;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Engine.prototype._rebuildInternalTextures = function () {
  12261. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12262. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12263. var internalTexture = currentState_1[_i];
  12264. internalTexture._rebuild();
  12265. }
  12266. };
  12267. Engine.prototype._rebuildEffects = function () {
  12268. for (var key in this._compiledEffects) {
  12269. var effect = this._compiledEffects[key];
  12270. effect._prepareEffect();
  12271. }
  12272. BABYLON.Effect.ResetCache();
  12273. };
  12274. Engine.prototype._rebuildBuffers = function () {
  12275. // Index / Vertex
  12276. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12277. var scene = _a[_i];
  12278. scene.resetCachedMaterial();
  12279. scene._rebuildGeometries();
  12280. scene._rebuildTextures();
  12281. }
  12282. // Uniforms
  12283. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12284. var uniformBuffer = _c[_b];
  12285. uniformBuffer._rebuild();
  12286. }
  12287. };
  12288. Engine.prototype._initGLContext = function () {
  12289. // Caps
  12290. this._caps = new EngineCapabilities();
  12291. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12292. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12293. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12294. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12295. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12296. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12297. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12298. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12299. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12300. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12301. // Infos
  12302. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12303. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12304. if (rendererInfo != null) {
  12305. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12306. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12307. }
  12308. if (!this._glVendor) {
  12309. this._glVendor = "Unknown vendor";
  12310. }
  12311. if (!this._glRenderer) {
  12312. this._glRenderer = "Unknown renderer";
  12313. }
  12314. // Constants
  12315. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12316. if (this._gl.RGBA16F !== 0x881A) {
  12317. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12318. }
  12319. if (this._gl.RGBA32F !== 0x8814) {
  12320. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12321. }
  12322. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12323. this._gl.DEPTH24_STENCIL8 = 35056;
  12324. }
  12325. // Extensions
  12326. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12327. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12328. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12329. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12330. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12331. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12332. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12333. 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');
  12334. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12335. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12336. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12337. this._caps.highPrecisionShaderSupported = true;
  12338. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12339. if (this._caps.timerQuery) {
  12340. if (this._webGLVersion === 1) {
  12341. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12342. }
  12343. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12344. }
  12345. // Checks if some of the format renders first to allow the use of webgl inspector.
  12346. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12347. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12348. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12349. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12350. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12351. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12352. if (this._webGLVersion > 1) {
  12353. this._gl.HALF_FLOAT_OES = 0x140B;
  12354. }
  12355. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12356. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12357. // Draw buffers
  12358. if (this._webGLVersion > 1) {
  12359. this._caps.drawBuffersExtension = true;
  12360. }
  12361. else {
  12362. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12363. if (drawBuffersExtension !== null) {
  12364. this._caps.drawBuffersExtension = true;
  12365. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12366. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12367. for (var i = 0; i < 16; i++) {
  12368. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12369. }
  12370. }
  12371. else {
  12372. this._caps.drawBuffersExtension = false;
  12373. }
  12374. }
  12375. // Depth Texture
  12376. if (this._webGLVersion > 1) {
  12377. this._caps.depthTextureExtension = true;
  12378. }
  12379. else {
  12380. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12381. if (depthTextureExtension != null) {
  12382. this._caps.depthTextureExtension = true;
  12383. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12384. }
  12385. }
  12386. // Vertex array object
  12387. if (this._webGLVersion > 1) {
  12388. this._caps.vertexArrayObject = true;
  12389. }
  12390. else {
  12391. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12392. if (vertexArrayObjectExtension != null) {
  12393. this._caps.vertexArrayObject = true;
  12394. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12395. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12396. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12397. }
  12398. else {
  12399. this._caps.vertexArrayObject = false;
  12400. }
  12401. }
  12402. // Instances count
  12403. if (this._webGLVersion > 1) {
  12404. this._caps.instancedArrays = true;
  12405. }
  12406. else {
  12407. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12408. if (instanceExtension != null) {
  12409. this._caps.instancedArrays = true;
  12410. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12411. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12412. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12413. }
  12414. else {
  12415. this._caps.instancedArrays = false;
  12416. }
  12417. }
  12418. // Intelligently add supported compressed formats in order to check for.
  12419. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12420. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12421. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12422. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12423. if (this._caps.astc)
  12424. this.texturesSupported.push('-astc.ktx');
  12425. if (this._caps.s3tc)
  12426. this.texturesSupported.push('-dxt.ktx');
  12427. if (this._caps.pvrtc)
  12428. this.texturesSupported.push('-pvrtc.ktx');
  12429. if (this._caps.etc2)
  12430. this.texturesSupported.push('-etc2.ktx');
  12431. if (this._caps.etc1)
  12432. this.texturesSupported.push('-etc1.ktx');
  12433. if (this._gl.getShaderPrecisionFormat) {
  12434. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12435. if (highp) {
  12436. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12437. }
  12438. }
  12439. // Depth buffer
  12440. this.setDepthBuffer(true);
  12441. this.setDepthFunctionToLessOrEqual();
  12442. this.setDepthWrite(true);
  12443. // Texture maps
  12444. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12445. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12446. this._nextFreeTextureSlots.push(slot);
  12447. }
  12448. };
  12449. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12450. /**
  12451. * Gets version of the current webGL context
  12452. */
  12453. get: function () {
  12454. return this._webGLVersion;
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12460. /**
  12461. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12462. */
  12463. get: function () {
  12464. return this._isStencilEnable;
  12465. },
  12466. enumerable: true,
  12467. configurable: true
  12468. });
  12469. Engine.prototype._prepareWorkingCanvas = function () {
  12470. if (this._workingCanvas) {
  12471. return;
  12472. }
  12473. this._workingCanvas = document.createElement("canvas");
  12474. var context = this._workingCanvas.getContext("2d");
  12475. if (context) {
  12476. this._workingContext = context;
  12477. }
  12478. };
  12479. /**
  12480. * Reset the texture cache to empty state
  12481. */
  12482. Engine.prototype.resetTextureCache = function () {
  12483. for (var key in this._boundTexturesCache) {
  12484. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12485. continue;
  12486. }
  12487. var boundTexture = this._boundTexturesCache[key];
  12488. if (boundTexture) {
  12489. this._removeDesignatedSlot(boundTexture);
  12490. }
  12491. this._boundTexturesCache[key] = null;
  12492. }
  12493. if (!this.disableTextureBindingOptimization) {
  12494. this._nextFreeTextureSlots = [];
  12495. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12496. this._nextFreeTextureSlots.push(slot);
  12497. }
  12498. }
  12499. this._currentTextureChannel = -1;
  12500. };
  12501. /**
  12502. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12503. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12504. * @returns true if engine is in deterministic lock step mode
  12505. */
  12506. Engine.prototype.isDeterministicLockStep = function () {
  12507. return this._deterministicLockstep;
  12508. };
  12509. /**
  12510. * Gets the max steps when engine is running in deterministic lock step
  12511. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12512. * @returns the max steps
  12513. */
  12514. Engine.prototype.getLockstepMaxSteps = function () {
  12515. return this._lockstepMaxSteps;
  12516. };
  12517. /**
  12518. * Gets an object containing information about the current webGL context
  12519. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12520. */
  12521. Engine.prototype.getGlInfo = function () {
  12522. return {
  12523. vendor: this._glVendor,
  12524. renderer: this._glRenderer,
  12525. version: this._glVersion
  12526. };
  12527. };
  12528. /**
  12529. * Gets current aspect ratio
  12530. * @param camera defines the camera to use to get the aspect ratio
  12531. * @param useScreen defines if screen size must be used (or the current render target if any)
  12532. * @returns a number defining the aspect ratio
  12533. */
  12534. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12535. if (useScreen === void 0) { useScreen = false; }
  12536. var viewport = camera.viewport;
  12537. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12538. };
  12539. /**
  12540. * Gets current screen aspect ratio
  12541. * @returns a number defining the aspect ratio
  12542. */
  12543. Engine.prototype.getScreenAspectRatio = function () {
  12544. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12545. };
  12546. /**
  12547. * Gets the current render width
  12548. * @param useScreen defines if screen size must be used (or the current render target if any)
  12549. * @returns a number defining the current render width
  12550. */
  12551. Engine.prototype.getRenderWidth = function (useScreen) {
  12552. if (useScreen === void 0) { useScreen = false; }
  12553. if (!useScreen && this._currentRenderTarget) {
  12554. return this._currentRenderTarget.width;
  12555. }
  12556. return this._gl.drawingBufferWidth;
  12557. };
  12558. /**
  12559. * Gets the current render height
  12560. * @param useScreen defines if screen size must be used (or the current render target if any)
  12561. * @returns a number defining the current render height
  12562. */
  12563. Engine.prototype.getRenderHeight = function (useScreen) {
  12564. if (useScreen === void 0) { useScreen = false; }
  12565. if (!useScreen && this._currentRenderTarget) {
  12566. return this._currentRenderTarget.height;
  12567. }
  12568. return this._gl.drawingBufferHeight;
  12569. };
  12570. /**
  12571. * Gets the HTML canvas attached with the current webGL context
  12572. * @returns a HTML canvas
  12573. */
  12574. Engine.prototype.getRenderingCanvas = function () {
  12575. return this._renderingCanvas;
  12576. };
  12577. /**
  12578. * Gets the client rect of the HTML canvas attached with the current webGL context
  12579. * @returns a client rectanglee
  12580. */
  12581. Engine.prototype.getRenderingCanvasClientRect = function () {
  12582. if (!this._renderingCanvas) {
  12583. return null;
  12584. }
  12585. return this._renderingCanvas.getBoundingClientRect();
  12586. };
  12587. /**
  12588. * Defines the hardware scaling level.
  12589. * By default the hardware scaling level is computed from the window device ratio.
  12590. * 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.
  12591. * @param level defines the level to use
  12592. */
  12593. Engine.prototype.setHardwareScalingLevel = function (level) {
  12594. this._hardwareScalingLevel = level;
  12595. this.resize();
  12596. };
  12597. /**
  12598. * Gets the current hardware scaling level.
  12599. * By default the hardware scaling level is computed from the window device ratio.
  12600. * 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.
  12601. * @returns a number indicating the current hardware scaling level
  12602. */
  12603. Engine.prototype.getHardwareScalingLevel = function () {
  12604. return this._hardwareScalingLevel;
  12605. };
  12606. /**
  12607. * Gets the list of loaded textures
  12608. * @returns an array containing all loaded textures
  12609. */
  12610. Engine.prototype.getLoadedTexturesCache = function () {
  12611. return this._internalTexturesCache;
  12612. };
  12613. /**
  12614. * Gets the object containing all engine capabilities
  12615. * @returns the EngineCapabilities object
  12616. */
  12617. Engine.prototype.getCaps = function () {
  12618. return this._caps;
  12619. };
  12620. Object.defineProperty(Engine.prototype, "drawCalls", {
  12621. /** @hidden */
  12622. get: function () {
  12623. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12624. return 0;
  12625. },
  12626. enumerable: true,
  12627. configurable: true
  12628. });
  12629. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12630. /** @hidden */
  12631. get: function () {
  12632. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12633. return null;
  12634. },
  12635. enumerable: true,
  12636. configurable: true
  12637. });
  12638. /**
  12639. * Gets the current depth function
  12640. * @returns a number defining the depth function
  12641. */
  12642. Engine.prototype.getDepthFunction = function () {
  12643. return this._depthCullingState.depthFunc;
  12644. };
  12645. /**
  12646. * Sets the current depth function
  12647. * @param depthFunc defines the function to use
  12648. */
  12649. Engine.prototype.setDepthFunction = function (depthFunc) {
  12650. this._depthCullingState.depthFunc = depthFunc;
  12651. };
  12652. /**
  12653. * Sets the current depth function to GREATER
  12654. */
  12655. Engine.prototype.setDepthFunctionToGreater = function () {
  12656. this._depthCullingState.depthFunc = this._gl.GREATER;
  12657. };
  12658. /**
  12659. * Sets the current depth function to GEQUAL
  12660. */
  12661. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12662. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12663. };
  12664. /**
  12665. * Sets the current depth function to LESS
  12666. */
  12667. Engine.prototype.setDepthFunctionToLess = function () {
  12668. this._depthCullingState.depthFunc = this._gl.LESS;
  12669. };
  12670. /**
  12671. * Sets the current depth function to LEQUAL
  12672. */
  12673. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12674. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12675. };
  12676. /**
  12677. * Gets a boolean indicating if stencil buffer is enabled
  12678. * @returns the current stencil buffer state
  12679. */
  12680. Engine.prototype.getStencilBuffer = function () {
  12681. return this._stencilState.stencilTest;
  12682. };
  12683. /**
  12684. * Enable or disable the stencil buffer
  12685. * @param enable defines if the stencil buffer must be enabled or disabled
  12686. */
  12687. Engine.prototype.setStencilBuffer = function (enable) {
  12688. this._stencilState.stencilTest = enable;
  12689. };
  12690. /**
  12691. * Gets the current stencil mask
  12692. * @returns a number defining the new stencil mask to use
  12693. */
  12694. Engine.prototype.getStencilMask = function () {
  12695. return this._stencilState.stencilMask;
  12696. };
  12697. /**
  12698. * Sets the current stencil mask
  12699. * @param mask defines the new stencil mask to use
  12700. */
  12701. Engine.prototype.setStencilMask = function (mask) {
  12702. this._stencilState.stencilMask = mask;
  12703. };
  12704. /**
  12705. * Gets the current stencil function
  12706. * @returns a number defining the stencil function to use
  12707. */
  12708. Engine.prototype.getStencilFunction = function () {
  12709. return this._stencilState.stencilFunc;
  12710. };
  12711. /**
  12712. * Gets the current stencil reference value
  12713. * @returns a number defining the stencil reference value to use
  12714. */
  12715. Engine.prototype.getStencilFunctionReference = function () {
  12716. return this._stencilState.stencilFuncRef;
  12717. };
  12718. /**
  12719. * Gets the current stencil mask
  12720. * @returns a number defining the stencil mask to use
  12721. */
  12722. Engine.prototype.getStencilFunctionMask = function () {
  12723. return this._stencilState.stencilFuncMask;
  12724. };
  12725. /**
  12726. * Sets the current stencil function
  12727. * @param stencilFunc defines the new stencil function to use
  12728. */
  12729. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12730. this._stencilState.stencilFunc = stencilFunc;
  12731. };
  12732. /**
  12733. * Sets the current stencil reference
  12734. * @param reference defines the new stencil reference to use
  12735. */
  12736. Engine.prototype.setStencilFunctionReference = function (reference) {
  12737. this._stencilState.stencilFuncRef = reference;
  12738. };
  12739. /**
  12740. * Sets the current stencil mask
  12741. * @param mask defines the new stencil mask to use
  12742. */
  12743. Engine.prototype.setStencilFunctionMask = function (mask) {
  12744. this._stencilState.stencilFuncMask = mask;
  12745. };
  12746. /**
  12747. * Gets the current stencil operation when stencil fails
  12748. * @returns a number defining stencil operation to use when stencil fails
  12749. */
  12750. Engine.prototype.getStencilOperationFail = function () {
  12751. return this._stencilState.stencilOpStencilFail;
  12752. };
  12753. /**
  12754. * Gets the current stencil operation when depth fails
  12755. * @returns a number defining stencil operation to use when depth fails
  12756. */
  12757. Engine.prototype.getStencilOperationDepthFail = function () {
  12758. return this._stencilState.stencilOpDepthFail;
  12759. };
  12760. /**
  12761. * Gets the current stencil operation when stencil passes
  12762. * @returns a number defining stencil operation to use when stencil passes
  12763. */
  12764. Engine.prototype.getStencilOperationPass = function () {
  12765. return this._stencilState.stencilOpStencilDepthPass;
  12766. };
  12767. /**
  12768. * Sets the stencil operation to use when stencil fails
  12769. * @param operation defines the stencil operation to use when stencil fails
  12770. */
  12771. Engine.prototype.setStencilOperationFail = function (operation) {
  12772. this._stencilState.stencilOpStencilFail = operation;
  12773. };
  12774. /**
  12775. * Sets the stencil operation to use when depth fails
  12776. * @param operation defines the stencil operation to use when depth fails
  12777. */
  12778. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12779. this._stencilState.stencilOpDepthFail = operation;
  12780. };
  12781. /**
  12782. * Sets the stencil operation to use when stencil passes
  12783. * @param operation defines the stencil operation to use when stencil passes
  12784. */
  12785. Engine.prototype.setStencilOperationPass = function (operation) {
  12786. this._stencilState.stencilOpStencilDepthPass = operation;
  12787. };
  12788. /**
  12789. * Sets a boolean indicating if the dithering state is enabled or disabled
  12790. * @param value defines the dithering state
  12791. */
  12792. Engine.prototype.setDitheringState = function (value) {
  12793. if (value) {
  12794. this._gl.enable(this._gl.DITHER);
  12795. }
  12796. else {
  12797. this._gl.disable(this._gl.DITHER);
  12798. }
  12799. };
  12800. /**
  12801. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12802. * @param value defines the rasterizer state
  12803. */
  12804. Engine.prototype.setRasterizerState = function (value) {
  12805. if (value) {
  12806. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12807. }
  12808. else {
  12809. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12810. }
  12811. };
  12812. /**
  12813. * stop executing a render loop function and remove it from the execution array
  12814. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12815. */
  12816. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12817. if (!renderFunction) {
  12818. this._activeRenderLoops = [];
  12819. return;
  12820. }
  12821. var index = this._activeRenderLoops.indexOf(renderFunction);
  12822. if (index >= 0) {
  12823. this._activeRenderLoops.splice(index, 1);
  12824. }
  12825. };
  12826. /** @hidden */
  12827. Engine.prototype._renderLoop = function () {
  12828. if (!this._contextWasLost) {
  12829. var shouldRender = true;
  12830. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12831. shouldRender = false;
  12832. }
  12833. if (shouldRender) {
  12834. // Start new frame
  12835. this.beginFrame();
  12836. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12837. var renderFunction = this._activeRenderLoops[index];
  12838. renderFunction();
  12839. }
  12840. // Present
  12841. this.endFrame();
  12842. }
  12843. }
  12844. if (this._activeRenderLoops.length > 0) {
  12845. // Register new frame
  12846. var requester = null;
  12847. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12848. requester = this._vrDisplay;
  12849. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12850. }
  12851. else {
  12852. this._renderingQueueLaunched = false;
  12853. }
  12854. };
  12855. /**
  12856. * Register and execute a render loop. The engine can have more than one render function
  12857. * @param renderFunction defines the function to continuously execute
  12858. */
  12859. Engine.prototype.runRenderLoop = function (renderFunction) {
  12860. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12861. return;
  12862. }
  12863. this._activeRenderLoops.push(renderFunction);
  12864. if (!this._renderingQueueLaunched) {
  12865. this._renderingQueueLaunched = true;
  12866. this._bindedRenderFunction = this._renderLoop.bind(this);
  12867. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12868. }
  12869. };
  12870. /**
  12871. * Toggle full screen mode
  12872. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12873. * @param options defines an option object to be sent to the requestFullscreen function
  12874. */
  12875. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12876. if (this.isFullscreen) {
  12877. BABYLON.Tools.ExitFullscreen();
  12878. }
  12879. else {
  12880. this._pointerLockRequested = requestPointerLock;
  12881. if (this._renderingCanvas) {
  12882. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12883. }
  12884. }
  12885. };
  12886. /**
  12887. * Clear the current render buffer or the current render target (if any is set up)
  12888. * @param color defines the color to use
  12889. * @param backBuffer defines if the back buffer must be cleared
  12890. * @param depth defines if the depth buffer must be cleared
  12891. * @param stencil defines if the stencil buffer must be cleared
  12892. */
  12893. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12894. if (stencil === void 0) { stencil = false; }
  12895. this.applyStates();
  12896. var mode = 0;
  12897. if (backBuffer && color) {
  12898. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12899. mode |= this._gl.COLOR_BUFFER_BIT;
  12900. }
  12901. if (depth) {
  12902. this._gl.clearDepth(1.0);
  12903. mode |= this._gl.DEPTH_BUFFER_BIT;
  12904. }
  12905. if (stencil) {
  12906. this._gl.clearStencil(0);
  12907. mode |= this._gl.STENCIL_BUFFER_BIT;
  12908. }
  12909. this._gl.clear(mode);
  12910. };
  12911. /**
  12912. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12913. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12914. * @param y defines the y-coordinate of the corner of the clear rectangle
  12915. * @param width defines the width of the clear rectangle
  12916. * @param height defines the height of the clear rectangle
  12917. * @param clearColor defines the clear color
  12918. */
  12919. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12920. var gl = this._gl;
  12921. // Save state
  12922. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12923. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12924. // Change state
  12925. gl.enable(gl.SCISSOR_TEST);
  12926. gl.scissor(x, y, width, height);
  12927. // Clear
  12928. this.clear(clearColor, true, true, true);
  12929. // Restore state
  12930. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12931. if (curScissor === true) {
  12932. gl.enable(gl.SCISSOR_TEST);
  12933. }
  12934. else {
  12935. gl.disable(gl.SCISSOR_TEST);
  12936. }
  12937. };
  12938. /**
  12939. * Set the WebGL's viewport
  12940. * @param viewport defines the viewport element to be used
  12941. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12942. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12943. */
  12944. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12945. var width = requiredWidth || this.getRenderWidth();
  12946. var height = requiredHeight || this.getRenderHeight();
  12947. var x = viewport.x || 0;
  12948. var y = viewport.y || 0;
  12949. this._cachedViewport = viewport;
  12950. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12951. };
  12952. /**
  12953. * Directly set the WebGL Viewport
  12954. * @param x defines the x coordinate of the viewport (in screen space)
  12955. * @param y defines the y coordinate of the viewport (in screen space)
  12956. * @param width defines the width of the viewport (in screen space)
  12957. * @param height defines the height of the viewport (in screen space)
  12958. * @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
  12959. */
  12960. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12961. var currentViewport = this._cachedViewport;
  12962. this._cachedViewport = null;
  12963. this._gl.viewport(x, y, width, height);
  12964. return currentViewport;
  12965. };
  12966. /**
  12967. * Begin a new frame
  12968. */
  12969. Engine.prototype.beginFrame = function () {
  12970. this.onBeginFrameObservable.notifyObservers(this);
  12971. this._measureFps();
  12972. };
  12973. /**
  12974. * Enf the current frame
  12975. */
  12976. Engine.prototype.endFrame = function () {
  12977. // Force a flush in case we are using a bad OS.
  12978. if (this._badOS) {
  12979. this.flushFramebuffer();
  12980. }
  12981. // Submit frame to the vr device, if enabled
  12982. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12983. // TODO: We should only submit the frame if we read frameData successfully.
  12984. this._vrDisplay.submitFrame();
  12985. }
  12986. this.onEndFrameObservable.notifyObservers(this);
  12987. };
  12988. /**
  12989. * Resize the view according to the canvas' size
  12990. */
  12991. Engine.prototype.resize = function () {
  12992. // We're not resizing the size of the canvas while in VR mode & presenting
  12993. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12994. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12995. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12996. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12997. }
  12998. };
  12999. /**
  13000. * Force a specific size of the canvas
  13001. * @param width defines the new canvas' width
  13002. * @param height defines the new canvas' height
  13003. */
  13004. Engine.prototype.setSize = function (width, height) {
  13005. if (!this._renderingCanvas) {
  13006. return;
  13007. }
  13008. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13009. return;
  13010. }
  13011. this._renderingCanvas.width = width;
  13012. this._renderingCanvas.height = height;
  13013. for (var index = 0; index < this.scenes.length; index++) {
  13014. var scene = this.scenes[index];
  13015. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13016. var cam = scene.cameras[camIndex];
  13017. cam._currentRenderId = 0;
  13018. }
  13019. }
  13020. if (this.onResizeObservable.hasObservers) {
  13021. this.onResizeObservable.notifyObservers(this);
  13022. }
  13023. };
  13024. // WebVR functions
  13025. /**
  13026. * Gets a boolean indicating if a webVR device was detected
  13027. * @returns true if a webVR device was detected
  13028. */
  13029. Engine.prototype.isVRDevicePresent = function () {
  13030. return !!this._vrDisplay;
  13031. };
  13032. /**
  13033. * Gets the current webVR device
  13034. * @returns the current webVR device (or null)
  13035. */
  13036. Engine.prototype.getVRDevice = function () {
  13037. return this._vrDisplay;
  13038. };
  13039. /**
  13040. * Initializes a webVR display and starts listening to display change events
  13041. * The onVRDisplayChangedObservable will be notified upon these changes
  13042. * @returns The onVRDisplayChangedObservable
  13043. */
  13044. Engine.prototype.initWebVR = function () {
  13045. this.initWebVRAsync();
  13046. return this.onVRDisplayChangedObservable;
  13047. };
  13048. /**
  13049. * Initializes a webVR display and starts listening to display change events
  13050. * The onVRDisplayChangedObservable will be notified upon these changes
  13051. * @returns A promise containing a VRDisplay and if vr is supported
  13052. */
  13053. Engine.prototype.initWebVRAsync = function () {
  13054. var _this = this;
  13055. var notifyObservers = function () {
  13056. var eventArgs = {
  13057. vrDisplay: _this._vrDisplay,
  13058. vrSupported: _this._vrSupported
  13059. };
  13060. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13061. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13062. };
  13063. if (!this._onVrDisplayConnect) {
  13064. this._onVrDisplayConnect = function (event) {
  13065. _this._vrDisplay = event.display;
  13066. notifyObservers();
  13067. };
  13068. this._onVrDisplayDisconnect = function () {
  13069. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13070. _this._vrDisplay = undefined;
  13071. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13072. notifyObservers();
  13073. };
  13074. this._onVrDisplayPresentChange = function () {
  13075. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13076. };
  13077. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13078. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13079. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13080. }
  13081. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13082. this._webVRInitPromise.then(notifyObservers);
  13083. return this._webVRInitPromise;
  13084. };
  13085. /**
  13086. * Call this function to switch to webVR mode
  13087. * Will do nothing if webVR is not supported or if there is no webVR device
  13088. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13089. */
  13090. Engine.prototype.enableVR = function () {
  13091. var _this = this;
  13092. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13093. var onResolved = function () {
  13094. _this.onVRRequestPresentComplete.notifyObservers(true);
  13095. _this._onVRFullScreenTriggered();
  13096. };
  13097. var onRejected = function () {
  13098. _this.onVRRequestPresentComplete.notifyObservers(false);
  13099. };
  13100. this.onVRRequestPresentStart.notifyObservers(this);
  13101. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13102. }
  13103. };
  13104. /**
  13105. * Call this function to leave webVR mode
  13106. * Will do nothing if webVR is not supported or if there is no webVR device
  13107. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13108. */
  13109. Engine.prototype.disableVR = function () {
  13110. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13111. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13112. }
  13113. };
  13114. Engine.prototype._getVRDisplaysAsync = function () {
  13115. var _this = this;
  13116. return new Promise(function (res, rej) {
  13117. if (navigator.getVRDisplays) {
  13118. navigator.getVRDisplays().then(function (devices) {
  13119. _this._vrSupported = true;
  13120. // note that devices may actually be an empty array. This is fine;
  13121. // we expect this._vrDisplay to be undefined in this case.
  13122. _this._vrDisplay = devices[0];
  13123. res({
  13124. vrDisplay: _this._vrDisplay,
  13125. vrSupported: _this._vrSupported
  13126. });
  13127. });
  13128. }
  13129. else {
  13130. _this._vrDisplay = undefined;
  13131. _this._vrSupported = false;
  13132. res({
  13133. vrDisplay: _this._vrDisplay,
  13134. vrSupported: _this._vrSupported
  13135. });
  13136. }
  13137. });
  13138. };
  13139. /**
  13140. * Binds the frame buffer to the specified texture.
  13141. * @param texture The texture to render to or null for the default canvas
  13142. * @param faceIndex The face of the texture to render to in case of cube texture
  13143. * @param requiredWidth The width of the target to render to
  13144. * @param requiredHeight The height of the target to render to
  13145. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13146. * @param depthStencilTexture The depth stencil texture to use to render
  13147. */
  13148. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13149. if (this._currentRenderTarget) {
  13150. this.unBindFramebuffer(this._currentRenderTarget);
  13151. }
  13152. this._currentRenderTarget = texture;
  13153. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13154. var gl = this._gl;
  13155. if (texture.isCube) {
  13156. if (faceIndex === undefined) {
  13157. faceIndex = 0;
  13158. }
  13159. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13160. if (depthStencilTexture) {
  13161. if (depthStencilTexture._generateStencilBuffer) {
  13162. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13163. }
  13164. else {
  13165. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13166. }
  13167. }
  13168. }
  13169. if (this._cachedViewport && !forceFullscreenViewport) {
  13170. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13171. }
  13172. else {
  13173. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13174. }
  13175. this.wipeCaches();
  13176. };
  13177. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13178. if (this._currentFramebuffer !== framebuffer) {
  13179. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13180. this._currentFramebuffer = framebuffer;
  13181. }
  13182. };
  13183. /**
  13184. * Unbind the current render target texture from the webGL context
  13185. * @param texture defines the render target texture to unbind
  13186. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13187. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13188. */
  13189. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13190. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13191. this._currentRenderTarget = null;
  13192. // If MSAA, we need to bitblt back to main texture
  13193. var gl = this._gl;
  13194. if (texture._MSAAFramebuffer) {
  13195. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13196. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13197. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13198. }
  13199. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13200. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13201. gl.generateMipmap(gl.TEXTURE_2D);
  13202. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13203. }
  13204. if (onBeforeUnbind) {
  13205. if (texture._MSAAFramebuffer) {
  13206. // Bind the correct framebuffer
  13207. this.bindUnboundFramebuffer(texture._framebuffer);
  13208. }
  13209. onBeforeUnbind();
  13210. }
  13211. this.bindUnboundFramebuffer(null);
  13212. };
  13213. /**
  13214. * Unbind a list of render target textures from the webGL context
  13215. * This is used only when drawBuffer extension or webGL2 are active
  13216. * @param textures defines the render target textures to unbind
  13217. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13218. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13219. */
  13220. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13221. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13222. this._currentRenderTarget = null;
  13223. // If MSAA, we need to bitblt back to main texture
  13224. var gl = this._gl;
  13225. if (textures[0]._MSAAFramebuffer) {
  13226. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13227. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13228. var attachments = textures[0]._attachments;
  13229. if (!attachments) {
  13230. attachments = new Array(textures.length);
  13231. textures[0]._attachments = attachments;
  13232. }
  13233. for (var i = 0; i < textures.length; i++) {
  13234. var texture = textures[i];
  13235. for (var j = 0; j < attachments.length; j++) {
  13236. attachments[j] = gl.NONE;
  13237. }
  13238. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13239. gl.readBuffer(attachments[i]);
  13240. gl.drawBuffers(attachments);
  13241. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13242. }
  13243. for (var i = 0; i < attachments.length; i++) {
  13244. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13245. }
  13246. gl.drawBuffers(attachments);
  13247. }
  13248. for (var i = 0; i < textures.length; i++) {
  13249. var texture = textures[i];
  13250. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13251. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13252. gl.generateMipmap(gl.TEXTURE_2D);
  13253. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13254. }
  13255. }
  13256. if (onBeforeUnbind) {
  13257. if (textures[0]._MSAAFramebuffer) {
  13258. // Bind the correct framebuffer
  13259. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13260. }
  13261. onBeforeUnbind();
  13262. }
  13263. this.bindUnboundFramebuffer(null);
  13264. };
  13265. /**
  13266. * Force the mipmap generation for the given render target texture
  13267. * @param texture defines the render target texture to use
  13268. */
  13269. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13270. if (texture.generateMipMaps) {
  13271. var gl = this._gl;
  13272. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13273. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13274. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13275. }
  13276. };
  13277. /**
  13278. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13279. */
  13280. Engine.prototype.flushFramebuffer = function () {
  13281. this._gl.flush();
  13282. };
  13283. /**
  13284. * Unbind the current render target and bind the default framebuffer
  13285. */
  13286. Engine.prototype.restoreDefaultFramebuffer = function () {
  13287. if (this._currentRenderTarget) {
  13288. this.unBindFramebuffer(this._currentRenderTarget);
  13289. }
  13290. else {
  13291. this.bindUnboundFramebuffer(null);
  13292. }
  13293. if (this._cachedViewport) {
  13294. this.setViewport(this._cachedViewport);
  13295. }
  13296. this.wipeCaches();
  13297. };
  13298. // UBOs
  13299. /**
  13300. * Create an uniform buffer
  13301. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13302. * @param elements defines the content of the uniform buffer
  13303. * @returns the webGL uniform buffer
  13304. */
  13305. Engine.prototype.createUniformBuffer = function (elements) {
  13306. var ubo = this._gl.createBuffer();
  13307. if (!ubo) {
  13308. throw new Error("Unable to create uniform buffer");
  13309. }
  13310. this.bindUniformBuffer(ubo);
  13311. if (elements instanceof Float32Array) {
  13312. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13313. }
  13314. else {
  13315. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13316. }
  13317. this.bindUniformBuffer(null);
  13318. ubo.references = 1;
  13319. return ubo;
  13320. };
  13321. /**
  13322. * Create a dynamic uniform buffer
  13323. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13324. * @param elements defines the content of the uniform buffer
  13325. * @returns the webGL uniform buffer
  13326. */
  13327. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13328. var ubo = this._gl.createBuffer();
  13329. if (!ubo) {
  13330. throw new Error("Unable to create dynamic uniform buffer");
  13331. }
  13332. this.bindUniformBuffer(ubo);
  13333. if (elements instanceof Float32Array) {
  13334. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13335. }
  13336. else {
  13337. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13338. }
  13339. this.bindUniformBuffer(null);
  13340. ubo.references = 1;
  13341. return ubo;
  13342. };
  13343. /**
  13344. * Update an existing uniform buffer
  13345. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13346. * @param uniformBuffer defines the target uniform buffer
  13347. * @param elements defines the content to update
  13348. * @param offset defines the offset in the uniform buffer where update should start
  13349. * @param count defines the size of the data to update
  13350. */
  13351. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13352. this.bindUniformBuffer(uniformBuffer);
  13353. if (offset === undefined) {
  13354. offset = 0;
  13355. }
  13356. if (count === undefined) {
  13357. if (elements instanceof Float32Array) {
  13358. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13359. }
  13360. else {
  13361. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13362. }
  13363. }
  13364. else {
  13365. if (elements instanceof Float32Array) {
  13366. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13367. }
  13368. else {
  13369. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13370. }
  13371. }
  13372. this.bindUniformBuffer(null);
  13373. };
  13374. // VBOs
  13375. Engine.prototype._resetVertexBufferBinding = function () {
  13376. this.bindArrayBuffer(null);
  13377. this._cachedVertexBuffers = null;
  13378. };
  13379. /**
  13380. * Creates a vertex buffer
  13381. * @param data the data for the vertex buffer
  13382. * @returns the new WebGL static buffer
  13383. */
  13384. Engine.prototype.createVertexBuffer = function (data) {
  13385. var vbo = this._gl.createBuffer();
  13386. if (!vbo) {
  13387. throw new Error("Unable to create vertex buffer");
  13388. }
  13389. this.bindArrayBuffer(vbo);
  13390. if (data instanceof Array) {
  13391. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13392. }
  13393. else {
  13394. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13395. }
  13396. this._resetVertexBufferBinding();
  13397. vbo.references = 1;
  13398. return vbo;
  13399. };
  13400. /**
  13401. * Creates a dynamic vertex buffer
  13402. * @param data the data for the dynamic vertex buffer
  13403. * @returns the new WebGL dynamic buffer
  13404. */
  13405. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13406. var vbo = this._gl.createBuffer();
  13407. if (!vbo) {
  13408. throw new Error("Unable to create dynamic vertex buffer");
  13409. }
  13410. this.bindArrayBuffer(vbo);
  13411. if (data instanceof Array) {
  13412. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13413. }
  13414. else {
  13415. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13416. }
  13417. this._resetVertexBufferBinding();
  13418. vbo.references = 1;
  13419. return vbo;
  13420. };
  13421. /**
  13422. * Update a dynamic index buffer
  13423. * @param indexBuffer defines the target index buffer
  13424. * @param indices defines the data to update
  13425. * @param offset defines the offset in the target index buffer where update should start
  13426. */
  13427. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13428. if (offset === void 0) { offset = 0; }
  13429. // Force cache update
  13430. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13431. this.bindIndexBuffer(indexBuffer);
  13432. var arrayBuffer;
  13433. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13434. arrayBuffer = indices;
  13435. }
  13436. else {
  13437. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13438. }
  13439. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13440. this._resetIndexBufferBinding();
  13441. };
  13442. /**
  13443. * Updates a dynamic vertex buffer.
  13444. * @param vertexBuffer the vertex buffer to update
  13445. * @param data the data used to update the vertex buffer
  13446. * @param byteOffset the byte offset of the data
  13447. * @param byteLength the byte length of the data
  13448. */
  13449. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13450. this.bindArrayBuffer(vertexBuffer);
  13451. if (byteOffset === undefined) {
  13452. byteOffset = 0;
  13453. }
  13454. if (byteLength === undefined) {
  13455. if (data instanceof Array) {
  13456. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13457. }
  13458. else {
  13459. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13460. }
  13461. }
  13462. else {
  13463. if (data instanceof Array) {
  13464. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13465. }
  13466. else {
  13467. if (data instanceof ArrayBuffer) {
  13468. data = new Uint8Array(data, byteOffset, byteLength);
  13469. }
  13470. else {
  13471. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13472. }
  13473. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13474. }
  13475. }
  13476. this._resetVertexBufferBinding();
  13477. };
  13478. Engine.prototype._resetIndexBufferBinding = function () {
  13479. this.bindIndexBuffer(null);
  13480. this._cachedIndexBuffer = null;
  13481. };
  13482. /**
  13483. * Creates a new index buffer
  13484. * @param indices defines the content of the index buffer
  13485. * @param updatable defines if the index buffer must be updatable
  13486. * @returns a new webGL buffer
  13487. */
  13488. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13489. var vbo = this._gl.createBuffer();
  13490. if (!vbo) {
  13491. throw new Error("Unable to create index buffer");
  13492. }
  13493. this.bindIndexBuffer(vbo);
  13494. // Check for 32 bits indices
  13495. var arrayBuffer;
  13496. var need32Bits = false;
  13497. if (indices instanceof Uint16Array) {
  13498. arrayBuffer = indices;
  13499. }
  13500. else {
  13501. //check 32 bit support
  13502. if (this._caps.uintIndices) {
  13503. if (indices instanceof Uint32Array) {
  13504. arrayBuffer = indices;
  13505. need32Bits = true;
  13506. }
  13507. else {
  13508. //number[] or Int32Array, check if 32 bit is necessary
  13509. for (var index = 0; index < indices.length; index++) {
  13510. if (indices[index] > 65535) {
  13511. need32Bits = true;
  13512. break;
  13513. }
  13514. }
  13515. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13516. }
  13517. }
  13518. else {
  13519. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13520. arrayBuffer = new Uint16Array(indices);
  13521. }
  13522. }
  13523. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13524. this._resetIndexBufferBinding();
  13525. vbo.references = 1;
  13526. vbo.is32Bits = need32Bits;
  13527. return vbo;
  13528. };
  13529. /**
  13530. * Bind a webGL buffer to the webGL context
  13531. * @param buffer defines the buffer to bind
  13532. */
  13533. Engine.prototype.bindArrayBuffer = function (buffer) {
  13534. if (!this._vaoRecordInProgress) {
  13535. this._unbindVertexArrayObject();
  13536. }
  13537. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13538. };
  13539. /**
  13540. * Bind an uniform buffer to the current webGL context
  13541. * @param buffer defines the buffer to bind
  13542. */
  13543. Engine.prototype.bindUniformBuffer = function (buffer) {
  13544. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13545. };
  13546. /**
  13547. * Bind a buffer to the current webGL context at a given location
  13548. * @param buffer defines the buffer to bind
  13549. * @param location defines the index where to bind the buffer
  13550. */
  13551. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13552. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13553. };
  13554. /**
  13555. * Bind a specific block at a given index in a specific shader program
  13556. * @param shaderProgram defines the shader program
  13557. * @param blockName defines the block name
  13558. * @param index defines the index where to bind the block
  13559. */
  13560. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13561. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13562. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13563. };
  13564. ;
  13565. Engine.prototype.bindIndexBuffer = function (buffer) {
  13566. if (!this._vaoRecordInProgress) {
  13567. this._unbindVertexArrayObject();
  13568. }
  13569. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13570. };
  13571. Engine.prototype.bindBuffer = function (buffer, target) {
  13572. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13573. this._gl.bindBuffer(target, buffer);
  13574. this._currentBoundBuffer[target] = buffer;
  13575. }
  13576. };
  13577. /**
  13578. * update the bound buffer with the given data
  13579. * @param data defines the data to update
  13580. */
  13581. Engine.prototype.updateArrayBuffer = function (data) {
  13582. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13583. };
  13584. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13585. var pointer = this._currentBufferPointers[indx];
  13586. var changed = false;
  13587. if (!pointer.active) {
  13588. changed = true;
  13589. pointer.active = true;
  13590. pointer.index = indx;
  13591. pointer.size = size;
  13592. pointer.type = type;
  13593. pointer.normalized = normalized;
  13594. pointer.stride = stride;
  13595. pointer.offset = offset;
  13596. pointer.buffer = buffer;
  13597. }
  13598. else {
  13599. if (pointer.buffer !== buffer) {
  13600. pointer.buffer = buffer;
  13601. changed = true;
  13602. }
  13603. if (pointer.size !== size) {
  13604. pointer.size = size;
  13605. changed = true;
  13606. }
  13607. if (pointer.type !== type) {
  13608. pointer.type = type;
  13609. changed = true;
  13610. }
  13611. if (pointer.normalized !== normalized) {
  13612. pointer.normalized = normalized;
  13613. changed = true;
  13614. }
  13615. if (pointer.stride !== stride) {
  13616. pointer.stride = stride;
  13617. changed = true;
  13618. }
  13619. if (pointer.offset !== offset) {
  13620. pointer.offset = offset;
  13621. changed = true;
  13622. }
  13623. }
  13624. if (changed || this._vaoRecordInProgress) {
  13625. this.bindArrayBuffer(buffer);
  13626. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13627. }
  13628. };
  13629. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13630. if (indexBuffer == null) {
  13631. return;
  13632. }
  13633. if (this._cachedIndexBuffer !== indexBuffer) {
  13634. this._cachedIndexBuffer = indexBuffer;
  13635. this.bindIndexBuffer(indexBuffer);
  13636. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13637. }
  13638. };
  13639. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13640. var attributes = effect.getAttributesNames();
  13641. if (!this._vaoRecordInProgress) {
  13642. this._unbindVertexArrayObject();
  13643. }
  13644. this.unbindAllAttributes();
  13645. for (var index = 0; index < attributes.length; index++) {
  13646. var order = effect.getAttributeLocation(index);
  13647. if (order >= 0) {
  13648. var vertexBuffer = vertexBuffers[attributes[index]];
  13649. if (!vertexBuffer) {
  13650. continue;
  13651. }
  13652. this._gl.enableVertexAttribArray(order);
  13653. if (!this._vaoRecordInProgress) {
  13654. this._vertexAttribArraysEnabled[order] = true;
  13655. }
  13656. var buffer = vertexBuffer.getBuffer();
  13657. if (buffer) {
  13658. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13659. if (vertexBuffer.getIsInstanced()) {
  13660. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13661. if (!this._vaoRecordInProgress) {
  13662. this._currentInstanceLocations.push(order);
  13663. this._currentInstanceBuffers.push(buffer);
  13664. }
  13665. }
  13666. }
  13667. }
  13668. }
  13669. };
  13670. /**
  13671. * Records a vertex array object
  13672. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13673. * @param vertexBuffers defines the list of vertex buffers to store
  13674. * @param indexBuffer defines the index buffer to store
  13675. * @param effect defines the effect to store
  13676. * @returns the new vertex array object
  13677. */
  13678. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13679. var vao = this._gl.createVertexArray();
  13680. this._vaoRecordInProgress = true;
  13681. this._gl.bindVertexArray(vao);
  13682. this._mustWipeVertexAttributes = true;
  13683. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13684. this.bindIndexBuffer(indexBuffer);
  13685. this._vaoRecordInProgress = false;
  13686. this._gl.bindVertexArray(null);
  13687. return vao;
  13688. };
  13689. /**
  13690. * Bind a specific vertex array object
  13691. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13692. * @param vertexArrayObject defines the vertex array object to bind
  13693. * @param indexBuffer defines the index buffer to bind
  13694. */
  13695. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13696. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13697. this._cachedVertexArrayObject = vertexArrayObject;
  13698. this._gl.bindVertexArray(vertexArrayObject);
  13699. this._cachedVertexBuffers = null;
  13700. this._cachedIndexBuffer = null;
  13701. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13702. this._mustWipeVertexAttributes = true;
  13703. }
  13704. };
  13705. /**
  13706. * Bind webGl buffers directly to the webGL context
  13707. * @param vertexBuffer defines the vertex buffer to bind
  13708. * @param indexBuffer defines the index buffer to bind
  13709. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13710. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13711. * @param effect defines the effect associated with the vertex buffer
  13712. */
  13713. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13714. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13715. this._cachedVertexBuffers = vertexBuffer;
  13716. this._cachedEffectForVertexBuffers = effect;
  13717. var attributesCount = effect.getAttributesCount();
  13718. this._unbindVertexArrayObject();
  13719. this.unbindAllAttributes();
  13720. var offset = 0;
  13721. for (var index = 0; index < attributesCount; index++) {
  13722. if (index < vertexDeclaration.length) {
  13723. var order = effect.getAttributeLocation(index);
  13724. if (order >= 0) {
  13725. this._gl.enableVertexAttribArray(order);
  13726. this._vertexAttribArraysEnabled[order] = true;
  13727. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13728. }
  13729. offset += vertexDeclaration[index] * 4;
  13730. }
  13731. }
  13732. }
  13733. this._bindIndexBufferWithCache(indexBuffer);
  13734. };
  13735. Engine.prototype._unbindVertexArrayObject = function () {
  13736. if (!this._cachedVertexArrayObject) {
  13737. return;
  13738. }
  13739. this._cachedVertexArrayObject = null;
  13740. this._gl.bindVertexArray(null);
  13741. };
  13742. /**
  13743. * Bind a list of vertex buffers to the webGL context
  13744. * @param vertexBuffers defines the list of vertex buffers to bind
  13745. * @param indexBuffer defines the index buffer to bind
  13746. * @param effect defines the effect associated with the vertex buffers
  13747. */
  13748. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13749. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13750. this._cachedVertexBuffers = vertexBuffers;
  13751. this._cachedEffectForVertexBuffers = effect;
  13752. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13753. }
  13754. this._bindIndexBufferWithCache(indexBuffer);
  13755. };
  13756. /**
  13757. * Unbind all instance attributes
  13758. */
  13759. Engine.prototype.unbindInstanceAttributes = function () {
  13760. var boundBuffer;
  13761. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13762. var instancesBuffer = this._currentInstanceBuffers[i];
  13763. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13764. boundBuffer = instancesBuffer;
  13765. this.bindArrayBuffer(instancesBuffer);
  13766. }
  13767. var offsetLocation = this._currentInstanceLocations[i];
  13768. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13769. }
  13770. this._currentInstanceBuffers.length = 0;
  13771. this._currentInstanceLocations.length = 0;
  13772. };
  13773. /**
  13774. * Release and free the memory of a vertex array object
  13775. * @param vao defines the vertex array object to delete
  13776. */
  13777. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13778. this._gl.deleteVertexArray(vao);
  13779. };
  13780. /** @hidden */
  13781. Engine.prototype._releaseBuffer = function (buffer) {
  13782. buffer.references--;
  13783. if (buffer.references === 0) {
  13784. this._gl.deleteBuffer(buffer);
  13785. return true;
  13786. }
  13787. return false;
  13788. };
  13789. /**
  13790. * Creates a webGL buffer to use with instanciation
  13791. * @param capacity defines the size of the buffer
  13792. * @returns the webGL buffer
  13793. */
  13794. Engine.prototype.createInstancesBuffer = function (capacity) {
  13795. var buffer = this._gl.createBuffer();
  13796. if (!buffer) {
  13797. throw new Error("Unable to create instance buffer");
  13798. }
  13799. buffer.capacity = capacity;
  13800. this.bindArrayBuffer(buffer);
  13801. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13802. return buffer;
  13803. };
  13804. /**
  13805. * Delete a webGL buffer used with instanciation
  13806. * @param buffer defines the webGL buffer to delete
  13807. */
  13808. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13809. this._gl.deleteBuffer(buffer);
  13810. };
  13811. /**
  13812. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13813. * @param instancesBuffer defines the webGL buffer to update and bind
  13814. * @param data defines the data to store in the buffer
  13815. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13816. */
  13817. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13818. this.bindArrayBuffer(instancesBuffer);
  13819. if (data) {
  13820. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13821. }
  13822. if (offsetLocations[0].index !== undefined) {
  13823. var stride = 0;
  13824. for (var i = 0; i < offsetLocations.length; i++) {
  13825. var ai = offsetLocations[i];
  13826. stride += ai.attributeSize * 4;
  13827. }
  13828. for (var i = 0; i < offsetLocations.length; i++) {
  13829. var ai = offsetLocations[i];
  13830. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13831. this._gl.enableVertexAttribArray(ai.index);
  13832. this._vertexAttribArraysEnabled[ai.index] = true;
  13833. }
  13834. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13835. this._gl.vertexAttribDivisor(ai.index, 1);
  13836. this._currentInstanceLocations.push(ai.index);
  13837. this._currentInstanceBuffers.push(instancesBuffer);
  13838. }
  13839. }
  13840. else {
  13841. for (var index = 0; index < 4; index++) {
  13842. var offsetLocation = offsetLocations[index];
  13843. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13844. this._gl.enableVertexAttribArray(offsetLocation);
  13845. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13846. }
  13847. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13848. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13849. this._currentInstanceLocations.push(offsetLocation);
  13850. this._currentInstanceBuffers.push(instancesBuffer);
  13851. }
  13852. }
  13853. };
  13854. /**
  13855. * Apply all cached states (depth, culling, stencil and alpha)
  13856. */
  13857. Engine.prototype.applyStates = function () {
  13858. this._depthCullingState.apply(this._gl);
  13859. this._stencilState.apply(this._gl);
  13860. this._alphaState.apply(this._gl);
  13861. };
  13862. /**
  13863. * Send a draw order
  13864. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13865. * @param indexStart defines the starting index
  13866. * @param indexCount defines the number of index to draw
  13867. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13868. */
  13869. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13870. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13871. };
  13872. /**
  13873. * Draw a list of points
  13874. * @param verticesStart defines the index of first vertex to draw
  13875. * @param verticesCount defines the count of vertices to draw
  13876. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13877. */
  13878. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13879. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13880. };
  13881. /**
  13882. * Draw a list of unindexed primitives
  13883. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13884. * @param verticesStart defines the index of first vertex to draw
  13885. * @param verticesCount defines the count of vertices to draw
  13886. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13887. */
  13888. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13889. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13890. };
  13891. /**
  13892. * Draw a list of indexed primitives
  13893. * @param fillMode defines the primitive to use
  13894. * @param indexStart defines the starting index
  13895. * @param indexCount defines the number of index to draw
  13896. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13897. */
  13898. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13899. // Apply states
  13900. this.applyStates();
  13901. this._drawCalls.addCount(1, false);
  13902. // Render
  13903. var drawMode = this._drawMode(fillMode);
  13904. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13905. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13906. if (instancesCount) {
  13907. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13908. }
  13909. else {
  13910. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13911. }
  13912. };
  13913. /**
  13914. * Draw a list of unindexed primitives
  13915. * @param fillMode defines the primitive to use
  13916. * @param verticesStart defines the index of first vertex to draw
  13917. * @param verticesCount defines the count of vertices to draw
  13918. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13919. */
  13920. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13921. // Apply states
  13922. this.applyStates();
  13923. this._drawCalls.addCount(1, false);
  13924. var drawMode = this._drawMode(fillMode);
  13925. if (instancesCount) {
  13926. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13927. }
  13928. else {
  13929. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13930. }
  13931. };
  13932. Engine.prototype._drawMode = function (fillMode) {
  13933. switch (fillMode) {
  13934. // Triangle views
  13935. case BABYLON.Material.TriangleFillMode:
  13936. return this._gl.TRIANGLES;
  13937. case BABYLON.Material.PointFillMode:
  13938. return this._gl.POINTS;
  13939. case BABYLON.Material.WireFrameFillMode:
  13940. return this._gl.LINES;
  13941. // Draw modes
  13942. case BABYLON.Material.PointListDrawMode:
  13943. return this._gl.POINTS;
  13944. case BABYLON.Material.LineListDrawMode:
  13945. return this._gl.LINES;
  13946. case BABYLON.Material.LineLoopDrawMode:
  13947. return this._gl.LINE_LOOP;
  13948. case BABYLON.Material.LineStripDrawMode:
  13949. return this._gl.LINE_STRIP;
  13950. case BABYLON.Material.TriangleStripDrawMode:
  13951. return this._gl.TRIANGLE_STRIP;
  13952. case BABYLON.Material.TriangleFanDrawMode:
  13953. return this._gl.TRIANGLE_FAN;
  13954. default:
  13955. return this._gl.TRIANGLES;
  13956. }
  13957. };
  13958. // Shaders
  13959. /** @hidden */
  13960. Engine.prototype._releaseEffect = function (effect) {
  13961. if (this._compiledEffects[effect._key]) {
  13962. delete this._compiledEffects[effect._key];
  13963. this._deleteProgram(effect.getProgram());
  13964. }
  13965. };
  13966. /** @hidden */
  13967. Engine.prototype._deleteProgram = function (program) {
  13968. if (program) {
  13969. program.__SPECTOR_rebuildProgram = null;
  13970. if (program.transformFeedback) {
  13971. this.deleteTransformFeedback(program.transformFeedback);
  13972. program.transformFeedback = null;
  13973. }
  13974. this._gl.deleteProgram(program);
  13975. }
  13976. };
  13977. /**
  13978. * Create a new effect (used to store vertex/fragment shaders)
  13979. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13980. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13981. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13982. * @param samplers defines an array of string used to represent textures
  13983. * @param defines defines the string containing the defines to use to compile the shaders
  13984. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13985. * @param onCompiled defines a function to call when the effect creation is successful
  13986. * @param onError defines a function to call when the effect creation has failed
  13987. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13988. * @returns the new Effect
  13989. */
  13990. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13991. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13992. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13993. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13994. if (this._compiledEffects[name]) {
  13995. var compiledEffect = this._compiledEffects[name];
  13996. if (onCompiled && compiledEffect.isReady()) {
  13997. onCompiled(compiledEffect);
  13998. }
  13999. return compiledEffect;
  14000. }
  14001. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14002. effect._key = name;
  14003. this._compiledEffects[name] = effect;
  14004. return effect;
  14005. };
  14006. /**
  14007. * Create an effect to use with particle systems
  14008. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14009. * @param uniformsNames defines a list of attribute names
  14010. * @param samplers defines an array of string used to represent textures
  14011. * @param defines defines the string containing the defines to use to compile the shaders
  14012. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14013. * @param onCompiled defines a function to call when the effect creation is successful
  14014. * @param onError defines a function to call when the effect creation has failed
  14015. * @returns the new Effect
  14016. */
  14017. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14018. if (uniformsNames === void 0) { uniformsNames = []; }
  14019. if (samplers === void 0) { samplers = []; }
  14020. if (defines === void 0) { defines = ""; }
  14021. return this.createEffect({
  14022. vertex: "particles",
  14023. fragmentElement: fragmentName
  14024. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14025. };
  14026. /**
  14027. * Directly creates a webGL program
  14028. * @param vertexCode defines the vertex shader code to use
  14029. * @param fragmentCode defines the fragment shader code to use
  14030. * @param context defines the webGL context to use (if not set, the current one will be used)
  14031. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14032. * @returns the new webGL program
  14033. */
  14034. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14035. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14036. context = context || this._gl;
  14037. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14038. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14039. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14040. };
  14041. /**
  14042. * Creates a webGL program
  14043. * @param vertexCode defines the vertex shader code to use
  14044. * @param fragmentCode defines the fragment shader code to use
  14045. * @param defines defines the string containing the defines to use to compile the shaders
  14046. * @param context defines the webGL context to use (if not set, the current one will be used)
  14047. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14048. * @returns the new webGL program
  14049. */
  14050. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14051. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14052. context = context || this._gl;
  14053. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14054. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14055. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14056. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14057. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14058. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14059. return program;
  14060. };
  14061. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14062. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14063. var shaderProgram = context.createProgram();
  14064. if (!shaderProgram) {
  14065. throw new Error("Unable to create program");
  14066. }
  14067. context.attachShader(shaderProgram, vertexShader);
  14068. context.attachShader(shaderProgram, fragmentShader);
  14069. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14070. var transformFeedback = this.createTransformFeedback();
  14071. this.bindTransformFeedback(transformFeedback);
  14072. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14073. shaderProgram.transformFeedback = transformFeedback;
  14074. }
  14075. context.linkProgram(shaderProgram);
  14076. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14077. this.bindTransformFeedback(null);
  14078. }
  14079. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14080. if (!linked) {
  14081. context.validateProgram(shaderProgram);
  14082. var error = context.getProgramInfoLog(shaderProgram);
  14083. if (error) {
  14084. throw new Error(error);
  14085. }
  14086. }
  14087. context.deleteShader(vertexShader);
  14088. context.deleteShader(fragmentShader);
  14089. return shaderProgram;
  14090. };
  14091. /**
  14092. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14093. * @param shaderProgram defines the webGL program to use
  14094. * @param uniformsNames defines the list of uniform names
  14095. * @returns an array of webGL uniform locations
  14096. */
  14097. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14098. var results = new Array();
  14099. for (var index = 0; index < uniformsNames.length; index++) {
  14100. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14101. }
  14102. return results;
  14103. };
  14104. /**
  14105. * Gets the lsit of active attributes for a given webGL program
  14106. * @param shaderProgram defines the webGL program to use
  14107. * @param attributesNames defines the list of attribute names to get
  14108. * @returns an array of indices indicating the offset of each attribute
  14109. */
  14110. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14111. var results = [];
  14112. for (var index = 0; index < attributesNames.length; index++) {
  14113. try {
  14114. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14115. }
  14116. catch (e) {
  14117. results.push(-1);
  14118. }
  14119. }
  14120. return results;
  14121. };
  14122. /**
  14123. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14124. * @param effect defines the effect to activate
  14125. */
  14126. Engine.prototype.enableEffect = function (effect) {
  14127. if (!effect) {
  14128. return;
  14129. }
  14130. // Use program
  14131. this.bindSamplers(effect);
  14132. this._currentEffect = effect;
  14133. if (effect.onBind) {
  14134. effect.onBind(effect);
  14135. }
  14136. effect.onBindObservable.notifyObservers(effect);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to an array of int32
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param array defines the array of int32 to store
  14142. */
  14143. Engine.prototype.setIntArray = function (uniform, array) {
  14144. if (!uniform)
  14145. return;
  14146. this._gl.uniform1iv(uniform, array);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to an array of int32 (stored as vec2)
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param array defines the array of int32 to store
  14152. */
  14153. Engine.prototype.setIntArray2 = function (uniform, array) {
  14154. if (!uniform || array.length % 2 !== 0)
  14155. return;
  14156. this._gl.uniform2iv(uniform, array);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to an array of int32 (stored as vec3)
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param array defines the array of int32 to store
  14162. */
  14163. Engine.prototype.setIntArray3 = function (uniform, array) {
  14164. if (!uniform || array.length % 3 !== 0)
  14165. return;
  14166. this._gl.uniform3iv(uniform, array);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to an array of int32 (stored as vec4)
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param array defines the array of int32 to store
  14172. */
  14173. Engine.prototype.setIntArray4 = function (uniform, array) {
  14174. if (!uniform || array.length % 4 !== 0)
  14175. return;
  14176. this._gl.uniform4iv(uniform, array);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to an array of float32
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param array defines the array of float32 to store
  14182. */
  14183. Engine.prototype.setFloatArray = function (uniform, array) {
  14184. if (!uniform)
  14185. return;
  14186. this._gl.uniform1fv(uniform, array);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to an array of float32 (stored as vec2)
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param array defines the array of float32 to store
  14192. */
  14193. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14194. if (!uniform || array.length % 2 !== 0)
  14195. return;
  14196. this._gl.uniform2fv(uniform, array);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to an array of float32 (stored as vec3)
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param array defines the array of float32 to store
  14202. */
  14203. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14204. if (!uniform || array.length % 3 !== 0)
  14205. return;
  14206. this._gl.uniform3fv(uniform, array);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to an array of float32 (stored as vec4)
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param array defines the array of float32 to store
  14212. */
  14213. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14214. if (!uniform || array.length % 4 !== 0)
  14215. return;
  14216. this._gl.uniform4fv(uniform, array);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to an array of number
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param array defines the array of number to store
  14222. */
  14223. Engine.prototype.setArray = function (uniform, array) {
  14224. if (!uniform)
  14225. return;
  14226. this._gl.uniform1fv(uniform, array);
  14227. };
  14228. /**
  14229. * Set the value of an uniform to an array of number (stored as vec2)
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param array defines the array of number to store
  14232. */
  14233. Engine.prototype.setArray2 = function (uniform, array) {
  14234. if (!uniform || array.length % 2 !== 0)
  14235. return;
  14236. this._gl.uniform2fv(uniform, array);
  14237. };
  14238. /**
  14239. * Set the value of an uniform to an array of number (stored as vec3)
  14240. * @param uniform defines the webGL uniform location where to store the value
  14241. * @param array defines the array of number to store
  14242. */
  14243. Engine.prototype.setArray3 = function (uniform, array) {
  14244. if (!uniform || array.length % 3 !== 0)
  14245. return;
  14246. this._gl.uniform3fv(uniform, array);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to an array of number (stored as vec4)
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param array defines the array of number to store
  14252. */
  14253. Engine.prototype.setArray4 = function (uniform, array) {
  14254. if (!uniform || array.length % 4 !== 0)
  14255. return;
  14256. this._gl.uniform4fv(uniform, array);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to an array of float32 (stored as matrices)
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param matrices defines the array of float32 to store
  14262. */
  14263. Engine.prototype.setMatrices = function (uniform, matrices) {
  14264. if (!uniform)
  14265. return;
  14266. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14267. };
  14268. /**
  14269. * Set the value of an uniform to a matrix
  14270. * @param uniform defines the webGL uniform location where to store the value
  14271. * @param matrix defines the matrix to store
  14272. */
  14273. Engine.prototype.setMatrix = function (uniform, matrix) {
  14274. if (!uniform)
  14275. return;
  14276. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14277. };
  14278. /**
  14279. * Set the value of an uniform to a matrix (3x3)
  14280. * @param uniform defines the webGL uniform location where to store the value
  14281. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14282. */
  14283. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a matrix (2x2)
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14292. */
  14293. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14294. if (!uniform)
  14295. return;
  14296. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14297. };
  14298. /**
  14299. * Set the value of an uniform to a number (int)
  14300. * @param uniform defines the webGL uniform location where to store the value
  14301. * @param value defines the int number to store
  14302. */
  14303. Engine.prototype.setInt = function (uniform, value) {
  14304. if (!uniform)
  14305. return;
  14306. this._gl.uniform1i(uniform, value);
  14307. };
  14308. /**
  14309. * Set the value of an uniform to a number (float)
  14310. * @param uniform defines the webGL uniform location where to store the value
  14311. * @param value defines the float number to store
  14312. */
  14313. Engine.prototype.setFloat = function (uniform, value) {
  14314. if (!uniform)
  14315. return;
  14316. this._gl.uniform1f(uniform, value);
  14317. };
  14318. /**
  14319. * Set the value of an uniform to a vec2
  14320. * @param uniform defines the webGL uniform location where to store the value
  14321. * @param x defines the 1st component of the value
  14322. * @param y defines the 2nd component of the value
  14323. */
  14324. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14325. if (!uniform)
  14326. return;
  14327. this._gl.uniform2f(uniform, x, y);
  14328. };
  14329. /**
  14330. * Set the value of an uniform to a vec3
  14331. * @param uniform defines the webGL uniform location where to store the value
  14332. * @param x defines the 1st component of the value
  14333. * @param y defines the 2nd component of the value
  14334. * @param z defines the 3rd component of the value
  14335. */
  14336. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14337. if (!uniform)
  14338. return;
  14339. this._gl.uniform3f(uniform, x, y, z);
  14340. };
  14341. /**
  14342. * Set the value of an uniform to a boolean
  14343. * @param uniform defines the webGL uniform location where to store the value
  14344. * @param bool defines the boolean to store
  14345. */
  14346. Engine.prototype.setBool = function (uniform, bool) {
  14347. if (!uniform)
  14348. return;
  14349. this._gl.uniform1i(uniform, bool);
  14350. };
  14351. /**
  14352. * Set the value of an uniform to a vec4
  14353. * @param uniform defines the webGL uniform location where to store the value
  14354. * @param x defines the 1st component of the value
  14355. * @param y defines the 2nd component of the value
  14356. * @param z defines the 3rd component of the value
  14357. * @param w defines the 4th component of the value
  14358. */
  14359. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14360. if (!uniform)
  14361. return;
  14362. this._gl.uniform4f(uniform, x, y, z, w);
  14363. };
  14364. /**
  14365. * Set the value of an uniform to a Color3
  14366. * @param uniform defines the webGL uniform location where to store the value
  14367. * @param color3 defines the color to store
  14368. */
  14369. Engine.prototype.setColor3 = function (uniform, color3) {
  14370. if (!uniform)
  14371. return;
  14372. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14373. };
  14374. /**
  14375. * Set the value of an uniform to a Color3 and an alpha value
  14376. * @param uniform defines the webGL uniform location where to store the value
  14377. * @param color3 defines the color to store
  14378. * @param alpha defines the alpha component to store
  14379. */
  14380. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14381. if (!uniform)
  14382. return;
  14383. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14384. };
  14385. /**
  14386. * Sets a Color4 on a uniform variable
  14387. * @param uniform defines the uniform location
  14388. * @param color4 defines the value to be set
  14389. */
  14390. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14391. if (!uniform)
  14392. return;
  14393. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14394. };
  14395. // States
  14396. /**
  14397. * Set various states to the webGL context
  14398. * @param culling defines backface culling state
  14399. * @param zOffset defines the value to apply to zOffset (0 by default)
  14400. * @param force defines if states must be applied even if cache is up to date
  14401. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14402. */
  14403. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14404. if (zOffset === void 0) { zOffset = 0; }
  14405. if (reverseSide === void 0) { reverseSide = false; }
  14406. // Culling
  14407. if (this._depthCullingState.cull !== culling || force) {
  14408. this._depthCullingState.cull = culling;
  14409. }
  14410. // Cull face
  14411. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14412. if (this._depthCullingState.cullFace !== cullFace || force) {
  14413. this._depthCullingState.cullFace = cullFace;
  14414. }
  14415. // Z offset
  14416. this.setZOffset(zOffset);
  14417. // Front face
  14418. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14419. if (this._depthCullingState.frontFace !== frontFace || force) {
  14420. this._depthCullingState.frontFace = frontFace;
  14421. }
  14422. };
  14423. /**
  14424. * Set the z offset to apply to current rendering
  14425. * @param value defines the offset to apply
  14426. */
  14427. Engine.prototype.setZOffset = function (value) {
  14428. this._depthCullingState.zOffset = value;
  14429. };
  14430. /**
  14431. * Gets the current value of the zOffset
  14432. * @returns the current zOffset state
  14433. */
  14434. Engine.prototype.getZOffset = function () {
  14435. return this._depthCullingState.zOffset;
  14436. };
  14437. /**
  14438. * Enable or disable depth buffering
  14439. * @param enable defines the state to set
  14440. */
  14441. Engine.prototype.setDepthBuffer = function (enable) {
  14442. this._depthCullingState.depthTest = enable;
  14443. };
  14444. /**
  14445. * Gets a boolean indicating if depth writing is enabled
  14446. * @returns the current depth writing state
  14447. */
  14448. Engine.prototype.getDepthWrite = function () {
  14449. return this._depthCullingState.depthMask;
  14450. };
  14451. /**
  14452. * Enable or disable depth writing
  14453. * @param enable defines the state to set
  14454. */
  14455. Engine.prototype.setDepthWrite = function (enable) {
  14456. this._depthCullingState.depthMask = enable;
  14457. };
  14458. /**
  14459. * Enable or disable color writing
  14460. * @param enable defines the state to set
  14461. */
  14462. Engine.prototype.setColorWrite = function (enable) {
  14463. this._gl.colorMask(enable, enable, enable, enable);
  14464. this._colorWrite = enable;
  14465. };
  14466. /**
  14467. * Gets a boolean indicating if color writing is enabled
  14468. * @returns the current color writing state
  14469. */
  14470. Engine.prototype.getColorWrite = function () {
  14471. return this._colorWrite;
  14472. };
  14473. /**
  14474. * Sets alpha constants used by some alpha blending modes
  14475. * @param r defines the red component
  14476. * @param g defines the green component
  14477. * @param b defines the blue component
  14478. * @param a defines the alpha component
  14479. */
  14480. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14481. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14482. };
  14483. /**
  14484. * Sets the current alpha mode
  14485. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14486. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14487. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14488. */
  14489. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14490. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14491. if (this._alphaMode === mode) {
  14492. return;
  14493. }
  14494. switch (mode) {
  14495. case Engine.ALPHA_DISABLE:
  14496. this._alphaState.alphaBlend = false;
  14497. break;
  14498. case Engine.ALPHA_PREMULTIPLIED:
  14499. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14500. this._alphaState.alphaBlend = true;
  14501. break;
  14502. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14503. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14504. this._alphaState.alphaBlend = true;
  14505. break;
  14506. case Engine.ALPHA_COMBINE:
  14507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14508. this._alphaState.alphaBlend = true;
  14509. break;
  14510. case Engine.ALPHA_ONEONE:
  14511. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14512. this._alphaState.alphaBlend = true;
  14513. break;
  14514. case Engine.ALPHA_ADD:
  14515. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14516. this._alphaState.alphaBlend = true;
  14517. break;
  14518. case Engine.ALPHA_SUBTRACT:
  14519. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14520. this._alphaState.alphaBlend = true;
  14521. break;
  14522. case Engine.ALPHA_MULTIPLY:
  14523. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14524. this._alphaState.alphaBlend = true;
  14525. break;
  14526. case Engine.ALPHA_MAXIMIZED:
  14527. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14528. this._alphaState.alphaBlend = true;
  14529. break;
  14530. case Engine.ALPHA_INTERPOLATE:
  14531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14532. this._alphaState.alphaBlend = true;
  14533. break;
  14534. case Engine.ALPHA_SCREENMODE:
  14535. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14536. this._alphaState.alphaBlend = true;
  14537. break;
  14538. }
  14539. if (!noDepthWriteChange) {
  14540. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14541. }
  14542. this._alphaMode = mode;
  14543. };
  14544. /**
  14545. * Gets the current alpha mode
  14546. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14547. * @returns the current alpha mode
  14548. */
  14549. Engine.prototype.getAlphaMode = function () {
  14550. return this._alphaMode;
  14551. };
  14552. // Textures
  14553. /**
  14554. * Force the entire cache to be cleared
  14555. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14556. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14557. */
  14558. Engine.prototype.wipeCaches = function (bruteForce) {
  14559. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14560. return;
  14561. }
  14562. this._currentEffect = null;
  14563. if (bruteForce) {
  14564. this.resetTextureCache();
  14565. this._currentProgram = null;
  14566. this._stencilState.reset();
  14567. this._depthCullingState.reset();
  14568. this.setDepthFunctionToLessOrEqual();
  14569. this._alphaState.reset();
  14570. }
  14571. this._resetVertexBufferBinding();
  14572. this._cachedIndexBuffer = null;
  14573. this._cachedEffectForVertexBuffers = null;
  14574. this._unbindVertexArrayObject();
  14575. this.bindIndexBuffer(null);
  14576. };
  14577. /**
  14578. * Set the compressed texture format to use, based on the formats you have, and the formats
  14579. * supported by the hardware / browser.
  14580. *
  14581. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14582. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14583. * to API arguments needed to compressed textures. This puts the burden on the container
  14584. * generator to house the arcane code for determining these for current & future formats.
  14585. *
  14586. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14587. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14588. *
  14589. * Note: The result of this call is not taken into account when a texture is base64.
  14590. *
  14591. * @param formatsAvailable defines the list of those format families you have created
  14592. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14593. *
  14594. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14595. * @returns The extension selected.
  14596. */
  14597. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14598. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14599. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14600. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14601. return this._textureFormatInUse = this._texturesSupported[i];
  14602. }
  14603. }
  14604. }
  14605. // actively set format to nothing, to allow this to be called more than once
  14606. // and possibly fail the 2nd time
  14607. this._textureFormatInUse = null;
  14608. return null;
  14609. };
  14610. /** @hidden */
  14611. Engine.prototype._createTexture = function () {
  14612. var texture = this._gl.createTexture();
  14613. if (!texture) {
  14614. throw new Error("Unable to create texture");
  14615. }
  14616. return texture;
  14617. };
  14618. /**
  14619. * Usually called from BABYLON.Texture.ts.
  14620. * Passed information to create a WebGLTexture
  14621. * @param urlArg defines a value which contains one of the following:
  14622. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14623. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14624. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14625. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14626. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14627. * @param scene needed for loading to the correct scene
  14628. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14629. * @param onLoad optional callback to be called upon successful completion
  14630. * @param onError optional callback to be called upon failure
  14631. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14632. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14633. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14634. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14635. */
  14636. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14637. var _this = this;
  14638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14639. if (onLoad === void 0) { onLoad = null; }
  14640. if (onError === void 0) { onError = null; }
  14641. if (buffer === void 0) { buffer = null; }
  14642. if (fallback === void 0) { fallback = null; }
  14643. if (format === void 0) { format = null; }
  14644. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14645. var fromData = url.substr(0, 5) === "data:";
  14646. var fromBlob = url.substr(0, 5) === "blob:";
  14647. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14648. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14649. // establish the file extension, if possible
  14650. var lastDot = url.lastIndexOf('.');
  14651. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14652. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14653. var isTGA = (extension.indexOf(".tga") === 0);
  14654. // determine if a ktx file should be substituted
  14655. var isKTX = false;
  14656. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14657. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14658. isKTX = true;
  14659. }
  14660. if (scene) {
  14661. scene._addPendingData(texture);
  14662. }
  14663. texture.url = url;
  14664. texture.generateMipMaps = !noMipmap;
  14665. texture.samplingMode = samplingMode;
  14666. texture.invertY = invertY;
  14667. if (!this._doNotHandleContextLost) {
  14668. // Keep a link to the buffer only if we plan to handle context lost
  14669. texture._buffer = buffer;
  14670. }
  14671. var onLoadObserver = null;
  14672. if (onLoad && !fallback) {
  14673. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14674. }
  14675. if (!fallback)
  14676. this._internalTexturesCache.push(texture);
  14677. var onerror = function (message, exception) {
  14678. if (scene) {
  14679. scene._removePendingData(texture);
  14680. }
  14681. if (onLoadObserver) {
  14682. texture.onLoadedObservable.remove(onLoadObserver);
  14683. }
  14684. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14685. if (isKTX) {
  14686. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14687. }
  14688. else if (BABYLON.Tools.UseFallbackTexture) {
  14689. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14690. }
  14691. if (onError) {
  14692. onError(message || "Unknown error", exception);
  14693. }
  14694. };
  14695. var callback = null;
  14696. // processing for non-image formats
  14697. if (isKTX || isTGA || isDDS) {
  14698. if (isKTX) {
  14699. callback = function (data) {
  14700. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14701. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14702. ktx.uploadLevels(_this._gl, !noMipmap);
  14703. return false;
  14704. }, samplingMode);
  14705. };
  14706. }
  14707. else if (isTGA) {
  14708. callback = function (arrayBuffer) {
  14709. var data = new Uint8Array(arrayBuffer);
  14710. var header = BABYLON.TGATools.GetTGAHeader(data);
  14711. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14712. BABYLON.TGATools.UploadContent(_this._gl, data);
  14713. return false;
  14714. }, samplingMode);
  14715. };
  14716. }
  14717. else if (isDDS) {
  14718. callback = function (data) {
  14719. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14720. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14721. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14722. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14723. return false;
  14724. }, samplingMode);
  14725. };
  14726. }
  14727. if (!buffer) {
  14728. this._loadFile(url, function (data) {
  14729. if (callback) {
  14730. callback(data);
  14731. }
  14732. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14733. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14734. });
  14735. }
  14736. else {
  14737. if (callback) {
  14738. callback(buffer);
  14739. }
  14740. }
  14741. // image format processing
  14742. }
  14743. else {
  14744. var onload = function (img) {
  14745. if (fromBlob && !_this._doNotHandleContextLost) {
  14746. // We need to store the image if we need to rebuild the texture
  14747. // in case of a webgl context lost
  14748. texture._buffer = img;
  14749. }
  14750. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14751. var gl = _this._gl;
  14752. var isPot = (img.width === potWidth && img.height === potHeight);
  14753. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14754. if (isPot) {
  14755. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14756. return false;
  14757. }
  14758. // Using shaders to rescale because canvas.drawImage is lossy
  14759. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14760. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14761. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14766. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14767. _this._releaseTexture(source);
  14768. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14769. continuationCallback();
  14770. });
  14771. return true;
  14772. }, samplingMode);
  14773. };
  14774. if (!fromData || isBase64) {
  14775. if (buffer instanceof HTMLImageElement) {
  14776. onload(buffer);
  14777. }
  14778. else {
  14779. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14780. }
  14781. }
  14782. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14783. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14784. }
  14785. else {
  14786. onload(buffer);
  14787. }
  14788. }
  14789. return texture;
  14790. };
  14791. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14792. var _this = this;
  14793. var rtt = this.createRenderTargetTexture({
  14794. width: destination.width,
  14795. height: destination.height,
  14796. }, {
  14797. generateMipMaps: false,
  14798. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14799. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14800. generateDepthBuffer: false,
  14801. generateStencilBuffer: false
  14802. });
  14803. if (!this._rescalePostProcess) {
  14804. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14805. }
  14806. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14807. _this._rescalePostProcess.onApply = function (effect) {
  14808. effect._bindTexture("textureSampler", source);
  14809. };
  14810. var hostingScene = scene;
  14811. if (!hostingScene) {
  14812. hostingScene = _this.scenes[_this.scenes.length - 1];
  14813. }
  14814. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14815. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14816. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14817. _this.unBindFramebuffer(rtt);
  14818. _this._releaseTexture(rtt);
  14819. if (onComplete) {
  14820. onComplete();
  14821. }
  14822. });
  14823. };
  14824. /**
  14825. * Update a raw texture
  14826. * @param texture defines the texture to update
  14827. * @param data defines the data to store in the texture
  14828. * @param format defines the format of the data
  14829. * @param invertY defines if data must be stored with Y axis inverted
  14830. * @param compression defines the compression used (null by default)
  14831. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14832. */
  14833. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14834. if (compression === void 0) { compression = null; }
  14835. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14836. if (!texture) {
  14837. return;
  14838. }
  14839. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14840. var internalFormat = this._getInternalFormat(format);
  14841. var textureType = this._getWebGLTextureType(type);
  14842. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14843. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14844. if (!this._doNotHandleContextLost) {
  14845. texture._bufferView = data;
  14846. texture.format = format;
  14847. texture.type = type;
  14848. texture.invertY = invertY;
  14849. texture._compression = compression;
  14850. }
  14851. if (texture.width % 4 !== 0) {
  14852. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14853. }
  14854. if (compression && data) {
  14855. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14856. }
  14857. else {
  14858. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14859. }
  14860. if (texture.generateMipMaps) {
  14861. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14862. }
  14863. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14864. // this.resetTextureCache();
  14865. texture.isReady = true;
  14866. };
  14867. /**
  14868. * Creates a raw texture
  14869. * @param data defines the data to store in the texture
  14870. * @param width defines the width of the texture
  14871. * @param height defines the height of the texture
  14872. * @param format defines the format of the data
  14873. * @param generateMipMaps defines if the engine should generate the mip levels
  14874. * @param invertY defines if data must be stored with Y axis inverted
  14875. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14876. * @param compression defines the compression used (null by default)
  14877. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14878. * @returns the raw texture inside an InternalTexture
  14879. */
  14880. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14881. if (compression === void 0) { compression = null; }
  14882. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14883. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14884. texture.baseWidth = width;
  14885. texture.baseHeight = height;
  14886. texture.width = width;
  14887. texture.height = height;
  14888. texture.format = format;
  14889. texture.generateMipMaps = generateMipMaps;
  14890. texture.samplingMode = samplingMode;
  14891. texture.invertY = invertY;
  14892. texture._compression = compression;
  14893. texture.type = type;
  14894. if (!this._doNotHandleContextLost) {
  14895. texture._bufferView = data;
  14896. }
  14897. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14898. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14899. // Filters
  14900. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14901. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14902. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14903. if (generateMipMaps) {
  14904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14905. }
  14906. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14907. this._internalTexturesCache.push(texture);
  14908. return texture;
  14909. };
  14910. /**
  14911. * Creates a dynamic texture
  14912. * @param width defines the width of the texture
  14913. * @param height defines the height of the texture
  14914. * @param generateMipMaps defines if the engine should generate the mip levels
  14915. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14916. * @returns the dynamic texture inside an InternalTexture
  14917. */
  14918. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14919. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14920. texture.baseWidth = width;
  14921. texture.baseHeight = height;
  14922. if (generateMipMaps) {
  14923. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14924. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14925. }
  14926. // this.resetTextureCache();
  14927. texture.width = width;
  14928. texture.height = height;
  14929. texture.isReady = false;
  14930. texture.generateMipMaps = generateMipMaps;
  14931. texture.samplingMode = samplingMode;
  14932. this.updateTextureSamplingMode(samplingMode, texture);
  14933. this._internalTexturesCache.push(texture);
  14934. return texture;
  14935. };
  14936. /**
  14937. * Update the sampling mode of a given texture
  14938. * @param samplingMode defines the required sampling mode
  14939. * @param texture defines the texture to update
  14940. */
  14941. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14942. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14943. if (texture.isCube) {
  14944. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14945. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14946. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14947. }
  14948. else if (texture.is3D) {
  14949. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14950. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14951. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14952. }
  14953. else {
  14954. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14955. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14956. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14957. }
  14958. texture.samplingMode = samplingMode;
  14959. };
  14960. /**
  14961. * Update the content of a dynamic texture
  14962. * @param texture defines the texture to update
  14963. * @param canvas defines the canvas containing the source
  14964. * @param invertY defines if data must be stored with Y axis inverted
  14965. * @param premulAlpha defines if alpha is stored as premultiplied
  14966. * @param format defines the format of the data
  14967. */
  14968. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14969. if (premulAlpha === void 0) { premulAlpha = false; }
  14970. if (!texture) {
  14971. return;
  14972. }
  14973. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14974. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14975. if (premulAlpha) {
  14976. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14977. }
  14978. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14979. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14980. if (texture.generateMipMaps) {
  14981. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14982. }
  14983. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14984. if (premulAlpha) {
  14985. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14986. }
  14987. texture.isReady = true;
  14988. };
  14989. /**
  14990. * Update a video texture
  14991. * @param texture defines the texture to update
  14992. * @param video defines the video element to use
  14993. * @param invertY defines if data must be stored with Y axis inverted
  14994. */
  14995. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14996. if (!texture || texture._isDisabled) {
  14997. return;
  14998. }
  14999. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15000. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  15001. try {
  15002. // Testing video texture support
  15003. if (this._videoTextureSupported === undefined) {
  15004. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15005. if (this._gl.getError() !== 0) {
  15006. this._videoTextureSupported = false;
  15007. }
  15008. else {
  15009. this._videoTextureSupported = true;
  15010. }
  15011. }
  15012. // Copy video through the current working canvas if video texture is not supported
  15013. if (!this._videoTextureSupported) {
  15014. if (!texture._workingCanvas) {
  15015. texture._workingCanvas = document.createElement("canvas");
  15016. var context = texture._workingCanvas.getContext("2d");
  15017. if (!context) {
  15018. throw new Error("Unable to get 2d context");
  15019. }
  15020. texture._workingContext = context;
  15021. texture._workingCanvas.width = texture.width;
  15022. texture._workingCanvas.height = texture.height;
  15023. }
  15024. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15025. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15026. }
  15027. else {
  15028. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15029. }
  15030. if (texture.generateMipMaps) {
  15031. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15032. }
  15033. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15034. // this.resetTextureCache();
  15035. texture.isReady = true;
  15036. }
  15037. catch (ex) {
  15038. // Something unexpected
  15039. // Let's disable the texture
  15040. texture._isDisabled = true;
  15041. }
  15042. };
  15043. /**
  15044. * Updates a depth texture Comparison Mode and Function.
  15045. * If the comparison Function is equal to 0, the mode will be set to none.
  15046. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15047. * @param texture The texture to set the comparison function for
  15048. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15049. */
  15050. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15051. if (this.webGLVersion === 1) {
  15052. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15053. return;
  15054. }
  15055. var gl = this._gl;
  15056. if (texture.isCube) {
  15057. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15058. if (comparisonFunction === 0) {
  15059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15061. }
  15062. else {
  15063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15065. }
  15066. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15067. }
  15068. else {
  15069. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15070. if (comparisonFunction === 0) {
  15071. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15072. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15073. }
  15074. else {
  15075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15077. }
  15078. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15079. }
  15080. texture._comparisonFunction = comparisonFunction;
  15081. };
  15082. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15083. var width = size.width || size;
  15084. var height = size.height || size;
  15085. internalTexture.baseWidth = width;
  15086. internalTexture.baseHeight = height;
  15087. internalTexture.width = width;
  15088. internalTexture.height = height;
  15089. internalTexture.isReady = true;
  15090. internalTexture.samples = 1;
  15091. internalTexture.generateMipMaps = false;
  15092. internalTexture._generateDepthBuffer = true;
  15093. internalTexture._generateStencilBuffer = generateStencil;
  15094. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15095. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15096. internalTexture._comparisonFunction = comparisonFunction;
  15097. var gl = this._gl;
  15098. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15099. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15100. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15101. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15102. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15103. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15104. if (comparisonFunction === 0) {
  15105. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15106. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15107. }
  15108. else {
  15109. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15110. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15111. }
  15112. };
  15113. /**
  15114. * Creates a depth stencil texture.
  15115. * This is only available in WebGL 2 or with the depth texture extension available.
  15116. * @param size The size of face edge in the texture.
  15117. * @param options The options defining the texture.
  15118. * @returns The texture
  15119. */
  15120. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15121. if (options.isCube) {
  15122. var width = size.width || size;
  15123. return this._createDepthStencilCubeTexture(width, options);
  15124. }
  15125. else {
  15126. return this._createDepthStencilTexture(size, options);
  15127. }
  15128. };
  15129. /**
  15130. * Creates a depth stencil texture.
  15131. * This is only available in WebGL 2 or with the depth texture extension available.
  15132. * @param size The size of face edge in the texture.
  15133. * @param options The options defining the texture.
  15134. * @returns The texture
  15135. */
  15136. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15137. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15138. if (!this._caps.depthTextureExtension) {
  15139. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15140. return internalTexture;
  15141. }
  15142. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15143. var gl = this._gl;
  15144. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15145. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15146. if (this.webGLVersion > 1) {
  15147. if (internalOptions.generateStencil) {
  15148. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15149. }
  15150. else {
  15151. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15152. }
  15153. }
  15154. else {
  15155. if (internalOptions.generateStencil) {
  15156. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15157. }
  15158. else {
  15159. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15160. }
  15161. }
  15162. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15163. return internalTexture;
  15164. };
  15165. /**
  15166. * Creates a depth stencil cube texture.
  15167. * This is only available in WebGL 2.
  15168. * @param size The size of face edge in the cube texture.
  15169. * @param options The options defining the cube texture.
  15170. * @returns The cube texture
  15171. */
  15172. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15173. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15174. internalTexture.isCube = true;
  15175. if (this.webGLVersion === 1) {
  15176. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15177. return internalTexture;
  15178. }
  15179. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15180. var gl = this._gl;
  15181. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15182. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15183. // Create the depth/stencil buffer
  15184. for (var face = 0; face < 6; face++) {
  15185. if (internalOptions.generateStencil) {
  15186. 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);
  15187. }
  15188. else {
  15189. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15190. }
  15191. }
  15192. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15193. return internalTexture;
  15194. };
  15195. /**
  15196. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15197. * @param renderTarget The render target to set the frame buffer for
  15198. */
  15199. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15200. // Create the framebuffer
  15201. var internalTexture = renderTarget.getInternalTexture();
  15202. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15203. return;
  15204. }
  15205. var gl = this._gl;
  15206. var depthStencilTexture = renderTarget.depthStencilTexture;
  15207. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15208. if (depthStencilTexture.isCube) {
  15209. if (depthStencilTexture._generateStencilBuffer) {
  15210. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15211. }
  15212. else {
  15213. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15214. }
  15215. }
  15216. else {
  15217. if (depthStencilTexture._generateStencilBuffer) {
  15218. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15219. }
  15220. else {
  15221. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15222. }
  15223. }
  15224. this.bindUnboundFramebuffer(null);
  15225. };
  15226. /**
  15227. * Creates a new render target texture
  15228. * @param size defines the size of the texture
  15229. * @param options defines the options used to create the texture
  15230. * @returns a new render target texture stored in an InternalTexture
  15231. */
  15232. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15233. var fullOptions = new RenderTargetCreationOptions();
  15234. if (options !== undefined && typeof options === "object") {
  15235. fullOptions.generateMipMaps = options.generateMipMaps;
  15236. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15237. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15238. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15239. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15240. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15241. }
  15242. else {
  15243. fullOptions.generateMipMaps = options;
  15244. fullOptions.generateDepthBuffer = true;
  15245. fullOptions.generateStencilBuffer = false;
  15246. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15247. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15248. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15249. }
  15250. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15251. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15252. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15253. }
  15254. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15255. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15256. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15257. }
  15258. var gl = this._gl;
  15259. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15260. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15261. var width = size.width || size;
  15262. var height = size.height || size;
  15263. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15264. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15265. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15266. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15267. }
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15272. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15273. // Create the framebuffer
  15274. var currentFrameBuffer = this._currentFramebuffer;
  15275. var framebuffer = gl.createFramebuffer();
  15276. this.bindUnboundFramebuffer(framebuffer);
  15277. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15278. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15279. if (fullOptions.generateMipMaps) {
  15280. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15281. }
  15282. // Unbind
  15283. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15284. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15285. this.bindUnboundFramebuffer(currentFrameBuffer);
  15286. texture._framebuffer = framebuffer;
  15287. texture.baseWidth = width;
  15288. texture.baseHeight = height;
  15289. texture.width = width;
  15290. texture.height = height;
  15291. texture.isReady = true;
  15292. texture.samples = 1;
  15293. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15294. texture.samplingMode = fullOptions.samplingMode;
  15295. texture.type = fullOptions.type;
  15296. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15297. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15298. // this.resetTextureCache();
  15299. this._internalTexturesCache.push(texture);
  15300. return texture;
  15301. };
  15302. /**
  15303. * Create a multi render target texture
  15304. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15305. * @param size defines the size of the texture
  15306. * @param options defines the creation options
  15307. * @returns the cube texture as an InternalTexture
  15308. */
  15309. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15310. var generateMipMaps = false;
  15311. var generateDepthBuffer = true;
  15312. var generateStencilBuffer = false;
  15313. var generateDepthTexture = false;
  15314. var textureCount = 1;
  15315. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15316. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15317. var types = new Array();
  15318. var samplingModes = new Array();
  15319. if (options !== undefined) {
  15320. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15321. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15322. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15323. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15324. textureCount = options.textureCount || 1;
  15325. if (options.types) {
  15326. types = options.types;
  15327. }
  15328. if (options.samplingModes) {
  15329. samplingModes = options.samplingModes;
  15330. }
  15331. }
  15332. var gl = this._gl;
  15333. // Create the framebuffer
  15334. var framebuffer = gl.createFramebuffer();
  15335. this.bindUnboundFramebuffer(framebuffer);
  15336. var width = size.width || size;
  15337. var height = size.height || size;
  15338. var textures = [];
  15339. var attachments = [];
  15340. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15341. for (var i = 0; i < textureCount; i++) {
  15342. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15343. var type = types[i] || defaultType;
  15344. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15345. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15346. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15347. }
  15348. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15349. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15350. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15351. }
  15352. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15353. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15354. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15355. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15356. }
  15357. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15358. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15359. textures.push(texture);
  15360. attachments.push(attachment);
  15361. gl.activeTexture(gl["TEXTURE" + i]);
  15362. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15367. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15368. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15369. if (generateMipMaps) {
  15370. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15371. }
  15372. // Unbind
  15373. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15374. texture._framebuffer = framebuffer;
  15375. texture._depthStencilBuffer = depthStencilBuffer;
  15376. texture.baseWidth = width;
  15377. texture.baseHeight = height;
  15378. texture.width = width;
  15379. texture.height = height;
  15380. texture.isReady = true;
  15381. texture.samples = 1;
  15382. texture.generateMipMaps = generateMipMaps;
  15383. texture.samplingMode = samplingMode;
  15384. texture.type = type;
  15385. texture._generateDepthBuffer = generateDepthBuffer;
  15386. texture._generateStencilBuffer = generateStencilBuffer;
  15387. texture._attachments = attachments;
  15388. this._internalTexturesCache.push(texture);
  15389. }
  15390. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15391. // Depth texture
  15392. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15393. gl.activeTexture(gl.TEXTURE0);
  15394. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15395. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15399. 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);
  15400. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15401. depthTexture._framebuffer = framebuffer;
  15402. depthTexture.baseWidth = width;
  15403. depthTexture.baseHeight = height;
  15404. depthTexture.width = width;
  15405. depthTexture.height = height;
  15406. depthTexture.isReady = true;
  15407. depthTexture.samples = 1;
  15408. depthTexture.generateMipMaps = generateMipMaps;
  15409. depthTexture.samplingMode = gl.NEAREST;
  15410. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15411. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15412. textures.push(depthTexture);
  15413. this._internalTexturesCache.push(depthTexture);
  15414. }
  15415. gl.drawBuffers(attachments);
  15416. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15417. this.bindUnboundFramebuffer(null);
  15418. this.resetTextureCache();
  15419. return textures;
  15420. };
  15421. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15422. if (samples === void 0) { samples = 1; }
  15423. var depthStencilBuffer = null;
  15424. var gl = this._gl;
  15425. // Create the depth/stencil buffer
  15426. if (generateStencilBuffer) {
  15427. depthStencilBuffer = gl.createRenderbuffer();
  15428. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15429. if (samples > 1) {
  15430. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15431. }
  15432. else {
  15433. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15434. }
  15435. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15436. }
  15437. else if (generateDepthBuffer) {
  15438. depthStencilBuffer = gl.createRenderbuffer();
  15439. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15440. if (samples > 1) {
  15441. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15442. }
  15443. else {
  15444. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15445. }
  15446. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15447. }
  15448. return depthStencilBuffer;
  15449. };
  15450. /**
  15451. * Updates the sample count of a render target texture
  15452. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15453. * @param texture defines the texture to update
  15454. * @param samples defines the sample count to set
  15455. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15456. */
  15457. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15458. if (this.webGLVersion < 2 || !texture) {
  15459. return 1;
  15460. }
  15461. if (texture.samples === samples) {
  15462. return samples;
  15463. }
  15464. var gl = this._gl;
  15465. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15466. // Dispose previous render buffers
  15467. if (texture._depthStencilBuffer) {
  15468. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15469. texture._depthStencilBuffer = null;
  15470. }
  15471. if (texture._MSAAFramebuffer) {
  15472. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15473. texture._MSAAFramebuffer = null;
  15474. }
  15475. if (texture._MSAARenderBuffer) {
  15476. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15477. texture._MSAARenderBuffer = null;
  15478. }
  15479. if (samples > 1) {
  15480. var framebuffer = gl.createFramebuffer();
  15481. if (!framebuffer) {
  15482. throw new Error("Unable to create multi sampled framebuffer");
  15483. }
  15484. texture._MSAAFramebuffer = framebuffer;
  15485. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15486. var colorRenderbuffer = gl.createRenderbuffer();
  15487. if (!colorRenderbuffer) {
  15488. throw new Error("Unable to create multi sampled framebuffer");
  15489. }
  15490. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15491. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15492. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15493. texture._MSAARenderBuffer = colorRenderbuffer;
  15494. }
  15495. else {
  15496. this.bindUnboundFramebuffer(texture._framebuffer);
  15497. }
  15498. texture.samples = samples;
  15499. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15500. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15501. this.bindUnboundFramebuffer(null);
  15502. return samples;
  15503. };
  15504. /**
  15505. * Update the sample count for a given multiple render target texture
  15506. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15507. * @param textures defines the textures to update
  15508. * @param samples defines the sample count to set
  15509. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15510. */
  15511. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15512. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15513. return 1;
  15514. }
  15515. if (textures[0].samples === samples) {
  15516. return samples;
  15517. }
  15518. var gl = this._gl;
  15519. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15520. // Dispose previous render buffers
  15521. if (textures[0]._depthStencilBuffer) {
  15522. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15523. textures[0]._depthStencilBuffer = null;
  15524. }
  15525. if (textures[0]._MSAAFramebuffer) {
  15526. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15527. textures[0]._MSAAFramebuffer = null;
  15528. }
  15529. for (var i = 0; i < textures.length; i++) {
  15530. if (textures[i]._MSAARenderBuffer) {
  15531. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15532. textures[i]._MSAARenderBuffer = null;
  15533. }
  15534. }
  15535. if (samples > 1) {
  15536. var framebuffer = gl.createFramebuffer();
  15537. if (!framebuffer) {
  15538. throw new Error("Unable to create multi sampled framebuffer");
  15539. }
  15540. this.bindUnboundFramebuffer(framebuffer);
  15541. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15542. var attachments = [];
  15543. for (var i = 0; i < textures.length; i++) {
  15544. var texture = textures[i];
  15545. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15546. var colorRenderbuffer = gl.createRenderbuffer();
  15547. if (!colorRenderbuffer) {
  15548. throw new Error("Unable to create multi sampled framebuffer");
  15549. }
  15550. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15551. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15552. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15553. texture._MSAAFramebuffer = framebuffer;
  15554. texture._MSAARenderBuffer = colorRenderbuffer;
  15555. texture.samples = samples;
  15556. texture._depthStencilBuffer = depthStencilBuffer;
  15557. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15558. attachments.push(attachment);
  15559. }
  15560. gl.drawBuffers(attachments);
  15561. }
  15562. else {
  15563. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15564. }
  15565. this.bindUnboundFramebuffer(null);
  15566. return samples;
  15567. };
  15568. /** @hidden */
  15569. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15570. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15571. };
  15572. /** @hidden */
  15573. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15574. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15575. };
  15576. /**
  15577. * Creates a new render target cube texture
  15578. * @param size defines the size of the texture
  15579. * @param options defines the options used to create the texture
  15580. * @returns a new render target cube texture stored in an InternalTexture
  15581. */
  15582. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15583. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15584. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15585. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15586. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15587. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15588. }
  15589. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15590. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15591. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15592. }
  15593. var gl = this._gl;
  15594. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15595. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15596. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15597. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15598. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15599. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15600. }
  15601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15604. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15605. for (var face = 0; face < 6; face++) {
  15606. 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);
  15607. }
  15608. // Create the framebuffer
  15609. var framebuffer = gl.createFramebuffer();
  15610. this.bindUnboundFramebuffer(framebuffer);
  15611. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15612. // MipMaps
  15613. if (fullOptions.generateMipMaps) {
  15614. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15615. }
  15616. // Unbind
  15617. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15618. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15619. this.bindUnboundFramebuffer(null);
  15620. texture._framebuffer = framebuffer;
  15621. texture.width = size;
  15622. texture.height = size;
  15623. texture.isReady = true;
  15624. texture.isCube = true;
  15625. texture.samples = 1;
  15626. texture.generateMipMaps = fullOptions.generateMipMaps;
  15627. texture.samplingMode = fullOptions.samplingMode;
  15628. texture.type = fullOptions.type;
  15629. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15630. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15631. this._internalTexturesCache.push(texture);
  15632. return texture;
  15633. };
  15634. /**
  15635. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15636. * @param rootUrl defines the url where the file to load is located
  15637. * @param scene defines the current scene
  15638. * @param scale defines scale to apply to the mip map selection
  15639. * @param offset defines offset to apply to the mip map selection
  15640. * @param onLoad defines an optional callback raised when the texture is loaded
  15641. * @param onError defines an optional callback raised if there is an issue to load the texture
  15642. * @param format defines the format of the data
  15643. * @param forcedExtension defines the extension to use to pick the right loader
  15644. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15645. * @returns the cube texture as an InternalTexture
  15646. */
  15647. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15648. var _this = this;
  15649. if (onLoad === void 0) { onLoad = null; }
  15650. if (onError === void 0) { onError = null; }
  15651. if (forcedExtension === void 0) { forcedExtension = null; }
  15652. if (createPolynomials === void 0) { createPolynomials = true; }
  15653. var callback = function (loadData) {
  15654. if (!loadData) {
  15655. if (onLoad) {
  15656. onLoad(null);
  15657. }
  15658. return;
  15659. }
  15660. var texture = loadData.texture;
  15661. if (!createPolynomials) {
  15662. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15663. }
  15664. else if (loadData.info.sphericalPolynomial) {
  15665. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15666. }
  15667. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15668. texture._lodGenerationScale = scale;
  15669. texture._lodGenerationOffset = offset;
  15670. if (_this._caps.textureLOD) {
  15671. // Do not add extra process if texture lod is supported.
  15672. if (onLoad) {
  15673. onLoad(texture);
  15674. }
  15675. return;
  15676. }
  15677. var mipSlices = 3;
  15678. var gl = _this._gl;
  15679. var width = loadData.width;
  15680. if (!width) {
  15681. return;
  15682. }
  15683. var textures = [];
  15684. for (var i = 0; i < mipSlices; i++) {
  15685. //compute LOD from even spacing in smoothness (matching shader calculation)
  15686. var smoothness = i / (mipSlices - 1);
  15687. var roughness = 1 - smoothness;
  15688. var minLODIndex = offset; // roughness = 0
  15689. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15690. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15691. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15692. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15693. glTextureFromLod.isCube = true;
  15694. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15699. if (loadData.isDDS) {
  15700. var info = loadData.info;
  15701. var data = loadData.data;
  15702. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15703. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15704. }
  15705. else {
  15706. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15707. }
  15708. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15709. // Wrap in a base texture for easy binding.
  15710. var lodTexture = new BABYLON.BaseTexture(scene);
  15711. lodTexture.isCube = true;
  15712. lodTexture._texture = glTextureFromLod;
  15713. glTextureFromLod.isReady = true;
  15714. textures.push(lodTexture);
  15715. }
  15716. texture._lodTextureHigh = textures[2];
  15717. texture._lodTextureMid = textures[1];
  15718. texture._lodTextureLow = textures[0];
  15719. if (onLoad) {
  15720. onLoad(texture);
  15721. }
  15722. };
  15723. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15724. };
  15725. /**
  15726. * Creates a cube texture
  15727. * @param rootUrl defines the url where the files to load is located
  15728. * @param scene defines the current scene
  15729. * @param files defines the list of files to load (1 per face)
  15730. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15731. * @param onLoad defines an optional callback raised when the texture is loaded
  15732. * @param onError defines an optional callback raised if there is an issue to load the texture
  15733. * @param format defines the format of the data
  15734. * @param forcedExtension defines the extension to use to pick the right loader
  15735. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15736. * @returns the cube texture as an InternalTexture
  15737. */
  15738. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15739. var _this = this;
  15740. if (onLoad === void 0) { onLoad = null; }
  15741. if (onError === void 0) { onError = null; }
  15742. if (forcedExtension === void 0) { forcedExtension = null; }
  15743. if (createPolynomials === void 0) { createPolynomials = false; }
  15744. var gl = this._gl;
  15745. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15746. texture.isCube = true;
  15747. texture.url = rootUrl;
  15748. texture.generateMipMaps = !noMipmap;
  15749. if (!this._doNotHandleContextLost) {
  15750. texture._extension = forcedExtension;
  15751. texture._files = files;
  15752. }
  15753. var isKTX = false;
  15754. var isDDS = false;
  15755. var lastDot = rootUrl.lastIndexOf('.');
  15756. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15757. if (this._textureFormatInUse) {
  15758. extension = this._textureFormatInUse;
  15759. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15760. isKTX = true;
  15761. }
  15762. else {
  15763. isDDS = (extension === ".dds");
  15764. }
  15765. var onerror = function (request, exception) {
  15766. if (onError && request) {
  15767. onError(request.status + " " + request.statusText, exception);
  15768. }
  15769. };
  15770. if (isKTX) {
  15771. this._loadFile(rootUrl, function (data) {
  15772. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15773. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15774. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15775. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15776. ktx.uploadLevels(_this._gl, !noMipmap);
  15777. _this.setCubeMapTextureParams(gl, loadMipmap);
  15778. texture.width = ktx.pixelWidth;
  15779. texture.height = ktx.pixelHeight;
  15780. texture.isReady = true;
  15781. }, undefined, undefined, true, onerror);
  15782. }
  15783. else if (isDDS) {
  15784. if (files && files.length === 6) {
  15785. this._cascadeLoadFiles(scene, function (imgs) {
  15786. var info;
  15787. var loadMipmap = false;
  15788. var width = 0;
  15789. for (var index = 0; index < imgs.length; index++) {
  15790. var data = imgs[index];
  15791. info = BABYLON.DDSTools.GetDDSInfo(data);
  15792. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15793. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15794. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15795. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15796. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15797. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15798. }
  15799. texture.width = info.width;
  15800. texture.height = info.height;
  15801. texture.type = info.textureType;
  15802. width = info.width;
  15803. }
  15804. _this.setCubeMapTextureParams(gl, loadMipmap);
  15805. texture.isReady = true;
  15806. if (onLoad) {
  15807. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15808. }
  15809. }, files, onError);
  15810. }
  15811. else {
  15812. this._loadFile(rootUrl, function (data) {
  15813. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15814. if (createPolynomials) {
  15815. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15816. }
  15817. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15818. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15819. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15820. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15821. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15822. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15823. }
  15824. _this.setCubeMapTextureParams(gl, loadMipmap);
  15825. texture.width = info.width;
  15826. texture.height = info.height;
  15827. texture.isReady = true;
  15828. texture.type = info.textureType;
  15829. if (onLoad) {
  15830. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15831. }
  15832. }, undefined, undefined, true, onerror);
  15833. }
  15834. }
  15835. else {
  15836. if (!files) {
  15837. throw new Error("Cannot load cubemap because files were not defined");
  15838. }
  15839. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15840. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15841. var height = width;
  15842. _this._prepareWorkingCanvas();
  15843. if (!_this._workingCanvas || !_this._workingContext) {
  15844. return;
  15845. }
  15846. _this._workingCanvas.width = width;
  15847. _this._workingCanvas.height = height;
  15848. var faces = [
  15849. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15850. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15851. ];
  15852. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15853. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15854. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15855. for (var index = 0; index < faces.length; index++) {
  15856. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15857. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15858. }
  15859. if (!noMipmap) {
  15860. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15861. }
  15862. _this.setCubeMapTextureParams(gl, !noMipmap);
  15863. texture.width = width;
  15864. texture.height = height;
  15865. texture.isReady = true;
  15866. if (format) {
  15867. texture.format = format;
  15868. }
  15869. texture.onLoadedObservable.notifyObservers(texture);
  15870. texture.onLoadedObservable.clear();
  15871. if (onLoad) {
  15872. onLoad();
  15873. }
  15874. }, files, onError);
  15875. }
  15876. this._internalTexturesCache.push(texture);
  15877. return texture;
  15878. };
  15879. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15884. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15885. // this.resetTextureCache();
  15886. };
  15887. /**
  15888. * Update a raw cube texture
  15889. * @param texture defines the texture to udpdate
  15890. * @param data defines the data to store
  15891. * @param format defines the data format
  15892. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15893. * @param invertY defines if data must be stored with Y axis inverted
  15894. * @param compression defines the compression used (null by default)
  15895. * @param level defines which level of the texture to update
  15896. */
  15897. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15898. if (compression === void 0) { compression = null; }
  15899. if (level === void 0) { level = 0; }
  15900. texture._bufferViewArray = data;
  15901. texture.format = format;
  15902. texture.type = type;
  15903. texture.invertY = invertY;
  15904. texture._compression = compression;
  15905. var gl = this._gl;
  15906. var textureType = this._getWebGLTextureType(type);
  15907. var internalFormat = this._getInternalFormat(format);
  15908. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15909. var needConversion = false;
  15910. if (internalFormat === gl.RGB) {
  15911. internalFormat = gl.RGBA;
  15912. needConversion = true;
  15913. }
  15914. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15915. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15916. if (texture.width % 4 !== 0) {
  15917. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15918. }
  15919. // Data are known to be in +X +Y +Z -X -Y -Z
  15920. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15921. var faceData = data[faceIndex];
  15922. if (compression) {
  15923. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15924. }
  15925. else {
  15926. if (needConversion) {
  15927. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15928. }
  15929. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15930. }
  15931. }
  15932. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15933. if (isPot && texture.generateMipMaps && level === 0) {
  15934. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15935. }
  15936. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15937. // this.resetTextureCache();
  15938. texture.isReady = true;
  15939. };
  15940. /**
  15941. * Creates a new raw cube texture
  15942. * @param data defines the array of data to use to create each face
  15943. * @param size defines the size of the textures
  15944. * @param format defines the format of the data
  15945. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15946. * @param generateMipMaps defines if the engine should generate the mip levels
  15947. * @param invertY defines if data must be stored with Y axis inverted
  15948. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15949. * @param compression defines the compression used (null by default)
  15950. * @returns the cube texture as an InternalTexture
  15951. */
  15952. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15953. if (compression === void 0) { compression = null; }
  15954. var gl = this._gl;
  15955. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15956. texture.isCube = true;
  15957. texture.generateMipMaps = generateMipMaps;
  15958. texture.format = format;
  15959. texture.type = type;
  15960. if (!this._doNotHandleContextLost) {
  15961. texture._bufferViewArray = data;
  15962. }
  15963. var textureType = this._getWebGLTextureType(type);
  15964. var internalFormat = this._getInternalFormat(format);
  15965. if (internalFormat === gl.RGB) {
  15966. internalFormat = gl.RGBA;
  15967. }
  15968. var width = size;
  15969. var height = width;
  15970. texture.width = width;
  15971. texture.height = height;
  15972. // Double check on POT to generate Mips.
  15973. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15974. if (!isPot) {
  15975. generateMipMaps = false;
  15976. }
  15977. // Upload data if needed. The texture won't be ready until then.
  15978. if (data) {
  15979. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15980. }
  15981. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15982. // Filters
  15983. if (data && generateMipMaps) {
  15984. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15985. }
  15986. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15989. }
  15990. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15991. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15992. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15993. }
  15994. else {
  15995. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15998. }
  15999. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16001. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16002. return texture;
  16003. };
  16004. /**
  16005. * Creates a new raw cube texture from a specified url
  16006. * @param url defines the url where the data is located
  16007. * @param scene defines the current scene
  16008. * @param size defines the size of the textures
  16009. * @param format defines the format of the data
  16010. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16011. * @param noMipmap defines if the engine should avoid generating the mip levels
  16012. * @param callback defines a callback used to extract texture data from loaded data
  16013. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16014. * @param onLoad defines a callback called when texture is loaded
  16015. * @param onError defines a callback called if there is an error
  16016. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16017. * @param invertY defines if data must be stored with Y axis inverted
  16018. * @returns the cube texture as an InternalTexture
  16019. */
  16020. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16021. var _this = this;
  16022. if (onLoad === void 0) { onLoad = null; }
  16023. if (onError === void 0) { onError = null; }
  16024. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16025. if (invertY === void 0) { invertY = false; }
  16026. var gl = this._gl;
  16027. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16028. scene._addPendingData(texture);
  16029. texture.url = url;
  16030. this._internalTexturesCache.push(texture);
  16031. var onerror = function (request, exception) {
  16032. scene._removePendingData(texture);
  16033. if (onError && request) {
  16034. onError(request.status + " " + request.statusText, exception);
  16035. }
  16036. };
  16037. var internalCallback = function (data) {
  16038. var width = texture.width;
  16039. var faceDataArrays = callback(data);
  16040. if (!faceDataArrays) {
  16041. return;
  16042. }
  16043. if (mipmapGenerator) {
  16044. var textureType = _this._getWebGLTextureType(type);
  16045. var internalFormat = _this._getInternalFormat(format);
  16046. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16047. var needConversion = false;
  16048. if (internalFormat === gl.RGB) {
  16049. internalFormat = gl.RGBA;
  16050. needConversion = true;
  16051. }
  16052. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16053. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16054. var mipData = mipmapGenerator(faceDataArrays);
  16055. for (var level = 0; level < mipData.length; level++) {
  16056. var mipSize = width >> level;
  16057. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16058. var mipFaceData = mipData[level][faceIndex];
  16059. if (needConversion) {
  16060. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16061. }
  16062. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16063. }
  16064. }
  16065. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16066. }
  16067. else {
  16068. texture.generateMipMaps = !noMipmap;
  16069. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16070. }
  16071. texture.isReady = true;
  16072. // this.resetTextureCache();
  16073. scene._removePendingData(texture);
  16074. if (onLoad) {
  16075. onLoad();
  16076. }
  16077. };
  16078. this._loadFile(url, function (data) {
  16079. internalCallback(data);
  16080. }, undefined, scene.database, true, onerror);
  16081. return texture;
  16082. };
  16083. ;
  16084. /**
  16085. * Update a raw 3D texture
  16086. * @param texture defines the texture to update
  16087. * @param data defines the data to store
  16088. * @param format defines the data format
  16089. * @param invertY defines if data must be stored with Y axis inverted
  16090. * @param compression defines the used compression (can be null)
  16091. */
  16092. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  16093. if (compression === void 0) { compression = null; }
  16094. var internalFormat = this._getInternalFormat(format);
  16095. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16096. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16097. if (!this._doNotHandleContextLost) {
  16098. texture._bufferView = data;
  16099. texture.format = format;
  16100. texture.invertY = invertY;
  16101. texture._compression = compression;
  16102. }
  16103. if (texture.width % 4 !== 0) {
  16104. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16105. }
  16106. if (compression && data) {
  16107. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16108. }
  16109. else {
  16110. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16111. }
  16112. if (texture.generateMipMaps) {
  16113. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16114. }
  16115. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16116. // this.resetTextureCache();
  16117. texture.isReady = true;
  16118. };
  16119. /**
  16120. * Creates a new raw 3D texture
  16121. * @param data defines the data used to create the texture
  16122. * @param width defines the width of the texture
  16123. * @param height defines the height of the texture
  16124. * @param depth defines the depth of the texture
  16125. * @param format defines the format of the texture
  16126. * @param generateMipMaps defines if the engine must generate mip levels
  16127. * @param invertY defines if data must be stored with Y axis inverted
  16128. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16129. * @param compression defines the compressed used (can be null)
  16130. * @returns a new raw 3D texture (stored in an InternalTexture)
  16131. */
  16132. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16133. if (compression === void 0) { compression = null; }
  16134. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16135. texture.baseWidth = width;
  16136. texture.baseHeight = height;
  16137. texture.baseDepth = depth;
  16138. texture.width = width;
  16139. texture.height = height;
  16140. texture.depth = depth;
  16141. texture.format = format;
  16142. texture.generateMipMaps = generateMipMaps;
  16143. texture.samplingMode = samplingMode;
  16144. texture.is3D = true;
  16145. if (!this._doNotHandleContextLost) {
  16146. texture._bufferView = data;
  16147. }
  16148. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16149. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16150. // Filters
  16151. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16152. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16153. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16154. if (generateMipMaps) {
  16155. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16156. }
  16157. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16158. this._internalTexturesCache.push(texture);
  16159. return texture;
  16160. };
  16161. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16162. var gl = this._gl;
  16163. if (!gl) {
  16164. return;
  16165. }
  16166. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16169. if (!noMipmap && !isCompressed) {
  16170. gl.generateMipmap(gl.TEXTURE_2D);
  16171. }
  16172. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16173. // this.resetTextureCache();
  16174. if (scene) {
  16175. scene._removePendingData(texture);
  16176. }
  16177. texture.onLoadedObservable.notifyObservers(texture);
  16178. texture.onLoadedObservable.clear();
  16179. };
  16180. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16181. var _this = this;
  16182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16183. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16184. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16185. var gl = this._gl;
  16186. if (!gl) {
  16187. return;
  16188. }
  16189. if (!texture._webGLTexture) {
  16190. // this.resetTextureCache();
  16191. if (scene) {
  16192. scene._removePendingData(texture);
  16193. }
  16194. return;
  16195. }
  16196. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16197. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16198. texture.baseWidth = width;
  16199. texture.baseHeight = height;
  16200. texture.width = potWidth;
  16201. texture.height = potHeight;
  16202. texture.isReady = true;
  16203. if (processFunction(potWidth, potHeight, function () {
  16204. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16205. })) {
  16206. // Returning as texture needs extra async steps
  16207. return;
  16208. }
  16209. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16210. };
  16211. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16212. // Create new RGBA data container.
  16213. var rgbaData;
  16214. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16215. rgbaData = new Float32Array(width * height * 4);
  16216. }
  16217. else {
  16218. rgbaData = new Uint32Array(width * height * 4);
  16219. }
  16220. // Convert each pixel.
  16221. for (var x = 0; x < width; x++) {
  16222. for (var y = 0; y < height; y++) {
  16223. var index = (y * width + x) * 3;
  16224. var newIndex = (y * width + x) * 4;
  16225. // Map Old Value to new value.
  16226. rgbaData[newIndex + 0] = rgbData[index + 0];
  16227. rgbaData[newIndex + 1] = rgbData[index + 1];
  16228. rgbaData[newIndex + 2] = rgbData[index + 2];
  16229. // Add fully opaque alpha channel.
  16230. rgbaData[newIndex + 3] = 1;
  16231. }
  16232. }
  16233. return rgbaData;
  16234. };
  16235. /** @hidden */
  16236. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16237. var gl = this._gl;
  16238. if (texture._framebuffer) {
  16239. gl.deleteFramebuffer(texture._framebuffer);
  16240. texture._framebuffer = null;
  16241. }
  16242. if (texture._depthStencilBuffer) {
  16243. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16244. texture._depthStencilBuffer = null;
  16245. }
  16246. if (texture._MSAAFramebuffer) {
  16247. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16248. texture._MSAAFramebuffer = null;
  16249. }
  16250. if (texture._MSAARenderBuffer) {
  16251. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16252. texture._MSAARenderBuffer = null;
  16253. }
  16254. };
  16255. /** @hidden */
  16256. Engine.prototype._releaseTexture = function (texture) {
  16257. var gl = this._gl;
  16258. this._releaseFramebufferObjects(texture);
  16259. gl.deleteTexture(texture._webGLTexture);
  16260. // Unbind channels
  16261. this.unbindAllTextures();
  16262. var index = this._internalTexturesCache.indexOf(texture);
  16263. if (index !== -1) {
  16264. this._internalTexturesCache.splice(index, 1);
  16265. }
  16266. // Integrated fixed lod samplers.
  16267. if (texture._lodTextureHigh) {
  16268. texture._lodTextureHigh.dispose();
  16269. }
  16270. if (texture._lodTextureMid) {
  16271. texture._lodTextureMid.dispose();
  16272. }
  16273. if (texture._lodTextureLow) {
  16274. texture._lodTextureLow.dispose();
  16275. }
  16276. // Set output texture of post process to null if the texture has been released/disposed
  16277. this.scenes.forEach(function (scene) {
  16278. scene.postProcesses.forEach(function (postProcess) {
  16279. if (postProcess._outputTexture == texture) {
  16280. postProcess._outputTexture = null;
  16281. }
  16282. });
  16283. scene.cameras.forEach(function (camera) {
  16284. camera._postProcesses.forEach(function (postProcess) {
  16285. if (postProcess) {
  16286. if (postProcess._outputTexture == texture) {
  16287. postProcess._outputTexture = null;
  16288. }
  16289. }
  16290. });
  16291. });
  16292. });
  16293. };
  16294. Engine.prototype.setProgram = function (program) {
  16295. if (this._currentProgram !== program) {
  16296. this._gl.useProgram(program);
  16297. this._currentProgram = program;
  16298. }
  16299. };
  16300. /**
  16301. * Binds an effect to the webGL context
  16302. * @param effect defines the effect to bind
  16303. */
  16304. Engine.prototype.bindSamplers = function (effect) {
  16305. this.setProgram(effect.getProgram());
  16306. var samplers = effect.getSamplers();
  16307. for (var index = 0; index < samplers.length; index++) {
  16308. var uniform = effect.getUniform(samplers[index]);
  16309. if (uniform) {
  16310. this._boundUniforms[index] = uniform;
  16311. }
  16312. }
  16313. this._currentEffect = null;
  16314. };
  16315. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16316. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16317. return;
  16318. }
  16319. // Remove
  16320. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16321. // Bind last to it
  16322. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16323. // Bind to dummy
  16324. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16325. };
  16326. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16327. if (!internalTexture) {
  16328. return -1;
  16329. }
  16330. internalTexture._initialSlot = channel;
  16331. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16332. if (channel !== internalTexture._designatedSlot) {
  16333. this._textureCollisions.addCount(1, false);
  16334. }
  16335. }
  16336. else {
  16337. if (channel !== internalTexture._designatedSlot) {
  16338. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16339. return internalTexture._designatedSlot;
  16340. }
  16341. else {
  16342. // No slot for this texture, let's pick a new one (if we find a free slot)
  16343. if (this._nextFreeTextureSlots.length) {
  16344. return this._nextFreeTextureSlots[0];
  16345. }
  16346. // We need to recycle the oldest bound texture, sorry.
  16347. this._textureCollisions.addCount(1, false);
  16348. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16349. }
  16350. }
  16351. }
  16352. return channel;
  16353. };
  16354. Engine.prototype._linkTrackers = function (previous, next) {
  16355. previous.next = next;
  16356. next.previous = previous;
  16357. };
  16358. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16359. var currentSlot = internalTexture._designatedSlot;
  16360. if (currentSlot === -1) {
  16361. return -1;
  16362. }
  16363. internalTexture._designatedSlot = -1;
  16364. if (this.disableTextureBindingOptimization) {
  16365. return -1;
  16366. }
  16367. // Remove from bound list
  16368. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16369. // Free the slot
  16370. this._boundTexturesCache[currentSlot] = null;
  16371. this._nextFreeTextureSlots.push(currentSlot);
  16372. return currentSlot;
  16373. };
  16374. Engine.prototype._activateCurrentTexture = function () {
  16375. if (this._currentTextureChannel !== this._activeChannel) {
  16376. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16377. this._currentTextureChannel = this._activeChannel;
  16378. }
  16379. };
  16380. /** @hidden */
  16381. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16382. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16383. if (force === void 0) { force = false; }
  16384. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16385. this._activeChannel = texture._designatedSlot;
  16386. }
  16387. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16388. var isTextureForRendering = texture && texture._initialSlot > -1;
  16389. if (currentTextureBound !== texture || force) {
  16390. if (currentTextureBound) {
  16391. this._removeDesignatedSlot(currentTextureBound);
  16392. }
  16393. this._activateCurrentTexture();
  16394. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16395. this._boundTexturesCache[this._activeChannel] = texture;
  16396. if (texture) {
  16397. if (!this.disableTextureBindingOptimization) {
  16398. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16399. if (slotIndex > -1) {
  16400. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16401. }
  16402. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16403. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16404. }
  16405. texture._designatedSlot = this._activeChannel;
  16406. }
  16407. }
  16408. else if (forTextureDataUpdate) {
  16409. this._activateCurrentTexture();
  16410. }
  16411. if (isTextureForRendering && !forTextureDataUpdate) {
  16412. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16413. }
  16414. };
  16415. /** @hidden */
  16416. Engine.prototype._bindTexture = function (channel, texture) {
  16417. if (channel < 0) {
  16418. return;
  16419. }
  16420. if (texture) {
  16421. channel = this._getCorrectTextureChannel(channel, texture);
  16422. }
  16423. this._activeChannel = channel;
  16424. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16425. };
  16426. /**
  16427. * Sets a texture to the webGL context from a postprocess
  16428. * @param channel defines the channel to use
  16429. * @param postProcess defines the source postprocess
  16430. */
  16431. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16432. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16433. };
  16434. /**
  16435. * Binds the output of the passed in post process to the texture channel specified
  16436. * @param channel The channel the texture should be bound to
  16437. * @param postProcess The post process which's output should be bound
  16438. */
  16439. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16440. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16441. };
  16442. /**
  16443. * Unbind all textures from the webGL context
  16444. */
  16445. Engine.prototype.unbindAllTextures = function () {
  16446. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16447. this._activeChannel = channel;
  16448. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16449. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16450. if (this.webGLVersion > 1) {
  16451. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16452. }
  16453. }
  16454. };
  16455. /**
  16456. * Sets a texture to the according uniform.
  16457. * @param channel The texture channel
  16458. * @param uniform The uniform to set
  16459. * @param texture The texture to apply
  16460. */
  16461. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16462. if (channel < 0) {
  16463. return;
  16464. }
  16465. if (uniform) {
  16466. this._boundUniforms[channel] = uniform;
  16467. }
  16468. this._setTexture(channel, texture);
  16469. };
  16470. /**
  16471. * Sets a depth stencil texture from a render target to the according uniform.
  16472. * @param channel The texture channel
  16473. * @param uniform The uniform to set
  16474. * @param texture The render target texture containing the depth stencil texture to apply
  16475. */
  16476. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16477. if (channel < 0) {
  16478. return;
  16479. }
  16480. if (uniform) {
  16481. this._boundUniforms[channel] = uniform;
  16482. }
  16483. if (!texture || !texture.depthStencilTexture) {
  16484. this._setTexture(channel, null);
  16485. }
  16486. else {
  16487. this._setTexture(channel, texture, false, true);
  16488. }
  16489. };
  16490. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16491. var uniform = this._boundUniforms[sourceSlot];
  16492. if (uniform._currentState === destination) {
  16493. return;
  16494. }
  16495. this._gl.uniform1i(uniform, destination);
  16496. uniform._currentState = destination;
  16497. };
  16498. Engine.prototype._getTextureWrapMode = function (mode) {
  16499. switch (mode) {
  16500. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16501. return this._gl.REPEAT;
  16502. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16503. return this._gl.CLAMP_TO_EDGE;
  16504. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16505. return this._gl.MIRRORED_REPEAT;
  16506. }
  16507. return this._gl.REPEAT;
  16508. };
  16509. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16510. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16511. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16512. // Not ready?
  16513. if (!texture) {
  16514. if (this._boundTexturesCache[channel] != null) {
  16515. this._activeChannel = channel;
  16516. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16517. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16518. if (this.webGLVersion > 1) {
  16519. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16520. }
  16521. }
  16522. return false;
  16523. }
  16524. // Video
  16525. if (texture.video) {
  16526. this._activeChannel = channel;
  16527. texture.update();
  16528. }
  16529. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16530. texture.delayLoad();
  16531. return false;
  16532. }
  16533. var internalTexture;
  16534. if (depthStencilTexture) {
  16535. internalTexture = texture.depthStencilTexture;
  16536. }
  16537. else if (texture.isReady()) {
  16538. internalTexture = texture.getInternalTexture();
  16539. }
  16540. else if (texture.isCube) {
  16541. internalTexture = this.emptyCubeTexture;
  16542. }
  16543. else if (texture.is3D) {
  16544. internalTexture = this.emptyTexture3D;
  16545. }
  16546. else {
  16547. internalTexture = this.emptyTexture;
  16548. }
  16549. if (!isPartOfTextureArray) {
  16550. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16551. }
  16552. var needToBind = true;
  16553. if (this._boundTexturesCache[channel] === internalTexture) {
  16554. this._moveBoundTextureOnTop(internalTexture);
  16555. if (!isPartOfTextureArray) {
  16556. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16557. }
  16558. needToBind = false;
  16559. }
  16560. this._activeChannel = channel;
  16561. if (internalTexture && internalTexture.is3D) {
  16562. if (needToBind) {
  16563. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16564. }
  16565. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16566. internalTexture._cachedWrapU = texture.wrapU;
  16567. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16568. }
  16569. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16570. internalTexture._cachedWrapV = texture.wrapV;
  16571. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16572. }
  16573. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16574. internalTexture._cachedWrapR = texture.wrapR;
  16575. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16576. }
  16577. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16578. }
  16579. else if (internalTexture && internalTexture.isCube) {
  16580. if (needToBind) {
  16581. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16582. }
  16583. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16584. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16585. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16586. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16587. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16588. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16589. }
  16590. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16591. }
  16592. else {
  16593. if (needToBind) {
  16594. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16595. }
  16596. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16597. internalTexture._cachedWrapU = texture.wrapU;
  16598. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16599. }
  16600. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16601. internalTexture._cachedWrapV = texture.wrapV;
  16602. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16603. }
  16604. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16605. }
  16606. return true;
  16607. };
  16608. /**
  16609. * Sets an array of texture to the webGL context
  16610. * @param channel defines the channel where the texture array must be set
  16611. * @param uniform defines the associated uniform location
  16612. * @param textures defines the array of textures to bind
  16613. */
  16614. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16615. if (channel < 0 || !uniform) {
  16616. return;
  16617. }
  16618. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16619. this._textureUnits = new Int32Array(textures.length);
  16620. }
  16621. for (var i = 0; i < textures.length; i++) {
  16622. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16623. }
  16624. this._gl.uniform1iv(uniform, this._textureUnits);
  16625. for (var index = 0; index < textures.length; index++) {
  16626. this._setTexture(this._textureUnits[index], textures[index], true);
  16627. }
  16628. };
  16629. /** @hidden */
  16630. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16631. var internalTexture = texture.getInternalTexture();
  16632. if (!internalTexture) {
  16633. return;
  16634. }
  16635. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16636. var value = texture.anisotropicFilteringLevel;
  16637. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16638. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16639. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16640. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16641. }
  16642. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16643. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16644. internalTexture._cachedAnisotropicFilteringLevel = value;
  16645. }
  16646. };
  16647. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16648. this._bindTextureDirectly(target, texture, true, true);
  16649. this._gl.texParameterf(target, parameter, value);
  16650. };
  16651. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16652. if (texture) {
  16653. this._bindTextureDirectly(target, texture, true, true);
  16654. }
  16655. this._gl.texParameteri(target, parameter, value);
  16656. };
  16657. /**
  16658. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16659. * @param x defines the x coordinate of the rectangle where pixels must be read
  16660. * @param y defines the y coordinate of the rectangle where pixels must be read
  16661. * @param width defines the width of the rectangle where pixels must be read
  16662. * @param height defines the height of the rectangle where pixels must be read
  16663. * @returns a Uint8Array containing RGBA colors
  16664. */
  16665. Engine.prototype.readPixels = function (x, y, width, height) {
  16666. var data = new Uint8Array(height * width * 4);
  16667. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16668. return data;
  16669. };
  16670. /**
  16671. * Add an externaly attached data from its key.
  16672. * This method call will fail and return false, if such key already exists.
  16673. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16674. * @param key the unique key that identifies the data
  16675. * @param data the data object to associate to the key for this Engine instance
  16676. * @return true if no such key were already present and the data was added successfully, false otherwise
  16677. */
  16678. Engine.prototype.addExternalData = function (key, data) {
  16679. if (!this._externalData) {
  16680. this._externalData = new BABYLON.StringDictionary();
  16681. }
  16682. return this._externalData.add(key, data);
  16683. };
  16684. /**
  16685. * Get an externaly attached data from its key
  16686. * @param key the unique key that identifies the data
  16687. * @return the associated data, if present (can be null), or undefined if not present
  16688. */
  16689. Engine.prototype.getExternalData = function (key) {
  16690. if (!this._externalData) {
  16691. this._externalData = new BABYLON.StringDictionary();
  16692. }
  16693. return this._externalData.get(key);
  16694. };
  16695. /**
  16696. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16697. * @param key the unique key that identifies the data
  16698. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16699. * @return the associated data, can be null if the factory returned null.
  16700. */
  16701. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16702. if (!this._externalData) {
  16703. this._externalData = new BABYLON.StringDictionary();
  16704. }
  16705. return this._externalData.getOrAddWithFactory(key, factory);
  16706. };
  16707. /**
  16708. * Remove an externaly attached data from the Engine instance
  16709. * @param key the unique key that identifies the data
  16710. * @return true if the data was successfully removed, false if it doesn't exist
  16711. */
  16712. Engine.prototype.removeExternalData = function (key) {
  16713. if (!this._externalData) {
  16714. this._externalData = new BABYLON.StringDictionary();
  16715. }
  16716. return this._externalData.remove(key);
  16717. };
  16718. /**
  16719. * Unbind all vertex attributes from the webGL context
  16720. */
  16721. Engine.prototype.unbindAllAttributes = function () {
  16722. if (this._mustWipeVertexAttributes) {
  16723. this._mustWipeVertexAttributes = false;
  16724. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16725. this._gl.disableVertexAttribArray(i);
  16726. this._vertexAttribArraysEnabled[i] = false;
  16727. this._currentBufferPointers[i].active = false;
  16728. }
  16729. return;
  16730. }
  16731. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16732. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16733. continue;
  16734. }
  16735. this._gl.disableVertexAttribArray(i);
  16736. this._vertexAttribArraysEnabled[i] = false;
  16737. this._currentBufferPointers[i].active = false;
  16738. }
  16739. };
  16740. /**
  16741. * 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
  16742. */
  16743. Engine.prototype.releaseEffects = function () {
  16744. for (var name in this._compiledEffects) {
  16745. this._deleteProgram(this._compiledEffects[name]._program);
  16746. }
  16747. this._compiledEffects = {};
  16748. };
  16749. /**
  16750. * Dispose and release all associated resources
  16751. */
  16752. Engine.prototype.dispose = function () {
  16753. this.hideLoadingUI();
  16754. this.stopRenderLoop();
  16755. // Release postProcesses
  16756. while (this.postProcesses.length) {
  16757. this.postProcesses[0].dispose();
  16758. }
  16759. // Empty texture
  16760. if (this._emptyTexture) {
  16761. this._releaseTexture(this._emptyTexture);
  16762. this._emptyTexture = null;
  16763. }
  16764. if (this._emptyCubeTexture) {
  16765. this._releaseTexture(this._emptyCubeTexture);
  16766. this._emptyCubeTexture = null;
  16767. }
  16768. // Rescale PP
  16769. if (this._rescalePostProcess) {
  16770. this._rescalePostProcess.dispose();
  16771. }
  16772. // Release scenes
  16773. while (this.scenes.length) {
  16774. this.scenes[0].dispose();
  16775. }
  16776. // Release audio engine
  16777. if (Engine.audioEngine) {
  16778. Engine.audioEngine.dispose();
  16779. }
  16780. // Release effects
  16781. this.releaseEffects();
  16782. // Unbind
  16783. this.unbindAllAttributes();
  16784. this._boundUniforms = [];
  16785. if (this._dummyFramebuffer) {
  16786. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16787. }
  16788. //WebVR
  16789. this.disableVR();
  16790. // Events
  16791. if (BABYLON.Tools.IsWindowObjectExist()) {
  16792. window.removeEventListener("blur", this._onBlur);
  16793. window.removeEventListener("focus", this._onFocus);
  16794. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16795. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16796. if (this._renderingCanvas) {
  16797. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16798. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16799. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16800. if (!this._doNotHandleContextLost) {
  16801. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16802. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16803. }
  16804. }
  16805. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16806. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16807. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16808. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16809. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16810. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16811. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16812. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16813. if (this._onVrDisplayConnect) {
  16814. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16815. if (this._onVrDisplayDisconnect) {
  16816. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16817. }
  16818. if (this._onVrDisplayPresentChange) {
  16819. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16820. }
  16821. this._onVrDisplayConnect = null;
  16822. this._onVrDisplayDisconnect = null;
  16823. }
  16824. }
  16825. // Remove from Instances
  16826. var index = Engine.Instances.indexOf(this);
  16827. if (index >= 0) {
  16828. Engine.Instances.splice(index, 1);
  16829. }
  16830. this._workingCanvas = null;
  16831. this._workingContext = null;
  16832. this._currentBufferPointers = [];
  16833. this._renderingCanvas = null;
  16834. this._currentProgram = null;
  16835. this._bindedRenderFunction = null;
  16836. this.onResizeObservable.clear();
  16837. this.onCanvasBlurObservable.clear();
  16838. this.onCanvasFocusObservable.clear();
  16839. this.onCanvasPointerOutObservable.clear();
  16840. this.onBeginFrameObservable.clear();
  16841. this.onEndFrameObservable.clear();
  16842. BABYLON.Effect.ResetCache();
  16843. // Abort active requests
  16844. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16845. var request = _a[_i];
  16846. request.abort();
  16847. }
  16848. };
  16849. // Loading screen
  16850. /**
  16851. * Display the loading screen
  16852. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16853. */
  16854. Engine.prototype.displayLoadingUI = function () {
  16855. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16856. return;
  16857. }
  16858. var loadingScreen = this.loadingScreen;
  16859. if (loadingScreen) {
  16860. loadingScreen.displayLoadingUI();
  16861. }
  16862. };
  16863. /**
  16864. * Hide the loading screen
  16865. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16866. */
  16867. Engine.prototype.hideLoadingUI = function () {
  16868. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16869. return;
  16870. }
  16871. var loadingScreen = this.loadingScreen;
  16872. if (loadingScreen) {
  16873. loadingScreen.hideLoadingUI();
  16874. }
  16875. };
  16876. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16877. /**
  16878. * Gets the current loading screen object
  16879. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16880. */
  16881. get: function () {
  16882. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16883. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16884. return this._loadingScreen;
  16885. },
  16886. /**
  16887. * Sets the current loading screen object
  16888. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16889. */
  16890. set: function (loadingScreen) {
  16891. this._loadingScreen = loadingScreen;
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16897. /**
  16898. * Sets the current loading screen text
  16899. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16900. */
  16901. set: function (text) {
  16902. this.loadingScreen.loadingUIText = text;
  16903. },
  16904. enumerable: true,
  16905. configurable: true
  16906. });
  16907. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16908. /**
  16909. * Sets the current loading screen background color
  16910. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16911. */
  16912. set: function (color) {
  16913. this.loadingScreen.loadingUIBackgroundColor = color;
  16914. },
  16915. enumerable: true,
  16916. configurable: true
  16917. });
  16918. /**
  16919. * Attach a new callback raised when context lost event is fired
  16920. * @param callback defines the callback to call
  16921. */
  16922. Engine.prototype.attachContextLostEvent = function (callback) {
  16923. if (this._renderingCanvas) {
  16924. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16925. }
  16926. };
  16927. /**
  16928. * Attach a new callback raised when context restored event is fired
  16929. * @param callback defines the callback to call
  16930. */
  16931. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16932. if (this._renderingCanvas) {
  16933. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16934. }
  16935. };
  16936. /**
  16937. * Gets the source code of the vertex shader associated with a specific webGL program
  16938. * @param program defines the program to use
  16939. * @returns a string containing the source code of the vertex shader associated with the program
  16940. */
  16941. Engine.prototype.getVertexShaderSource = function (program) {
  16942. var shaders = this._gl.getAttachedShaders(program);
  16943. if (!shaders) {
  16944. return null;
  16945. }
  16946. return this._gl.getShaderSource(shaders[0]);
  16947. };
  16948. /**
  16949. * Gets the source code of the fragment shader associated with a specific webGL program
  16950. * @param program defines the program to use
  16951. * @returns a string containing the source code of the fragment shader associated with the program
  16952. */
  16953. Engine.prototype.getFragmentShaderSource = function (program) {
  16954. var shaders = this._gl.getAttachedShaders(program);
  16955. if (!shaders) {
  16956. return null;
  16957. }
  16958. return this._gl.getShaderSource(shaders[1]);
  16959. };
  16960. /**
  16961. * Get the current error code of the webGL context
  16962. * @returns the error code
  16963. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16964. */
  16965. Engine.prototype.getError = function () {
  16966. return this._gl.getError();
  16967. };
  16968. // FPS
  16969. /**
  16970. * Gets the current framerate
  16971. * @returns a number representing the framerate
  16972. */
  16973. Engine.prototype.getFps = function () {
  16974. return this._fps;
  16975. };
  16976. /**
  16977. * Gets the time spent between current and previous frame
  16978. * @returns a number representing the delta time in ms
  16979. */
  16980. Engine.prototype.getDeltaTime = function () {
  16981. return this._deltaTime;
  16982. };
  16983. Engine.prototype._measureFps = function () {
  16984. this._performanceMonitor.sampleFrame();
  16985. this._fps = this._performanceMonitor.averageFPS;
  16986. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16987. };
  16988. /** @hidden */
  16989. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16990. if (faceIndex === void 0) { faceIndex = -1; }
  16991. var gl = this._gl;
  16992. if (!this._dummyFramebuffer) {
  16993. var dummy = gl.createFramebuffer();
  16994. if (!dummy) {
  16995. throw new Error("Unable to create dummy framebuffer");
  16996. }
  16997. this._dummyFramebuffer = dummy;
  16998. }
  16999. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17000. if (faceIndex > -1) {
  17001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  17002. }
  17003. else {
  17004. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  17005. }
  17006. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17007. var buffer;
  17008. switch (readType) {
  17009. case gl.UNSIGNED_BYTE:
  17010. buffer = new Uint8Array(4 * width * height);
  17011. readType = gl.UNSIGNED_BYTE;
  17012. break;
  17013. default:
  17014. buffer = new Float32Array(4 * width * height);
  17015. readType = gl.FLOAT;
  17016. break;
  17017. }
  17018. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17019. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17020. return buffer;
  17021. };
  17022. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17023. if (this._webGLVersion > 1) {
  17024. return this._caps.colorBufferFloat;
  17025. }
  17026. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17027. };
  17028. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17029. if (this._webGLVersion > 1) {
  17030. return this._caps.colorBufferFloat;
  17031. }
  17032. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17033. };
  17034. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17035. Engine.prototype._canRenderToFramebuffer = function (type) {
  17036. var gl = this._gl;
  17037. //clear existing errors
  17038. while (gl.getError() !== gl.NO_ERROR) { }
  17039. var successful = true;
  17040. var texture = gl.createTexture();
  17041. gl.bindTexture(gl.TEXTURE_2D, texture);
  17042. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17043. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17044. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17045. var fb = gl.createFramebuffer();
  17046. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17047. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17048. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17049. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17050. successful = successful && (gl.getError() === gl.NO_ERROR);
  17051. //try render by clearing frame buffer's color buffer
  17052. if (successful) {
  17053. gl.clear(gl.COLOR_BUFFER_BIT);
  17054. successful = successful && (gl.getError() === gl.NO_ERROR);
  17055. }
  17056. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17057. if (successful) {
  17058. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17059. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17060. var readFormat = gl.RGBA;
  17061. var readType = gl.UNSIGNED_BYTE;
  17062. var buffer = new Uint8Array(4);
  17063. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17064. successful = successful && (gl.getError() === gl.NO_ERROR);
  17065. }
  17066. //clean up
  17067. gl.deleteTexture(texture);
  17068. gl.deleteFramebuffer(fb);
  17069. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17070. //clear accumulated errors
  17071. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17072. return successful;
  17073. };
  17074. /** @hidden */
  17075. Engine.prototype._getWebGLTextureType = function (type) {
  17076. if (type === Engine.TEXTURETYPE_FLOAT) {
  17077. return this._gl.FLOAT;
  17078. }
  17079. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17080. // Add Half Float Constant.
  17081. return this._gl.HALF_FLOAT_OES;
  17082. }
  17083. return this._gl.UNSIGNED_BYTE;
  17084. };
  17085. ;
  17086. Engine.prototype._getInternalFormat = function (format) {
  17087. var internalFormat = this._gl.RGBA;
  17088. switch (format) {
  17089. case Engine.TEXTUREFORMAT_ALPHA:
  17090. internalFormat = this._gl.ALPHA;
  17091. break;
  17092. case Engine.TEXTUREFORMAT_LUMINANCE:
  17093. internalFormat = this._gl.LUMINANCE;
  17094. break;
  17095. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17096. internalFormat = this._gl.LUMINANCE_ALPHA;
  17097. break;
  17098. case Engine.TEXTUREFORMAT_RGB:
  17099. case Engine.TEXTUREFORMAT_RGB32F:
  17100. internalFormat = this._gl.RGB;
  17101. break;
  17102. case Engine.TEXTUREFORMAT_RGBA:
  17103. case Engine.TEXTUREFORMAT_RGBA32F:
  17104. internalFormat = this._gl.RGBA;
  17105. break;
  17106. case Engine.TEXTUREFORMAT_R32F:
  17107. internalFormat = this._gl.RED;
  17108. break;
  17109. case Engine.TEXTUREFORMAT_RG32F:
  17110. internalFormat = this._gl.RG;
  17111. break;
  17112. }
  17113. return internalFormat;
  17114. };
  17115. /** @hidden */
  17116. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17117. if (this._webGLVersion === 1) {
  17118. if (format) {
  17119. switch (format) {
  17120. case Engine.TEXTUREFORMAT_LUMINANCE:
  17121. return this._gl.LUMINANCE;
  17122. }
  17123. }
  17124. return this._gl.RGBA;
  17125. }
  17126. if (type === Engine.TEXTURETYPE_FLOAT) {
  17127. if (format) {
  17128. switch (format) {
  17129. case Engine.TEXTUREFORMAT_R32F:
  17130. return this._gl.R32F;
  17131. case Engine.TEXTUREFORMAT_RG32F:
  17132. return this._gl.RG32F;
  17133. case Engine.TEXTUREFORMAT_RGB32F:
  17134. return this._gl.RGB32F;
  17135. }
  17136. }
  17137. return this._gl.RGBA32F;
  17138. }
  17139. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17140. return this._gl.RGBA16F;
  17141. }
  17142. if (format) {
  17143. switch (format) {
  17144. case Engine.TEXTUREFORMAT_LUMINANCE:
  17145. return this._gl.LUMINANCE;
  17146. case Engine.TEXTUREFORMAT_RGB:
  17147. return this._gl.RGB;
  17148. }
  17149. }
  17150. return this._gl.RGBA;
  17151. };
  17152. ;
  17153. /** @hidden */
  17154. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17155. if (type === Engine.TEXTURETYPE_FLOAT) {
  17156. return this._gl.RGBA32F;
  17157. }
  17158. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17159. return this._gl.RGBA16F;
  17160. }
  17161. return this._gl.RGBA8;
  17162. };
  17163. ;
  17164. /**
  17165. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17166. * @return the new query
  17167. */
  17168. Engine.prototype.createQuery = function () {
  17169. return this._gl.createQuery();
  17170. };
  17171. /**
  17172. * Delete and release a webGL query
  17173. * @param query defines the query to delete
  17174. * @return the current engine
  17175. */
  17176. Engine.prototype.deleteQuery = function (query) {
  17177. this._gl.deleteQuery(query);
  17178. return this;
  17179. };
  17180. /**
  17181. * Check if a given query has resolved and got its value
  17182. * @param query defines the query to check
  17183. * @returns true if the query got its value
  17184. */
  17185. Engine.prototype.isQueryResultAvailable = function (query) {
  17186. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17187. };
  17188. /**
  17189. * Gets the value of a given query
  17190. * @param query defines the query to check
  17191. * @returns the value of the query
  17192. */
  17193. Engine.prototype.getQueryResult = function (query) {
  17194. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17195. };
  17196. /**
  17197. * Initiates an occlusion query
  17198. * @param algorithmType defines the algorithm to use
  17199. * @param query defines the query to use
  17200. * @returns the current engine
  17201. * @see http://doc.babylonjs.com/features/occlusionquery
  17202. */
  17203. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17204. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17205. this._gl.beginQuery(glAlgorithm, query);
  17206. return this;
  17207. };
  17208. /**
  17209. * Ends an occlusion query
  17210. * @see http://doc.babylonjs.com/features/occlusionquery
  17211. * @param algorithmType defines the algorithm to use
  17212. * @returns the current engine
  17213. */
  17214. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17215. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17216. this._gl.endQuery(glAlgorithm);
  17217. return this;
  17218. };
  17219. /* Time queries */
  17220. Engine.prototype._createTimeQuery = function () {
  17221. var timerQuery = this._caps.timerQuery;
  17222. if (timerQuery.createQueryEXT) {
  17223. return timerQuery.createQueryEXT();
  17224. }
  17225. return this.createQuery();
  17226. };
  17227. Engine.prototype._deleteTimeQuery = function (query) {
  17228. var timerQuery = this._caps.timerQuery;
  17229. if (timerQuery.deleteQueryEXT) {
  17230. timerQuery.deleteQueryEXT(query);
  17231. return;
  17232. }
  17233. this.deleteQuery(query);
  17234. };
  17235. Engine.prototype._getTimeQueryResult = function (query) {
  17236. var timerQuery = this._caps.timerQuery;
  17237. if (timerQuery.getQueryObjectEXT) {
  17238. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17239. }
  17240. return this.getQueryResult(query);
  17241. };
  17242. Engine.prototype._getTimeQueryAvailability = function (query) {
  17243. var timerQuery = this._caps.timerQuery;
  17244. if (timerQuery.getQueryObjectEXT) {
  17245. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17246. }
  17247. return this.isQueryResultAvailable(query);
  17248. };
  17249. /**
  17250. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17251. * Please note that only one query can be issued at a time
  17252. * @returns a time token used to track the time span
  17253. */
  17254. Engine.prototype.startTimeQuery = function () {
  17255. var timerQuery = this._caps.timerQuery;
  17256. if (!timerQuery) {
  17257. return null;
  17258. }
  17259. var token = new BABYLON._TimeToken();
  17260. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17261. if (this._caps.canUseTimestampForTimerQuery) {
  17262. token._startTimeQuery = this._createTimeQuery();
  17263. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17264. }
  17265. else {
  17266. if (this._currentNonTimestampToken) {
  17267. return this._currentNonTimestampToken;
  17268. }
  17269. token._timeElapsedQuery = this._createTimeQuery();
  17270. if (timerQuery.beginQueryEXT) {
  17271. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17272. }
  17273. else {
  17274. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17275. }
  17276. this._currentNonTimestampToken = token;
  17277. }
  17278. return token;
  17279. };
  17280. /**
  17281. * Ends a time query
  17282. * @param token defines the token used to measure the time span
  17283. * @returns the time spent (in ns)
  17284. */
  17285. Engine.prototype.endTimeQuery = function (token) {
  17286. var timerQuery = this._caps.timerQuery;
  17287. if (!timerQuery || !token) {
  17288. return -1;
  17289. }
  17290. if (this._caps.canUseTimestampForTimerQuery) {
  17291. if (!token._startTimeQuery) {
  17292. return -1;
  17293. }
  17294. if (!token._endTimeQuery) {
  17295. token._endTimeQuery = this._createTimeQuery();
  17296. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17297. }
  17298. }
  17299. else if (!token._timeElapsedQueryEnded) {
  17300. if (!token._timeElapsedQuery) {
  17301. return -1;
  17302. }
  17303. if (timerQuery.endQueryEXT) {
  17304. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17305. }
  17306. else {
  17307. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17308. }
  17309. token._timeElapsedQueryEnded = true;
  17310. }
  17311. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17312. var available = false;
  17313. if (token._endTimeQuery) {
  17314. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17315. }
  17316. else if (token._timeElapsedQuery) {
  17317. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17318. }
  17319. if (available && !disjoint) {
  17320. var result = 0;
  17321. if (this._caps.canUseTimestampForTimerQuery) {
  17322. if (!token._startTimeQuery || !token._endTimeQuery) {
  17323. return -1;
  17324. }
  17325. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17326. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17327. result = timeEnd - timeStart;
  17328. this._deleteTimeQuery(token._startTimeQuery);
  17329. this._deleteTimeQuery(token._endTimeQuery);
  17330. token._startTimeQuery = null;
  17331. token._endTimeQuery = null;
  17332. }
  17333. else {
  17334. if (!token._timeElapsedQuery) {
  17335. return -1;
  17336. }
  17337. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17338. this._deleteTimeQuery(token._timeElapsedQuery);
  17339. token._timeElapsedQuery = null;
  17340. token._timeElapsedQueryEnded = false;
  17341. this._currentNonTimestampToken = null;
  17342. }
  17343. return result;
  17344. }
  17345. return -1;
  17346. };
  17347. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17348. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17349. };
  17350. // Transform feedback
  17351. /**
  17352. * Creates a webGL transform feedback object
  17353. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17354. * @returns the webGL transform feedback object
  17355. */
  17356. Engine.prototype.createTransformFeedback = function () {
  17357. return this._gl.createTransformFeedback();
  17358. };
  17359. /**
  17360. * Delete a webGL transform feedback object
  17361. * @param value defines the webGL transform feedback object to delete
  17362. */
  17363. Engine.prototype.deleteTransformFeedback = function (value) {
  17364. this._gl.deleteTransformFeedback(value);
  17365. };
  17366. /**
  17367. * Bind a webGL transform feedback object to the webgl context
  17368. * @param value defines the webGL transform feedback object to bind
  17369. */
  17370. Engine.prototype.bindTransformFeedback = function (value) {
  17371. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17372. };
  17373. /**
  17374. * Begins a transform feedback operation
  17375. * @param usePoints defines if points or triangles must be used
  17376. */
  17377. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17378. if (usePoints === void 0) { usePoints = true; }
  17379. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17380. };
  17381. /**
  17382. * Ends a transform feedback operation
  17383. */
  17384. Engine.prototype.endTransformFeedback = function () {
  17385. this._gl.endTransformFeedback();
  17386. };
  17387. /**
  17388. * Specify the varyings to use with transform feedback
  17389. * @param program defines the associated webGL program
  17390. * @param value defines the list of strings representing the varying names
  17391. */
  17392. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17393. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17394. };
  17395. /**
  17396. * Bind a webGL buffer for a transform feedback operation
  17397. * @param value defines the webGL buffer to bind
  17398. */
  17399. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17400. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17401. };
  17402. /** @hidden */
  17403. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17404. var _this = this;
  17405. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17406. this._activeRequests.push(request);
  17407. request.onCompleteObservable.add(function (request) {
  17408. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17409. });
  17410. return request;
  17411. };
  17412. /** @hidden */
  17413. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17414. var _this = this;
  17415. return new Promise(function (resolve, reject) {
  17416. _this._loadFile(url, function (data) {
  17417. resolve(data);
  17418. }, undefined, database, useArrayBuffer, function (request, exception) {
  17419. reject(exception);
  17420. });
  17421. });
  17422. };
  17423. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17424. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17425. var onload = function (data) {
  17426. loadedFiles[index] = data;
  17427. loadedFiles._internalCount++;
  17428. if (loadedFiles._internalCount === 6) {
  17429. onfinish(loadedFiles);
  17430. }
  17431. };
  17432. var onerror = function (request, exception) {
  17433. if (onErrorCallBack && request) {
  17434. onErrorCallBack(request.status + " " + request.statusText, exception);
  17435. }
  17436. };
  17437. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17438. };
  17439. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17440. if (onError === void 0) { onError = null; }
  17441. var loadedFiles = [];
  17442. loadedFiles._internalCount = 0;
  17443. for (var index = 0; index < 6; index++) {
  17444. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17445. }
  17446. };
  17447. // Statics
  17448. /**
  17449. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17450. * @returns true if the engine can be created
  17451. * @ignorenaming
  17452. */
  17453. Engine.isSupported = function () {
  17454. try {
  17455. var tempcanvas = document.createElement("canvas");
  17456. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17457. return gl != null && !!window.WebGLRenderingContext;
  17458. }
  17459. catch (e) {
  17460. return false;
  17461. }
  17462. };
  17463. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17464. Engine.ExceptionList = [
  17465. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17466. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17467. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17468. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17469. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17470. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17471. ];
  17472. /** Gets the list of created engines */
  17473. Engine.Instances = new Array();
  17474. // Const statics
  17475. Engine._ALPHA_DISABLE = 0;
  17476. Engine._ALPHA_ADD = 1;
  17477. Engine._ALPHA_COMBINE = 2;
  17478. Engine._ALPHA_SUBTRACT = 3;
  17479. Engine._ALPHA_MULTIPLY = 4;
  17480. Engine._ALPHA_MAXIMIZED = 5;
  17481. Engine._ALPHA_ONEONE = 6;
  17482. Engine._ALPHA_PREMULTIPLIED = 7;
  17483. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17484. Engine._ALPHA_INTERPOLATE = 9;
  17485. Engine._ALPHA_SCREENMODE = 10;
  17486. Engine._DELAYLOADSTATE_NONE = 0;
  17487. Engine._DELAYLOADSTATE_LOADED = 1;
  17488. Engine._DELAYLOADSTATE_LOADING = 2;
  17489. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17490. Engine._TEXTUREFORMAT_ALPHA = 0;
  17491. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17492. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17493. Engine._TEXTUREFORMAT_RGB = 4;
  17494. Engine._TEXTUREFORMAT_RGBA = 5;
  17495. Engine._TEXTUREFORMAT_R32F = 6;
  17496. Engine._TEXTUREFORMAT_RG32F = 7;
  17497. Engine._TEXTUREFORMAT_RGB32F = 8;
  17498. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17499. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17500. Engine._TEXTURETYPE_FLOAT = 1;
  17501. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17502. // Depht or Stencil test Constants.
  17503. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17504. 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.
  17505. 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.
  17506. 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.
  17507. 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.
  17508. 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.
  17509. 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.
  17510. 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.
  17511. // Stencil Actions Constants.
  17512. Engine._KEEP = 0x1E00;
  17513. Engine._REPLACE = 0x1E01;
  17514. Engine._INCR = 0x1E02;
  17515. Engine._DECR = 0x1E03;
  17516. Engine._INVERT = 0x150A;
  17517. Engine._INCR_WRAP = 0x8507;
  17518. Engine._DECR_WRAP = 0x8508;
  17519. // Texture rescaling mode
  17520. Engine._SCALEMODE_FLOOR = 1;
  17521. Engine._SCALEMODE_NEAREST = 2;
  17522. Engine._SCALEMODE_CEILING = 3;
  17523. // Updatable statics so stick with vars here
  17524. /**
  17525. * Gets or sets the epsilon value used by collision engine
  17526. */
  17527. Engine.CollisionsEpsilon = 0.001;
  17528. /**
  17529. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17530. */
  17531. Engine.CodeRepository = "src/";
  17532. /**
  17533. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17534. */
  17535. Engine.ShadersRepository = "src/Shaders/";
  17536. return Engine;
  17537. }());
  17538. BABYLON.Engine = Engine;
  17539. })(BABYLON || (BABYLON = {}));
  17540. //# sourceMappingURL=babylon.engine.js.map
  17541. var BABYLON;
  17542. (function (BABYLON) {
  17543. /**
  17544. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17545. */
  17546. var Node = /** @class */ (function () {
  17547. /**
  17548. * Creates a new Node
  17549. * @param {string} name - the name and id to be given to this node
  17550. * @param {BABYLON.Scene} the scene this node will be added to
  17551. */
  17552. function Node(name, scene) {
  17553. if (scene === void 0) { scene = null; }
  17554. /**
  17555. * Gets or sets a string used to store user defined state for the node
  17556. */
  17557. this.state = "";
  17558. /**
  17559. * Gets or sets an object used to store user defined information for the node
  17560. */
  17561. this.metadata = null;
  17562. /**
  17563. * Gets or sets a boolean used to define if the node must be serialized
  17564. */
  17565. this.doNotSerialize = false;
  17566. /** @hidden */
  17567. this._isDisposed = false;
  17568. /**
  17569. * Gets a list of Animations associated with the node
  17570. */
  17571. this.animations = new Array();
  17572. this._ranges = {};
  17573. this._isEnabled = true;
  17574. this._isReady = true;
  17575. /** @hidden */
  17576. this._currentRenderId = -1;
  17577. this._parentRenderId = -1;
  17578. this._childRenderId = -1;
  17579. this._animationPropertiesOverride = null;
  17580. /**
  17581. * An event triggered when the mesh is disposed
  17582. */
  17583. this.onDisposeObservable = new BABYLON.Observable();
  17584. // Behaviors
  17585. this._behaviors = new Array();
  17586. this.name = name;
  17587. this.id = name;
  17588. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17589. this.uniqueId = this._scene.getUniqueId();
  17590. this._initCache();
  17591. }
  17592. /**
  17593. * Gets a boolean indicating if the node has been disposed
  17594. * @returns true if the node was disposed
  17595. */
  17596. Node.prototype.isDisposed = function () {
  17597. return this._isDisposed;
  17598. };
  17599. Object.defineProperty(Node.prototype, "parent", {
  17600. get: function () {
  17601. return this._parentNode;
  17602. },
  17603. /**
  17604. * Gets or sets the parent of the node
  17605. */
  17606. set: function (parent) {
  17607. if (this._parentNode === parent) {
  17608. return;
  17609. }
  17610. // Remove self from list of children of parent
  17611. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17612. var index = this._parentNode._children.indexOf(this);
  17613. if (index !== -1) {
  17614. this._parentNode._children.splice(index, 1);
  17615. }
  17616. }
  17617. // Store new parent
  17618. this._parentNode = parent;
  17619. // Add as child to new parent
  17620. if (this._parentNode) {
  17621. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17622. this._parentNode._children = new Array();
  17623. }
  17624. this._parentNode._children.push(this);
  17625. }
  17626. },
  17627. enumerable: true,
  17628. configurable: true
  17629. });
  17630. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17631. /**
  17632. * Gets or sets the animation properties override
  17633. */
  17634. get: function () {
  17635. if (!this._animationPropertiesOverride) {
  17636. return this._scene.animationPropertiesOverride;
  17637. }
  17638. return this._animationPropertiesOverride;
  17639. },
  17640. set: function (value) {
  17641. this._animationPropertiesOverride = value;
  17642. },
  17643. enumerable: true,
  17644. configurable: true
  17645. });
  17646. /**
  17647. * Gets a string idenfifying the name of the class
  17648. * @returns "Node" string
  17649. */
  17650. Node.prototype.getClassName = function () {
  17651. return "Node";
  17652. };
  17653. Object.defineProperty(Node.prototype, "onDispose", {
  17654. /**
  17655. * Sets a callback that will be raised when the node will be disposed
  17656. */
  17657. set: function (callback) {
  17658. if (this._onDisposeObserver) {
  17659. this.onDisposeObservable.remove(this._onDisposeObserver);
  17660. }
  17661. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17662. },
  17663. enumerable: true,
  17664. configurable: true
  17665. });
  17666. /**
  17667. * Gets the scene of the node
  17668. * @returns a {BABYLON.Scene}
  17669. */
  17670. Node.prototype.getScene = function () {
  17671. return this._scene;
  17672. };
  17673. /**
  17674. * Gets the engine of the node
  17675. * @returns a {BABYLON.Engine}
  17676. */
  17677. Node.prototype.getEngine = function () {
  17678. return this._scene.getEngine();
  17679. };
  17680. /**
  17681. * Attach a behavior to the node
  17682. * @see http://doc.babylonjs.com/features/behaviour
  17683. * @param behavior defines the behavior to attach
  17684. * @returns the current Node
  17685. */
  17686. Node.prototype.addBehavior = function (behavior) {
  17687. var _this = this;
  17688. var index = this._behaviors.indexOf(behavior);
  17689. if (index !== -1) {
  17690. return this;
  17691. }
  17692. behavior.init();
  17693. if (this._scene.isLoading) {
  17694. // We defer the attach when the scene will be loaded
  17695. this._scene.onDataLoadedObservable.addOnce(function () {
  17696. behavior.attach(_this);
  17697. });
  17698. }
  17699. else {
  17700. behavior.attach(this);
  17701. }
  17702. this._behaviors.push(behavior);
  17703. return this;
  17704. };
  17705. /**
  17706. * Remove an attached behavior
  17707. * @see http://doc.babylonjs.com/features/behaviour
  17708. * @param behavior defines the behavior to attach
  17709. * @returns the current Node
  17710. */
  17711. Node.prototype.removeBehavior = function (behavior) {
  17712. var index = this._behaviors.indexOf(behavior);
  17713. if (index === -1) {
  17714. return this;
  17715. }
  17716. this._behaviors[index].detach();
  17717. this._behaviors.splice(index, 1);
  17718. return this;
  17719. };
  17720. Object.defineProperty(Node.prototype, "behaviors", {
  17721. /**
  17722. * Gets the list of attached behaviors
  17723. * @see http://doc.babylonjs.com/features/behaviour
  17724. */
  17725. get: function () {
  17726. return this._behaviors;
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. /**
  17732. * Gets an attached behavior by name
  17733. * @param name defines the name of the behavior to look for
  17734. * @see http://doc.babylonjs.com/features/behaviour
  17735. * @returns null if behavior was not found else the requested behavior
  17736. */
  17737. Node.prototype.getBehaviorByName = function (name) {
  17738. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17739. var behavior = _a[_i];
  17740. if (behavior.name === name) {
  17741. return behavior;
  17742. }
  17743. }
  17744. return null;
  17745. };
  17746. /**
  17747. * Returns the world matrix of the node
  17748. * @returns a matrix containing the node's world matrix
  17749. */
  17750. Node.prototype.getWorldMatrix = function () {
  17751. return BABYLON.Matrix.Identity();
  17752. };
  17753. /** @hidden */
  17754. Node.prototype._getWorldMatrixDeterminant = function () {
  17755. return 1;
  17756. };
  17757. // override it in derived class if you add new variables to the cache
  17758. // and call the parent class method
  17759. /** @hidden */
  17760. Node.prototype._initCache = function () {
  17761. this._cache = {};
  17762. this._cache.parent = undefined;
  17763. };
  17764. /** @hidden */
  17765. Node.prototype.updateCache = function (force) {
  17766. if (!force && this.isSynchronized())
  17767. return;
  17768. this._cache.parent = this.parent;
  17769. this._updateCache();
  17770. };
  17771. // override it in derived class if you add new variables to the cache
  17772. // and call the parent class method if !ignoreParentClass
  17773. /** @hidden */
  17774. Node.prototype._updateCache = function (ignoreParentClass) {
  17775. };
  17776. // override it in derived class if you add new variables to the cache
  17777. /** @hidden */
  17778. Node.prototype._isSynchronized = function () {
  17779. return true;
  17780. };
  17781. /** @hidden */
  17782. Node.prototype._markSyncedWithParent = function () {
  17783. if (this.parent) {
  17784. this._parentRenderId = this.parent._childRenderId;
  17785. }
  17786. };
  17787. /** @hidden */
  17788. Node.prototype.isSynchronizedWithParent = function () {
  17789. if (!this.parent) {
  17790. return true;
  17791. }
  17792. if (this._parentRenderId !== this.parent._childRenderId) {
  17793. return false;
  17794. }
  17795. return this.parent.isSynchronized();
  17796. };
  17797. /** @hidden */
  17798. Node.prototype.isSynchronized = function (updateCache) {
  17799. var check = this.hasNewParent();
  17800. check = check || !this.isSynchronizedWithParent();
  17801. check = check || !this._isSynchronized();
  17802. if (updateCache)
  17803. this.updateCache(true);
  17804. return !check;
  17805. };
  17806. /** @hidden */
  17807. Node.prototype.hasNewParent = function (update) {
  17808. if (this._cache.parent === this.parent)
  17809. return false;
  17810. if (update)
  17811. this._cache.parent = this.parent;
  17812. return true;
  17813. };
  17814. /**
  17815. * Is this node ready to be used/rendered
  17816. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17817. * @return true if the node is ready
  17818. */
  17819. Node.prototype.isReady = function (completeCheck) {
  17820. if (completeCheck === void 0) { completeCheck = false; }
  17821. return this._isReady;
  17822. };
  17823. /**
  17824. * Is this node enabled?
  17825. * 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
  17826. * @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
  17827. * @return whether this node (and its parent) is enabled
  17828. */
  17829. Node.prototype.isEnabled = function (checkAncestors) {
  17830. if (checkAncestors === void 0) { checkAncestors = true; }
  17831. if (checkAncestors === false) {
  17832. return this._isEnabled;
  17833. }
  17834. if (this._isEnabled === false) {
  17835. return false;
  17836. }
  17837. if (this.parent !== undefined && this.parent !== null) {
  17838. return this.parent.isEnabled(checkAncestors);
  17839. }
  17840. return true;
  17841. };
  17842. /**
  17843. * Set the enabled state of this node
  17844. * @param value defines the new enabled state
  17845. */
  17846. Node.prototype.setEnabled = function (value) {
  17847. this._isEnabled = value;
  17848. };
  17849. /**
  17850. * Is this node a descendant of the given node?
  17851. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17852. * @param ancestor defines the parent node to inspect
  17853. * @returns a boolean indicating if this node is a descendant of the given node
  17854. */
  17855. Node.prototype.isDescendantOf = function (ancestor) {
  17856. if (this.parent) {
  17857. if (this.parent === ancestor) {
  17858. return true;
  17859. }
  17860. return this.parent.isDescendantOf(ancestor);
  17861. }
  17862. return false;
  17863. };
  17864. /** @hidden */
  17865. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17866. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17867. if (!this._children) {
  17868. return;
  17869. }
  17870. for (var index = 0; index < this._children.length; index++) {
  17871. var item = this._children[index];
  17872. if (!predicate || predicate(item)) {
  17873. results.push(item);
  17874. }
  17875. if (!directDescendantsOnly) {
  17876. item._getDescendants(results, false, predicate);
  17877. }
  17878. }
  17879. };
  17880. /**
  17881. * Will return all nodes that have this node as ascendant
  17882. * @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
  17883. * @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
  17884. * @return all children nodes of all types
  17885. */
  17886. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17887. var results = new Array();
  17888. this._getDescendants(results, directDescendantsOnly, predicate);
  17889. return results;
  17890. };
  17891. /**
  17892. * Get all child-meshes of this node
  17893. * @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
  17894. * @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
  17895. * @returns an array of {BABYLON.AbstractMesh}
  17896. */
  17897. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17898. var results = [];
  17899. this._getDescendants(results, directDescendantsOnly, function (node) {
  17900. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17901. });
  17902. return results;
  17903. };
  17904. /**
  17905. * Get all child-transformNodes of this node
  17906. * @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
  17907. * @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
  17908. * @returns an array of {BABYLON.TransformNode}
  17909. */
  17910. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17911. var results = [];
  17912. this._getDescendants(results, directDescendantsOnly, function (node) {
  17913. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17914. });
  17915. return results;
  17916. };
  17917. /**
  17918. * Get all direct children of this node
  17919. * @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
  17920. * @returns an array of {BABYLON.Node}
  17921. */
  17922. Node.prototype.getChildren = function (predicate) {
  17923. return this.getDescendants(true, predicate);
  17924. };
  17925. /** @hidden */
  17926. Node.prototype._setReady = function (state) {
  17927. if (state === this._isReady) {
  17928. return;
  17929. }
  17930. if (!state) {
  17931. this._isReady = false;
  17932. return;
  17933. }
  17934. if (this.onReady) {
  17935. this.onReady(this);
  17936. }
  17937. this._isReady = true;
  17938. };
  17939. /**
  17940. * Get an animation by name
  17941. * @param name defines the name of the animation to look for
  17942. * @returns null if not found else the requested animation
  17943. */
  17944. Node.prototype.getAnimationByName = function (name) {
  17945. for (var i = 0; i < this.animations.length; i++) {
  17946. var animation = this.animations[i];
  17947. if (animation.name === name) {
  17948. return animation;
  17949. }
  17950. }
  17951. return null;
  17952. };
  17953. /**
  17954. * Creates an animation range for this node
  17955. * @param name defines the name of the range
  17956. * @param from defines the starting key
  17957. * @param to defines the end key
  17958. */
  17959. Node.prototype.createAnimationRange = function (name, from, to) {
  17960. // check name not already in use
  17961. if (!this._ranges[name]) {
  17962. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17963. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17964. if (this.animations[i]) {
  17965. this.animations[i].createRange(name, from, to);
  17966. }
  17967. }
  17968. }
  17969. };
  17970. /**
  17971. * Delete a specific animation range
  17972. * @param name defines the name of the range to delete
  17973. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17974. */
  17975. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17976. if (deleteFrames === void 0) { deleteFrames = true; }
  17977. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17978. if (this.animations[i]) {
  17979. this.animations[i].deleteRange(name, deleteFrames);
  17980. }
  17981. }
  17982. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17983. };
  17984. /**
  17985. * Get an animation range by name
  17986. * @param name defines the name of the animation range to look for
  17987. * @returns null if not found else the requested animation range
  17988. */
  17989. Node.prototype.getAnimationRange = function (name) {
  17990. return this._ranges[name];
  17991. };
  17992. /**
  17993. * Will start the animation sequence
  17994. * @param name defines the range frames for animation sequence
  17995. * @param loop defines if the animation should loop (false by default)
  17996. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17997. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17998. * @returns the object created for this animation. If range does not exist, it will return null
  17999. */
  18000. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18001. var range = this.getAnimationRange(name);
  18002. if (!range) {
  18003. return null;
  18004. }
  18005. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18006. };
  18007. /**
  18008. * Serialize animation ranges into a JSON compatible object
  18009. * @returns serialization object
  18010. */
  18011. Node.prototype.serializeAnimationRanges = function () {
  18012. var serializationRanges = [];
  18013. for (var name in this._ranges) {
  18014. var localRange = this._ranges[name];
  18015. if (!localRange) {
  18016. continue;
  18017. }
  18018. var range = {};
  18019. range.name = name;
  18020. range.from = localRange.from;
  18021. range.to = localRange.to;
  18022. serializationRanges.push(range);
  18023. }
  18024. return serializationRanges;
  18025. };
  18026. /**
  18027. * Computes the world matrix of the node
  18028. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18029. * @returns the world matrix
  18030. */
  18031. Node.prototype.computeWorldMatrix = function (force) {
  18032. return BABYLON.Matrix.Identity();
  18033. };
  18034. /**
  18035. * Releases resources associated with this node.
  18036. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18037. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18038. */
  18039. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18040. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18041. if (!doNotRecurse) {
  18042. var nodes = this.getDescendants(true);
  18043. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18044. var node = nodes_1[_i];
  18045. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18046. }
  18047. }
  18048. else {
  18049. var transformNodes = this.getChildTransformNodes(true);
  18050. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18051. var transformNode = transformNodes_1[_a];
  18052. transformNode.parent = null;
  18053. transformNode.computeWorldMatrix(true);
  18054. }
  18055. }
  18056. this.parent = null;
  18057. // Callback
  18058. this.onDisposeObservable.notifyObservers(this);
  18059. this.onDisposeObservable.clear();
  18060. // Behaviors
  18061. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18062. var behavior = _c[_b];
  18063. behavior.detach();
  18064. }
  18065. this._behaviors = [];
  18066. this._isDisposed = true;
  18067. };
  18068. /**
  18069. * Parse animation range data from a serialization object and store them into a given node
  18070. * @param node defines where to store the animation ranges
  18071. * @param parsedNode defines the serialization object to read data from
  18072. * @param scene defines the hosting scene
  18073. */
  18074. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18075. if (parsedNode.ranges) {
  18076. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18077. var data = parsedNode.ranges[index];
  18078. node.createAnimationRange(data.name, data.from, data.to);
  18079. }
  18080. }
  18081. };
  18082. __decorate([
  18083. BABYLON.serialize()
  18084. ], Node.prototype, "name", void 0);
  18085. __decorate([
  18086. BABYLON.serialize()
  18087. ], Node.prototype, "id", void 0);
  18088. __decorate([
  18089. BABYLON.serialize()
  18090. ], Node.prototype, "uniqueId", void 0);
  18091. __decorate([
  18092. BABYLON.serialize()
  18093. ], Node.prototype, "state", void 0);
  18094. __decorate([
  18095. BABYLON.serialize()
  18096. ], Node.prototype, "metadata", void 0);
  18097. return Node;
  18098. }());
  18099. BABYLON.Node = Node;
  18100. })(BABYLON || (BABYLON = {}));
  18101. //# sourceMappingURL=babylon.node.js.map
  18102. var BABYLON;
  18103. (function (BABYLON) {
  18104. var BoundingSphere = /** @class */ (function () {
  18105. /**
  18106. * Creates a new bounding sphere
  18107. * @param min defines the minimum vector (in local space)
  18108. * @param max defines the maximum vector (in local space)
  18109. */
  18110. function BoundingSphere(min, max) {
  18111. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18112. this.reConstruct(min, max);
  18113. }
  18114. /**
  18115. * Recreates the entire bounding sphere from scratch
  18116. * @param min defines the new minimum vector (in local space)
  18117. * @param max defines the new maximum vector (in local space)
  18118. */
  18119. BoundingSphere.prototype.reConstruct = function (min, max) {
  18120. this.minimum = min.clone();
  18121. this.maximum = max.clone();
  18122. var distance = BABYLON.Vector3.Distance(min, max);
  18123. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18124. this.radius = distance * 0.5;
  18125. this.centerWorld = BABYLON.Vector3.Zero();
  18126. this._update(BABYLON.Matrix.Identity());
  18127. };
  18128. // Methods
  18129. BoundingSphere.prototype._update = function (world) {
  18130. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18131. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18132. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18133. };
  18134. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18135. for (var i = 0; i < 6; i++) {
  18136. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18137. return false;
  18138. }
  18139. return true;
  18140. };
  18141. BoundingSphere.prototype.intersectsPoint = function (point) {
  18142. var x = this.centerWorld.x - point.x;
  18143. var y = this.centerWorld.y - point.y;
  18144. var z = this.centerWorld.z - point.z;
  18145. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18146. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18147. return false;
  18148. return true;
  18149. };
  18150. // Statics
  18151. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18152. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18153. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18154. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18155. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18156. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18157. return false;
  18158. return true;
  18159. };
  18160. return BoundingSphere;
  18161. }());
  18162. BABYLON.BoundingSphere = BoundingSphere;
  18163. })(BABYLON || (BABYLON = {}));
  18164. //# sourceMappingURL=babylon.boundingSphere.js.map
  18165. var BABYLON;
  18166. (function (BABYLON) {
  18167. var BoundingBox = /** @class */ (function () {
  18168. /**
  18169. * Creates a new bounding box
  18170. * @param min defines the minimum vector (in local space)
  18171. * @param max defines the maximum vector (in local space)
  18172. */
  18173. function BoundingBox(min, max) {
  18174. this.vectorsWorld = new Array();
  18175. this.reConstruct(min, max);
  18176. }
  18177. // Methods
  18178. /**
  18179. * Recreates the entire bounding box from scratch
  18180. * @param min defines the new minimum vector (in local space)
  18181. * @param max defines the new maximum vector (in local space)
  18182. */
  18183. BoundingBox.prototype.reConstruct = function (min, max) {
  18184. this.minimum = min.clone();
  18185. this.maximum = max.clone();
  18186. // Bounding vectors
  18187. this.vectors = new Array();
  18188. this.vectors.push(this.minimum.clone());
  18189. this.vectors.push(this.maximum.clone());
  18190. this.vectors.push(this.minimum.clone());
  18191. this.vectors[2].x = this.maximum.x;
  18192. this.vectors.push(this.minimum.clone());
  18193. this.vectors[3].y = this.maximum.y;
  18194. this.vectors.push(this.minimum.clone());
  18195. this.vectors[4].z = this.maximum.z;
  18196. this.vectors.push(this.maximum.clone());
  18197. this.vectors[5].z = this.minimum.z;
  18198. this.vectors.push(this.maximum.clone());
  18199. this.vectors[6].x = this.minimum.x;
  18200. this.vectors.push(this.maximum.clone());
  18201. this.vectors[7].y = this.minimum.y;
  18202. // OBB
  18203. this.center = this.maximum.add(this.minimum).scale(0.5);
  18204. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18205. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18206. // World
  18207. for (var index = 0; index < this.vectors.length; index++) {
  18208. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18209. }
  18210. this.minimumWorld = BABYLON.Vector3.Zero();
  18211. this.maximumWorld = BABYLON.Vector3.Zero();
  18212. this.centerWorld = BABYLON.Vector3.Zero();
  18213. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18214. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18215. };
  18216. BoundingBox.prototype.getWorldMatrix = function () {
  18217. return this._worldMatrix;
  18218. };
  18219. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18220. this._worldMatrix.copyFrom(matrix);
  18221. return this;
  18222. };
  18223. BoundingBox.prototype._update = function (world) {
  18224. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18225. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18226. for (var index = 0; index < this.vectors.length; index++) {
  18227. var v = this.vectorsWorld[index];
  18228. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18229. if (v.x < this.minimumWorld.x)
  18230. this.minimumWorld.x = v.x;
  18231. if (v.y < this.minimumWorld.y)
  18232. this.minimumWorld.y = v.y;
  18233. if (v.z < this.minimumWorld.z)
  18234. this.minimumWorld.z = v.z;
  18235. if (v.x > this.maximumWorld.x)
  18236. this.maximumWorld.x = v.x;
  18237. if (v.y > this.maximumWorld.y)
  18238. this.maximumWorld.y = v.y;
  18239. if (v.z > this.maximumWorld.z)
  18240. this.maximumWorld.z = v.z;
  18241. }
  18242. // Extend
  18243. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18244. this.extendSizeWorld.scaleInPlace(0.5);
  18245. // OBB
  18246. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18247. this.centerWorld.scaleInPlace(0.5);
  18248. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18249. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18250. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18251. this._worldMatrix = world;
  18252. };
  18253. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18254. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18255. };
  18256. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18257. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18258. };
  18259. BoundingBox.prototype.intersectsPoint = function (point) {
  18260. var delta = -BABYLON.Epsilon;
  18261. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18262. return false;
  18263. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18264. return false;
  18265. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18266. return false;
  18267. return true;
  18268. };
  18269. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18270. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18271. };
  18272. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18273. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18274. return false;
  18275. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18276. return false;
  18277. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18278. return false;
  18279. return true;
  18280. };
  18281. // Statics
  18282. BoundingBox.Intersects = function (box0, box1) {
  18283. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18284. return false;
  18285. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18286. return false;
  18287. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18288. return false;
  18289. return true;
  18290. };
  18291. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18292. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18293. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18294. return (num <= (sphereRadius * sphereRadius));
  18295. };
  18296. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18297. for (var p = 0; p < 6; p++) {
  18298. for (var i = 0; i < 8; i++) {
  18299. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18300. return false;
  18301. }
  18302. }
  18303. }
  18304. return true;
  18305. };
  18306. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18307. for (var p = 0; p < 6; p++) {
  18308. var inCount = 8;
  18309. for (var i = 0; i < 8; i++) {
  18310. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18311. --inCount;
  18312. }
  18313. else {
  18314. break;
  18315. }
  18316. }
  18317. if (inCount === 0)
  18318. return false;
  18319. }
  18320. return true;
  18321. };
  18322. return BoundingBox;
  18323. }());
  18324. BABYLON.BoundingBox = BoundingBox;
  18325. })(BABYLON || (BABYLON = {}));
  18326. //# sourceMappingURL=babylon.boundingBox.js.map
  18327. var BABYLON;
  18328. (function (BABYLON) {
  18329. var computeBoxExtents = function (axis, box) {
  18330. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18331. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18332. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18333. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18334. var r = r0 + r1 + r2;
  18335. return {
  18336. min: p - r,
  18337. max: p + r
  18338. };
  18339. };
  18340. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18341. var axisOverlap = function (axis, box0, box1) {
  18342. var result0 = computeBoxExtents(axis, box0);
  18343. var result1 = computeBoxExtents(axis, box1);
  18344. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18345. };
  18346. var BoundingInfo = /** @class */ (function () {
  18347. function BoundingInfo(minimum, maximum) {
  18348. this.minimum = minimum;
  18349. this.maximum = maximum;
  18350. this._isLocked = false;
  18351. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18352. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18353. }
  18354. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18355. get: function () {
  18356. return this._isLocked;
  18357. },
  18358. set: function (value) {
  18359. this._isLocked = value;
  18360. },
  18361. enumerable: true,
  18362. configurable: true
  18363. });
  18364. // Methods
  18365. BoundingInfo.prototype.update = function (world) {
  18366. if (this._isLocked) {
  18367. return;
  18368. }
  18369. this.boundingBox._update(world);
  18370. this.boundingSphere._update(world);
  18371. };
  18372. /**
  18373. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18374. * @param center New center of the bounding info
  18375. * @param extend New extend of the bounding info
  18376. */
  18377. BoundingInfo.prototype.centerOn = function (center, extend) {
  18378. this.minimum = center.subtract(extend);
  18379. this.maximum = center.add(extend);
  18380. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18381. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18382. return this;
  18383. };
  18384. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18385. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18386. return false;
  18387. return this.boundingBox.isInFrustum(frustumPlanes);
  18388. };
  18389. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18390. /**
  18391. * Gets the world distance between the min and max points of the bounding box
  18392. */
  18393. get: function () {
  18394. var boundingBox = this.boundingBox;
  18395. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18396. return size.length();
  18397. },
  18398. enumerable: true,
  18399. configurable: true
  18400. });
  18401. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18402. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18403. };
  18404. BoundingInfo.prototype._checkCollision = function (collider) {
  18405. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18406. };
  18407. BoundingInfo.prototype.intersectsPoint = function (point) {
  18408. if (!this.boundingSphere.centerWorld) {
  18409. return false;
  18410. }
  18411. if (!this.boundingSphere.intersectsPoint(point)) {
  18412. return false;
  18413. }
  18414. if (!this.boundingBox.intersectsPoint(point)) {
  18415. return false;
  18416. }
  18417. return true;
  18418. };
  18419. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18420. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18421. return false;
  18422. }
  18423. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18424. return false;
  18425. }
  18426. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18427. return false;
  18428. }
  18429. if (!precise) {
  18430. return true;
  18431. }
  18432. var box0 = this.boundingBox;
  18433. var box1 = boundingInfo.boundingBox;
  18434. if (!axisOverlap(box0.directions[0], box0, box1))
  18435. return false;
  18436. if (!axisOverlap(box0.directions[1], box0, box1))
  18437. return false;
  18438. if (!axisOverlap(box0.directions[2], box0, box1))
  18439. return false;
  18440. if (!axisOverlap(box1.directions[0], box0, box1))
  18441. return false;
  18442. if (!axisOverlap(box1.directions[1], box0, box1))
  18443. return false;
  18444. if (!axisOverlap(box1.directions[2], box0, box1))
  18445. return false;
  18446. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18447. return false;
  18448. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18449. return false;
  18450. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18451. return false;
  18452. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18453. return false;
  18454. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18455. return false;
  18456. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18457. return false;
  18458. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18459. return false;
  18460. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18461. return false;
  18462. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18463. return false;
  18464. return true;
  18465. };
  18466. return BoundingInfo;
  18467. }());
  18468. BABYLON.BoundingInfo = BoundingInfo;
  18469. })(BABYLON || (BABYLON = {}));
  18470. //# sourceMappingURL=babylon.boundingInfo.js.map
  18471. var BABYLON;
  18472. (function (BABYLON) {
  18473. var TransformNode = /** @class */ (function (_super) {
  18474. __extends(TransformNode, _super);
  18475. function TransformNode(name, scene, isPure) {
  18476. if (scene === void 0) { scene = null; }
  18477. if (isPure === void 0) { isPure = true; }
  18478. var _this = _super.call(this, name, scene) || this;
  18479. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18480. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18481. _this._up = new BABYLON.Vector3(0, 1, 0);
  18482. _this._right = new BABYLON.Vector3(1, 0, 0);
  18483. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18484. // Properties
  18485. _this._rotation = BABYLON.Vector3.Zero();
  18486. _this._scaling = BABYLON.Vector3.One();
  18487. _this._isDirty = false;
  18488. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18489. _this.scalingDeterminant = 1;
  18490. _this.infiniteDistance = false;
  18491. _this.position = BABYLON.Vector3.Zero();
  18492. _this._localWorld = BABYLON.Matrix.Zero();
  18493. _this._worldMatrix = BABYLON.Matrix.Zero();
  18494. _this._worldMatrixDeterminant = 0;
  18495. _this._absolutePosition = BABYLON.Vector3.Zero();
  18496. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18497. _this._postMultiplyPivotMatrix = false;
  18498. _this._isWorldMatrixFrozen = false;
  18499. /**
  18500. * An event triggered after the world matrix is updated
  18501. */
  18502. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18503. _this._nonUniformScaling = false;
  18504. if (isPure) {
  18505. _this.getScene().addTransformNode(_this);
  18506. }
  18507. return _this;
  18508. }
  18509. /**
  18510. * Gets a string idenfifying the name of the class
  18511. * @returns "TransformNode" string
  18512. */
  18513. TransformNode.prototype.getClassName = function () {
  18514. return "TransformNode";
  18515. };
  18516. Object.defineProperty(TransformNode.prototype, "rotation", {
  18517. /**
  18518. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18519. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18520. * Default : (0.0, 0.0, 0.0)
  18521. */
  18522. get: function () {
  18523. return this._rotation;
  18524. },
  18525. set: function (newRotation) {
  18526. this._rotation = newRotation;
  18527. },
  18528. enumerable: true,
  18529. configurable: true
  18530. });
  18531. Object.defineProperty(TransformNode.prototype, "scaling", {
  18532. /**
  18533. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18534. * Default : (1.0, 1.0, 1.0)
  18535. */
  18536. get: function () {
  18537. return this._scaling;
  18538. },
  18539. /**
  18540. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18541. * Default : (1.0, 1.0, 1.0)
  18542. */
  18543. set: function (newScaling) {
  18544. this._scaling = newScaling;
  18545. },
  18546. enumerable: true,
  18547. configurable: true
  18548. });
  18549. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18550. /**
  18551. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18552. * It's null by default.
  18553. * 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)
  18554. */
  18555. get: function () {
  18556. return this._rotationQuaternion;
  18557. },
  18558. set: function (quaternion) {
  18559. this._rotationQuaternion = quaternion;
  18560. //reset the rotation vector.
  18561. if (quaternion && this.rotation.length()) {
  18562. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18563. }
  18564. },
  18565. enumerable: true,
  18566. configurable: true
  18567. });
  18568. Object.defineProperty(TransformNode.prototype, "forward", {
  18569. /**
  18570. * The forward direction of that transform in world space.
  18571. */
  18572. get: function () {
  18573. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18574. },
  18575. enumerable: true,
  18576. configurable: true
  18577. });
  18578. Object.defineProperty(TransformNode.prototype, "up", {
  18579. /**
  18580. * The up direction of that transform in world space.
  18581. */
  18582. get: function () {
  18583. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18584. },
  18585. enumerable: true,
  18586. configurable: true
  18587. });
  18588. Object.defineProperty(TransformNode.prototype, "right", {
  18589. /**
  18590. * The right direction of that transform in world space.
  18591. */
  18592. get: function () {
  18593. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18594. },
  18595. enumerable: true,
  18596. configurable: true
  18597. });
  18598. /**
  18599. * Returns the latest update of the World matrix
  18600. * Returns a Matrix.
  18601. */
  18602. TransformNode.prototype.getWorldMatrix = function () {
  18603. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18604. this.computeWorldMatrix();
  18605. }
  18606. return this._worldMatrix;
  18607. };
  18608. /** @hidden */
  18609. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18610. return this._worldMatrixDeterminant;
  18611. };
  18612. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18613. /**
  18614. * Returns directly the latest state of the mesh World matrix.
  18615. * A Matrix is returned.
  18616. */
  18617. get: function () {
  18618. return this._worldMatrix;
  18619. },
  18620. enumerable: true,
  18621. configurable: true
  18622. });
  18623. /**
  18624. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18625. * Returns the TransformNode.
  18626. */
  18627. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18628. this._poseMatrix.copyFrom(matrix);
  18629. return this;
  18630. };
  18631. /**
  18632. * Returns the mesh Pose matrix.
  18633. * Returned object : Matrix
  18634. */
  18635. TransformNode.prototype.getPoseMatrix = function () {
  18636. return this._poseMatrix;
  18637. };
  18638. TransformNode.prototype._isSynchronized = function () {
  18639. if (this._isDirty) {
  18640. return false;
  18641. }
  18642. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18643. return false;
  18644. if (this._cache.pivotMatrixUpdated) {
  18645. return false;
  18646. }
  18647. if (this.infiniteDistance) {
  18648. return false;
  18649. }
  18650. if (!this._cache.position.equals(this.position))
  18651. return false;
  18652. if (this.rotationQuaternion) {
  18653. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18654. return false;
  18655. }
  18656. if (!this._cache.rotation.equals(this.rotation))
  18657. return false;
  18658. if (!this._cache.scaling.equals(this.scaling))
  18659. return false;
  18660. return true;
  18661. };
  18662. TransformNode.prototype._initCache = function () {
  18663. _super.prototype._initCache.call(this);
  18664. this._cache.localMatrixUpdated = false;
  18665. this._cache.position = BABYLON.Vector3.Zero();
  18666. this._cache.scaling = BABYLON.Vector3.Zero();
  18667. this._cache.rotation = BABYLON.Vector3.Zero();
  18668. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18669. this._cache.billboardMode = -1;
  18670. };
  18671. TransformNode.prototype.markAsDirty = function (property) {
  18672. if (property === "rotation") {
  18673. this.rotationQuaternion = null;
  18674. }
  18675. this._currentRenderId = Number.MAX_VALUE;
  18676. this._isDirty = true;
  18677. return this;
  18678. };
  18679. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18680. /**
  18681. * Returns the current mesh absolute position.
  18682. * Retuns a Vector3.
  18683. */
  18684. get: function () {
  18685. return this._absolutePosition;
  18686. },
  18687. enumerable: true,
  18688. configurable: true
  18689. });
  18690. /**
  18691. * Sets a new matrix to apply before all other transformation
  18692. * @param matrix defines the transform matrix
  18693. * @returns the current TransformNode
  18694. */
  18695. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18696. return this.setPivotMatrix(matrix, false);
  18697. };
  18698. /**
  18699. * Sets a new pivot matrix to the current node
  18700. * @param matrix defines the new pivot matrix to use
  18701. * @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
  18702. * @returns the current TransformNode
  18703. */
  18704. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18705. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18706. this._pivotMatrix = matrix.clone();
  18707. this._cache.pivotMatrixUpdated = true;
  18708. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18709. if (this._postMultiplyPivotMatrix) {
  18710. if (!this._pivotMatrixInverse) {
  18711. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18712. }
  18713. else {
  18714. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18715. }
  18716. }
  18717. return this;
  18718. };
  18719. /**
  18720. * Returns the mesh pivot matrix.
  18721. * Default : Identity.
  18722. * A Matrix is returned.
  18723. */
  18724. TransformNode.prototype.getPivotMatrix = function () {
  18725. return this._pivotMatrix;
  18726. };
  18727. /**
  18728. * Prevents the World matrix to be computed any longer.
  18729. * Returns the TransformNode.
  18730. */
  18731. TransformNode.prototype.freezeWorldMatrix = function () {
  18732. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18733. this.computeWorldMatrix(true);
  18734. this._isWorldMatrixFrozen = true;
  18735. return this;
  18736. };
  18737. /**
  18738. * Allows back the World matrix computation.
  18739. * Returns the TransformNode.
  18740. */
  18741. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18742. this._isWorldMatrixFrozen = false;
  18743. this.computeWorldMatrix(true);
  18744. return this;
  18745. };
  18746. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18747. /**
  18748. * True if the World matrix has been frozen.
  18749. * Returns a boolean.
  18750. */
  18751. get: function () {
  18752. return this._isWorldMatrixFrozen;
  18753. },
  18754. enumerable: true,
  18755. configurable: true
  18756. });
  18757. /**
  18758. * Retuns the mesh absolute position in the World.
  18759. * Returns a Vector3.
  18760. */
  18761. TransformNode.prototype.getAbsolutePosition = function () {
  18762. this.computeWorldMatrix();
  18763. return this._absolutePosition;
  18764. };
  18765. /**
  18766. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18767. * Returns the TransformNode.
  18768. */
  18769. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18770. if (!absolutePosition) {
  18771. return this;
  18772. }
  18773. var absolutePositionX;
  18774. var absolutePositionY;
  18775. var absolutePositionZ;
  18776. if (absolutePosition.x === undefined) {
  18777. if (arguments.length < 3) {
  18778. return this;
  18779. }
  18780. absolutePositionX = arguments[0];
  18781. absolutePositionY = arguments[1];
  18782. absolutePositionZ = arguments[2];
  18783. }
  18784. else {
  18785. absolutePositionX = absolutePosition.x;
  18786. absolutePositionY = absolutePosition.y;
  18787. absolutePositionZ = absolutePosition.z;
  18788. }
  18789. if (this.parent) {
  18790. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18791. invertParentWorldMatrix.invert();
  18792. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18793. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18794. }
  18795. else {
  18796. this.position.x = absolutePositionX;
  18797. this.position.y = absolutePositionY;
  18798. this.position.z = absolutePositionZ;
  18799. }
  18800. return this;
  18801. };
  18802. /**
  18803. * Sets the mesh position in its local space.
  18804. * Returns the TransformNode.
  18805. */
  18806. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18807. this.computeWorldMatrix();
  18808. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18809. return this;
  18810. };
  18811. /**
  18812. * Returns the mesh position in the local space from the current World matrix values.
  18813. * Returns a new Vector3.
  18814. */
  18815. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18816. this.computeWorldMatrix();
  18817. var invLocalWorldMatrix = this._localWorld.clone();
  18818. invLocalWorldMatrix.invert();
  18819. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18820. };
  18821. /**
  18822. * Translates the mesh along the passed Vector3 in its local space.
  18823. * Returns the TransformNode.
  18824. */
  18825. TransformNode.prototype.locallyTranslate = function (vector3) {
  18826. this.computeWorldMatrix(true);
  18827. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18828. return this;
  18829. };
  18830. /**
  18831. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18832. * @param targetPoint the position (must be in same space as current mesh) to look at
  18833. * @param yawCor optional yaw (y-axis) correction in radians
  18834. * @param pitchCor optional pitch (x-axis) correction in radians
  18835. * @param rollCor optional roll (z-axis) correction in radians
  18836. * @param space the choosen space of the target
  18837. * @returns the TransformNode.
  18838. */
  18839. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18840. if (yawCor === void 0) { yawCor = 0; }
  18841. if (pitchCor === void 0) { pitchCor = 0; }
  18842. if (rollCor === void 0) { rollCor = 0; }
  18843. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18844. var dv = TransformNode._lookAtVectorCache;
  18845. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18846. targetPoint.subtractToRef(pos, dv);
  18847. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18848. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18849. var pitch = Math.atan2(dv.y, len);
  18850. if (this.rotationQuaternion) {
  18851. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18852. }
  18853. else {
  18854. this.rotation.x = pitch + pitchCor;
  18855. this.rotation.y = yaw + yawCor;
  18856. this.rotation.z = rollCor;
  18857. }
  18858. return this;
  18859. };
  18860. /**
  18861. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18862. * This Vector3 is expressed in the World space.
  18863. */
  18864. TransformNode.prototype.getDirection = function (localAxis) {
  18865. var result = BABYLON.Vector3.Zero();
  18866. this.getDirectionToRef(localAxis, result);
  18867. return result;
  18868. };
  18869. /**
  18870. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18871. * localAxis is expressed in the mesh local space.
  18872. * result is computed in the Wordl space from the mesh World matrix.
  18873. * Returns the TransformNode.
  18874. */
  18875. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18876. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18877. return this;
  18878. };
  18879. /**
  18880. * Sets a new pivot point to the current node
  18881. * @param point defines the new pivot point to use
  18882. * @param space defines if the point is in world or local space (local by default)
  18883. * @returns the current TransformNode
  18884. */
  18885. TransformNode.prototype.setPivotPoint = function (point, space) {
  18886. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18887. if (this.getScene().getRenderId() == 0) {
  18888. this.computeWorldMatrix(true);
  18889. }
  18890. var wm = this.getWorldMatrix();
  18891. if (space == BABYLON.Space.WORLD) {
  18892. var tmat = BABYLON.Tmp.Matrix[0];
  18893. wm.invertToRef(tmat);
  18894. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18895. }
  18896. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18897. };
  18898. /**
  18899. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18900. */
  18901. TransformNode.prototype.getPivotPoint = function () {
  18902. var point = BABYLON.Vector3.Zero();
  18903. this.getPivotPointToRef(point);
  18904. return point;
  18905. };
  18906. /**
  18907. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18908. * Returns the TransformNode.
  18909. */
  18910. TransformNode.prototype.getPivotPointToRef = function (result) {
  18911. result.x = -this._pivotMatrix.m[12];
  18912. result.y = -this._pivotMatrix.m[13];
  18913. result.z = -this._pivotMatrix.m[14];
  18914. return this;
  18915. };
  18916. /**
  18917. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18918. */
  18919. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18920. var point = BABYLON.Vector3.Zero();
  18921. this.getAbsolutePivotPointToRef(point);
  18922. return point;
  18923. };
  18924. /**
  18925. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18926. * Returns the TransformNode.
  18927. */
  18928. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18929. result.x = this._pivotMatrix.m[12];
  18930. result.y = this._pivotMatrix.m[13];
  18931. result.z = this._pivotMatrix.m[14];
  18932. this.getPivotPointToRef(result);
  18933. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18934. return this;
  18935. };
  18936. /**
  18937. * Defines the passed node as the parent of the current node.
  18938. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18939. * Returns the TransformNode.
  18940. */
  18941. TransformNode.prototype.setParent = function (node) {
  18942. if (node === null) {
  18943. var rotation = BABYLON.Tmp.Quaternion[0];
  18944. var position = BABYLON.Tmp.Vector3[0];
  18945. var scale = BABYLON.Tmp.Vector3[1];
  18946. if (this.parent && this.parent.computeWorldMatrix) {
  18947. this.parent.computeWorldMatrix(true);
  18948. }
  18949. this.computeWorldMatrix(true);
  18950. this.getWorldMatrix().decompose(scale, rotation, position);
  18951. if (this.rotationQuaternion) {
  18952. this.rotationQuaternion.copyFrom(rotation);
  18953. }
  18954. else {
  18955. rotation.toEulerAnglesToRef(this.rotation);
  18956. }
  18957. this.scaling.x = scale.x;
  18958. this.scaling.y = scale.y;
  18959. this.scaling.z = scale.z;
  18960. this.position.x = position.x;
  18961. this.position.y = position.y;
  18962. this.position.z = position.z;
  18963. }
  18964. else {
  18965. var rotation = BABYLON.Tmp.Quaternion[0];
  18966. var position = BABYLON.Tmp.Vector3[0];
  18967. var scale = BABYLON.Tmp.Vector3[1];
  18968. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18969. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18970. this.computeWorldMatrix(true);
  18971. node.computeWorldMatrix(true);
  18972. node.getWorldMatrix().invertToRef(invParentMatrix);
  18973. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18974. diffMatrix.decompose(scale, rotation, position);
  18975. if (this.rotationQuaternion) {
  18976. this.rotationQuaternion.copyFrom(rotation);
  18977. }
  18978. else {
  18979. rotation.toEulerAnglesToRef(this.rotation);
  18980. }
  18981. this.position.x = position.x;
  18982. this.position.y = position.y;
  18983. this.position.z = position.z;
  18984. this.scaling.x = scale.x;
  18985. this.scaling.y = scale.y;
  18986. this.scaling.z = scale.z;
  18987. }
  18988. this.parent = node;
  18989. return this;
  18990. };
  18991. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18992. get: function () {
  18993. return this._nonUniformScaling;
  18994. },
  18995. enumerable: true,
  18996. configurable: true
  18997. });
  18998. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18999. if (this._nonUniformScaling === value) {
  19000. return false;
  19001. }
  19002. this._nonUniformScaling = true;
  19003. return true;
  19004. };
  19005. /**
  19006. * Attach the current TransformNode to another TransformNode associated with a bone
  19007. * @param bone Bone affecting the TransformNode
  19008. * @param affectedTransformNode TransformNode associated with the bone
  19009. */
  19010. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19011. this._transformToBoneReferal = affectedTransformNode;
  19012. this.parent = bone;
  19013. if (bone.getWorldMatrix().determinant() < 0) {
  19014. this.scalingDeterminant *= -1;
  19015. }
  19016. return this;
  19017. };
  19018. TransformNode.prototype.detachFromBone = function () {
  19019. if (!this.parent) {
  19020. return this;
  19021. }
  19022. if (this.parent.getWorldMatrix().determinant() < 0) {
  19023. this.scalingDeterminant *= -1;
  19024. }
  19025. this._transformToBoneReferal = null;
  19026. this.parent = null;
  19027. return this;
  19028. };
  19029. /**
  19030. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19031. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19032. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19033. * The passed axis is also normalized.
  19034. * Returns the TransformNode.
  19035. */
  19036. TransformNode.prototype.rotate = function (axis, amount, space) {
  19037. axis.normalize();
  19038. if (!this.rotationQuaternion) {
  19039. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19040. this.rotation = BABYLON.Vector3.Zero();
  19041. }
  19042. var rotationQuaternion;
  19043. if (!space || space === BABYLON.Space.LOCAL) {
  19044. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19045. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19046. }
  19047. else {
  19048. if (this.parent) {
  19049. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19050. invertParentWorldMatrix.invert();
  19051. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19052. }
  19053. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19054. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19055. }
  19056. return this;
  19057. };
  19058. /**
  19059. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19060. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19061. * The passed axis is also normalized.
  19062. * Returns the TransformNode.
  19063. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19064. */
  19065. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19066. axis.normalize();
  19067. if (!this.rotationQuaternion) {
  19068. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19069. this.rotation.copyFromFloats(0, 0, 0);
  19070. }
  19071. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19072. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19073. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19074. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19075. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19076. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19077. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19078. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19079. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19080. return this;
  19081. };
  19082. /**
  19083. * Translates the mesh along the axis vector for the passed distance in the given space.
  19084. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19085. * Returns the TransformNode.
  19086. */
  19087. TransformNode.prototype.translate = function (axis, distance, space) {
  19088. var displacementVector = axis.scale(distance);
  19089. if (!space || space === BABYLON.Space.LOCAL) {
  19090. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19091. this.setPositionWithLocalVector(tempV3);
  19092. }
  19093. else {
  19094. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19095. }
  19096. return this;
  19097. };
  19098. /**
  19099. * Adds a rotation step to the mesh current rotation.
  19100. * x, y, z are Euler angles expressed in radians.
  19101. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19102. * This means this rotation is made in the mesh local space only.
  19103. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19104. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19105. * ```javascript
  19106. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19107. * ```
  19108. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19109. * 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.
  19110. * Returns the TransformNode.
  19111. */
  19112. TransformNode.prototype.addRotation = function (x, y, z) {
  19113. var rotationQuaternion;
  19114. if (this.rotationQuaternion) {
  19115. rotationQuaternion = this.rotationQuaternion;
  19116. }
  19117. else {
  19118. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19119. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19120. }
  19121. var accumulation = BABYLON.Tmp.Quaternion[0];
  19122. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19123. rotationQuaternion.multiplyInPlace(accumulation);
  19124. if (!this.rotationQuaternion) {
  19125. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19126. }
  19127. return this;
  19128. };
  19129. /**
  19130. * Computes the mesh World matrix and returns it.
  19131. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19132. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19133. * If the parameter `force`is set to `true`, the actual computation is done.
  19134. * Returns the mesh World Matrix.
  19135. */
  19136. TransformNode.prototype.computeWorldMatrix = function (force) {
  19137. if (this._isWorldMatrixFrozen) {
  19138. return this._worldMatrix;
  19139. }
  19140. if (!force && this.isSynchronized(true)) {
  19141. this._currentRenderId = this.getScene().getRenderId();
  19142. return this._worldMatrix;
  19143. }
  19144. this._cache.position.copyFrom(this.position);
  19145. this._cache.scaling.copyFrom(this.scaling);
  19146. this._cache.pivotMatrixUpdated = false;
  19147. this._cache.billboardMode = this.billboardMode;
  19148. this._currentRenderId = this.getScene().getRenderId();
  19149. this._childRenderId = this.getScene().getRenderId();
  19150. this._isDirty = false;
  19151. // Scaling
  19152. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19153. // Rotation
  19154. //rotate, if quaternion is set and rotation was used
  19155. if (this.rotationQuaternion) {
  19156. var len = this.rotation.length();
  19157. if (len) {
  19158. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19159. this.rotation.copyFromFloats(0, 0, 0);
  19160. }
  19161. }
  19162. if (this.rotationQuaternion) {
  19163. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19164. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19165. }
  19166. else {
  19167. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19168. this._cache.rotation.copyFrom(this.rotation);
  19169. }
  19170. // Translation
  19171. var camera = this.getScene().activeCamera;
  19172. if (this.infiniteDistance && !this.parent && camera) {
  19173. var cameraWorldMatrix = camera.getWorldMatrix();
  19174. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19175. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19176. }
  19177. else {
  19178. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19179. }
  19180. // Composing transformations
  19181. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19182. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19183. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19184. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19185. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19186. // Need to decompose each rotation here
  19187. var currentPosition = BABYLON.Tmp.Vector3[3];
  19188. if (this.parent && this.parent.getWorldMatrix) {
  19189. if (this._transformToBoneReferal) {
  19190. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19191. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19192. }
  19193. else {
  19194. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19195. }
  19196. }
  19197. else {
  19198. currentPosition.copyFrom(this.position);
  19199. }
  19200. currentPosition.subtractInPlace(camera.globalPosition);
  19201. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19202. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19203. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19204. }
  19205. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19206. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19207. }
  19208. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19209. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19210. }
  19211. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19212. }
  19213. else {
  19214. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19215. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19216. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19217. }
  19218. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19219. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19220. }
  19221. // Local world
  19222. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19223. // Parent
  19224. if (this.parent && this.parent.getWorldMatrix) {
  19225. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19226. if (this._transformToBoneReferal) {
  19227. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19228. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19229. }
  19230. else {
  19231. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19232. }
  19233. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19234. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19235. this._worldMatrix.copyFrom(this._localWorld);
  19236. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19237. }
  19238. else {
  19239. if (this._transformToBoneReferal) {
  19240. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19241. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19242. }
  19243. else {
  19244. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19245. }
  19246. }
  19247. this._markSyncedWithParent();
  19248. }
  19249. else {
  19250. this._worldMatrix.copyFrom(this._localWorld);
  19251. }
  19252. // Post multiply inverse of pivotMatrix
  19253. if (this._postMultiplyPivotMatrix) {
  19254. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19255. }
  19256. // Normal matrix
  19257. if (this.scaling.isNonUniform) {
  19258. this._updateNonUniformScalingState(true);
  19259. }
  19260. else if (this.parent && this.parent._nonUniformScaling) {
  19261. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19262. }
  19263. else {
  19264. this._updateNonUniformScalingState(false);
  19265. }
  19266. this._afterComputeWorldMatrix();
  19267. // Absolute position
  19268. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19269. // Callbacks
  19270. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19271. if (!this._poseMatrix) {
  19272. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19273. }
  19274. // Cache the determinant
  19275. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19276. return this._worldMatrix;
  19277. };
  19278. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19279. };
  19280. /**
  19281. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19282. * @param func: callback function to add
  19283. *
  19284. * Returns the TransformNode.
  19285. */
  19286. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19287. this.onAfterWorldMatrixUpdateObservable.add(func);
  19288. return this;
  19289. };
  19290. /**
  19291. * Removes a registered callback function.
  19292. * Returns the TransformNode.
  19293. */
  19294. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19295. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19296. return this;
  19297. };
  19298. /**
  19299. * Clone the current transform node
  19300. * Returns the new transform node
  19301. * @param name Name of the new clone
  19302. * @param newParent New parent for the clone
  19303. * @param doNotCloneChildren Do not clone children hierarchy
  19304. */
  19305. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19306. var _this = this;
  19307. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19308. result.name = name;
  19309. result.id = name;
  19310. if (newParent) {
  19311. result.parent = newParent;
  19312. }
  19313. if (!doNotCloneChildren) {
  19314. // Children
  19315. var directDescendants = this.getDescendants(true);
  19316. for (var index = 0; index < directDescendants.length; index++) {
  19317. var child = directDescendants[index];
  19318. if (child.clone) {
  19319. child.clone(name + "." + child.name, result);
  19320. }
  19321. }
  19322. }
  19323. return result;
  19324. };
  19325. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19326. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19327. serializationObject.type = this.getClassName();
  19328. // Parent
  19329. if (this.parent) {
  19330. serializationObject.parentId = this.parent.id;
  19331. }
  19332. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19333. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19334. }
  19335. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19336. serializationObject.isEnabled = this.isEnabled();
  19337. // Parent
  19338. if (this.parent) {
  19339. serializationObject.parentId = this.parent.id;
  19340. }
  19341. return serializationObject;
  19342. };
  19343. // Statics
  19344. /**
  19345. * Returns a new TransformNode object parsed from the source provided.
  19346. * The parameter `parsedMesh` is the source.
  19347. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19348. */
  19349. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19350. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19351. if (BABYLON.Tags) {
  19352. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19353. }
  19354. if (parsedTransformNode.localMatrix) {
  19355. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19356. }
  19357. else if (parsedTransformNode.pivotMatrix) {
  19358. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19359. }
  19360. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19361. // Parent
  19362. if (parsedTransformNode.parentId) {
  19363. transformNode._waitingParentId = parsedTransformNode.parentId;
  19364. }
  19365. return transformNode;
  19366. };
  19367. /**
  19368. * Releases resources associated with this transform node.
  19369. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19370. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19371. */
  19372. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19373. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19374. // Animations
  19375. this.getScene().stopAnimation(this);
  19376. // Remove from scene
  19377. this.getScene().removeTransformNode(this);
  19378. this.onAfterWorldMatrixUpdateObservable.clear();
  19379. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19380. };
  19381. // Statics
  19382. TransformNode.BILLBOARDMODE_NONE = 0;
  19383. TransformNode.BILLBOARDMODE_X = 1;
  19384. TransformNode.BILLBOARDMODE_Y = 2;
  19385. TransformNode.BILLBOARDMODE_Z = 4;
  19386. TransformNode.BILLBOARDMODE_ALL = 7;
  19387. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19388. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19389. __decorate([
  19390. BABYLON.serializeAsVector3()
  19391. ], TransformNode.prototype, "_rotation", void 0);
  19392. __decorate([
  19393. BABYLON.serializeAsQuaternion()
  19394. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19395. __decorate([
  19396. BABYLON.serializeAsVector3()
  19397. ], TransformNode.prototype, "_scaling", void 0);
  19398. __decorate([
  19399. BABYLON.serialize()
  19400. ], TransformNode.prototype, "billboardMode", void 0);
  19401. __decorate([
  19402. BABYLON.serialize()
  19403. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19404. __decorate([
  19405. BABYLON.serialize()
  19406. ], TransformNode.prototype, "infiniteDistance", void 0);
  19407. __decorate([
  19408. BABYLON.serializeAsVector3()
  19409. ], TransformNode.prototype, "position", void 0);
  19410. return TransformNode;
  19411. }(BABYLON.Node));
  19412. BABYLON.TransformNode = TransformNode;
  19413. })(BABYLON || (BABYLON = {}));
  19414. //# sourceMappingURL=babylon.transformNode.js.map
  19415. var BABYLON;
  19416. (function (BABYLON) {
  19417. /**
  19418. * Class used to store all common mesh properties
  19419. */
  19420. var AbstractMesh = /** @class */ (function (_super) {
  19421. __extends(AbstractMesh, _super);
  19422. // Constructor
  19423. /**
  19424. * Creates a new AbstractMesh
  19425. * @param name defines the name of the mesh
  19426. * @param scene defines the hosting scene
  19427. */
  19428. function AbstractMesh(name, scene) {
  19429. if (scene === void 0) { scene = null; }
  19430. var _this = _super.call(this, name, scene, false) || this;
  19431. _this._facetNb = 0; // facet number
  19432. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19433. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19434. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19435. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19436. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19437. _this._subDiv = {
  19438. max: 1,
  19439. X: 1,
  19440. Y: 1,
  19441. Z: 1
  19442. };
  19443. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19444. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19445. // Events
  19446. /**
  19447. * An event triggered when this mesh collides with another one
  19448. */
  19449. _this.onCollideObservable = new BABYLON.Observable();
  19450. /**
  19451. * An event triggered when the collision's position changes
  19452. */
  19453. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19454. /**
  19455. * An event triggered when material is changed
  19456. */
  19457. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19458. // Properties
  19459. /**
  19460. * Gets or sets the orientation for POV movement & rotation
  19461. */
  19462. _this.definedFacingForward = true;
  19463. /**
  19464. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19465. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19466. * * 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.
  19467. * @see http://doc.babylonjs.com/features/occlusionquery
  19468. */
  19469. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19470. /**
  19471. * 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:
  19472. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19473. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19474. * * 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.
  19475. * @see http://doc.babylonjs.com/features/occlusionquery
  19476. */
  19477. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19478. /**
  19479. * 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.
  19480. * The default value is -1 which means don't break the query and wait till the result
  19481. * @see http://doc.babylonjs.com/features/occlusionquery
  19482. */
  19483. _this.occlusionRetryCount = -1;
  19484. _this._occlusionInternalRetryCounter = 0;
  19485. _this._isOccluded = false;
  19486. _this._isOcclusionQueryInProgress = false;
  19487. _this._visibility = 1.0;
  19488. /** Gets or sets the alpha index used to sort transparent meshes
  19489. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19490. */
  19491. _this.alphaIndex = Number.MAX_VALUE;
  19492. /**
  19493. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19494. */
  19495. _this.isVisible = true;
  19496. /**
  19497. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19498. */
  19499. _this.isPickable = true;
  19500. /**
  19501. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19502. */
  19503. _this.showBoundingBox = false;
  19504. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19505. _this.showSubMeshesBoundingBox = false;
  19506. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19507. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19508. */
  19509. _this.isBlocker = false;
  19510. /**
  19511. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19512. */
  19513. _this.enablePointerMoveEvents = false;
  19514. /**
  19515. * Specifies the rendering group id for this mesh (0 by default)
  19516. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19517. */
  19518. _this.renderingGroupId = 0;
  19519. _this._receiveShadows = false;
  19520. /**
  19521. * Gets or sets a boolean indicating if the outline must be rendered as well
  19522. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19523. */
  19524. _this.renderOutline = false;
  19525. /** Defines color to use when rendering outline */
  19526. _this.outlineColor = BABYLON.Color3.Red();
  19527. /** Define width to use when rendering outline */
  19528. _this.outlineWidth = 0.02;
  19529. /**
  19530. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19531. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19532. */
  19533. _this.renderOverlay = false;
  19534. /** Defines color to use when rendering overlay */
  19535. _this.overlayColor = BABYLON.Color3.Red();
  19536. /** Defines alpha to use when rendering overlay */
  19537. _this.overlayAlpha = 0.5;
  19538. _this._hasVertexAlpha = false;
  19539. _this._useVertexColors = true;
  19540. _this._computeBonesUsingShaders = true;
  19541. _this._numBoneInfluencers = 4;
  19542. _this._applyFog = true;
  19543. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19544. _this.useOctreeForRenderingSelection = true;
  19545. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19546. _this.useOctreeForPicking = true;
  19547. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19548. _this.useOctreeForCollisions = true;
  19549. _this._layerMask = 0x0FFFFFFF;
  19550. /**
  19551. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19552. */
  19553. _this.alwaysSelectAsActiveMesh = false;
  19554. /**
  19555. * Gets or sets the current action manager
  19556. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19557. */
  19558. _this.actionManager = null;
  19559. /**
  19560. * Gets or sets impostor used for physic simulation
  19561. * @see http://doc.babylonjs.com/features/physics_engine
  19562. */
  19563. _this.physicsImpostor = null;
  19564. // Collisions
  19565. _this._checkCollisions = false;
  19566. _this._collisionMask = -1;
  19567. _this._collisionGroup = -1;
  19568. /**
  19569. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19570. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19571. */
  19572. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19573. /**
  19574. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19575. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19576. */
  19577. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19578. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19579. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19580. // Edges
  19581. /**
  19582. * Defines edge width used when edgesRenderer is enabled
  19583. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19584. */
  19585. _this.edgesWidth = 1;
  19586. /**
  19587. * Defines edge color used when edgesRenderer is enabled
  19588. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19589. */
  19590. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19591. // Cache
  19592. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19593. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19594. /** @hidden */
  19595. _this._renderId = 0;
  19596. /** @hidden */
  19597. _this._intersectionsInProgress = new Array();
  19598. /** @hidden */
  19599. _this._unIndexed = false;
  19600. /** @hidden */
  19601. _this._lightSources = new Array();
  19602. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19603. if (collidedMesh === void 0) { collidedMesh = null; }
  19604. //TODO move this to the collision coordinator!
  19605. if (_this.getScene().workerCollisions)
  19606. newPosition.multiplyInPlace(_this._collider._radius);
  19607. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19608. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19609. _this.position.addInPlace(_this._diffPositionForCollisions);
  19610. }
  19611. if (collidedMesh) {
  19612. _this.onCollideObservable.notifyObservers(collidedMesh);
  19613. }
  19614. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19615. };
  19616. _this.getScene().addMesh(_this);
  19617. _this._resyncLightSources();
  19618. return _this;
  19619. }
  19620. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19621. /**
  19622. * No billboard
  19623. */
  19624. get: function () {
  19625. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19626. },
  19627. enumerable: true,
  19628. configurable: true
  19629. });
  19630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19631. /** Billboard on X axis */
  19632. get: function () {
  19633. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19634. },
  19635. enumerable: true,
  19636. configurable: true
  19637. });
  19638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19639. /** Billboard on Y axis */
  19640. get: function () {
  19641. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19647. /** Billboard on Z axis */
  19648. get: function () {
  19649. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19655. /** Billboard on all axes */
  19656. get: function () {
  19657. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19658. },
  19659. enumerable: true,
  19660. configurable: true
  19661. });
  19662. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19663. /**
  19664. * Gets the number of facets in the mesh
  19665. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19666. */
  19667. get: function () {
  19668. return this._facetNb;
  19669. },
  19670. enumerable: true,
  19671. configurable: true
  19672. });
  19673. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19674. /**
  19675. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19676. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19677. */
  19678. get: function () {
  19679. return this._partitioningSubdivisions;
  19680. },
  19681. set: function (nb) {
  19682. this._partitioningSubdivisions = nb;
  19683. },
  19684. enumerable: true,
  19685. configurable: true
  19686. });
  19687. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19688. /**
  19689. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19690. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19691. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19692. */
  19693. get: function () {
  19694. return this._partitioningBBoxRatio;
  19695. },
  19696. set: function (ratio) {
  19697. this._partitioningBBoxRatio = ratio;
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19703. /**
  19704. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19705. * Works only for updatable meshes.
  19706. * Doesn't work with multi-materials
  19707. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19708. */
  19709. get: function () {
  19710. return this._facetDepthSort;
  19711. },
  19712. set: function (sort) {
  19713. this._facetDepthSort = sort;
  19714. },
  19715. enumerable: true,
  19716. configurable: true
  19717. });
  19718. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19719. /**
  19720. * The location (Vector3) where the facet depth sort must be computed from.
  19721. * By default, the active camera position.
  19722. * Used only when facet depth sort is enabled
  19723. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19724. */
  19725. get: function () {
  19726. return this._facetDepthSortFrom;
  19727. },
  19728. set: function (location) {
  19729. this._facetDepthSortFrom = location;
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19735. /**
  19736. * gets a boolean indicating if facetData is enabled
  19737. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19738. */
  19739. get: function () {
  19740. return this._facetDataEnabled;
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. /** @hidden */
  19746. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19747. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19748. return false;
  19749. }
  19750. this._markSubMeshesAsMiscDirty();
  19751. return true;
  19752. };
  19753. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19754. /** Set a function to call when this mesh collides with another one */
  19755. set: function (callback) {
  19756. if (this._onCollideObserver) {
  19757. this.onCollideObservable.remove(this._onCollideObserver);
  19758. }
  19759. this._onCollideObserver = this.onCollideObservable.add(callback);
  19760. },
  19761. enumerable: true,
  19762. configurable: true
  19763. });
  19764. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19765. /** Set a function to call when the collision's position changes */
  19766. set: function (callback) {
  19767. if (this._onCollisionPositionChangeObserver) {
  19768. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19769. }
  19770. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19776. /**
  19777. * 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
  19778. * @see http://doc.babylonjs.com/features/occlusionquery
  19779. */
  19780. get: function () {
  19781. return this._isOccluded;
  19782. },
  19783. set: function (value) {
  19784. this._isOccluded = value;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19790. /**
  19791. * Flag to check the progress status of the query
  19792. * @see http://doc.babylonjs.com/features/occlusionquery
  19793. */
  19794. get: function () {
  19795. return this._isOcclusionQueryInProgress;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19801. /**
  19802. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19803. */
  19804. get: function () {
  19805. return this._visibility;
  19806. },
  19807. /**
  19808. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19809. */
  19810. set: function (value) {
  19811. if (this._visibility === value) {
  19812. return;
  19813. }
  19814. this._visibility = value;
  19815. this._markSubMeshesAsMiscDirty();
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(AbstractMesh.prototype, "material", {
  19821. /** Gets or sets current material */
  19822. get: function () {
  19823. return this._material;
  19824. },
  19825. set: function (value) {
  19826. if (this._material === value) {
  19827. return;
  19828. }
  19829. this._material = value;
  19830. if (this.onMaterialChangedObservable.hasObservers) {
  19831. this.onMaterialChangedObservable.notifyObservers(this);
  19832. }
  19833. if (!this.subMeshes) {
  19834. return;
  19835. }
  19836. this._unBindEffect();
  19837. },
  19838. enumerable: true,
  19839. configurable: true
  19840. });
  19841. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19842. /**
  19843. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19844. * @see http://doc.babylonjs.com/babylon101/shadows
  19845. */
  19846. get: function () {
  19847. return this._receiveShadows;
  19848. },
  19849. set: function (value) {
  19850. if (this._receiveShadows === value) {
  19851. return;
  19852. }
  19853. this._receiveShadows = value;
  19854. this._markSubMeshesAsLightDirty();
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19860. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19861. get: function () {
  19862. return this._hasVertexAlpha;
  19863. },
  19864. set: function (value) {
  19865. if (this._hasVertexAlpha === value) {
  19866. return;
  19867. }
  19868. this._hasVertexAlpha = value;
  19869. this._markSubMeshesAsAttributesDirty();
  19870. this._markSubMeshesAsMiscDirty();
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19876. /** 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) */
  19877. get: function () {
  19878. return this._useVertexColors;
  19879. },
  19880. set: function (value) {
  19881. if (this._useVertexColors === value) {
  19882. return;
  19883. }
  19884. this._useVertexColors = value;
  19885. this._markSubMeshesAsAttributesDirty();
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19891. /**
  19892. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19893. */
  19894. get: function () {
  19895. return this._computeBonesUsingShaders;
  19896. },
  19897. set: function (value) {
  19898. if (this._computeBonesUsingShaders === value) {
  19899. return;
  19900. }
  19901. this._computeBonesUsingShaders = value;
  19902. this._markSubMeshesAsAttributesDirty();
  19903. },
  19904. enumerable: true,
  19905. configurable: true
  19906. });
  19907. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19908. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19909. get: function () {
  19910. return this._numBoneInfluencers;
  19911. },
  19912. set: function (value) {
  19913. if (this._numBoneInfluencers === value) {
  19914. return;
  19915. }
  19916. this._numBoneInfluencers = value;
  19917. this._markSubMeshesAsAttributesDirty();
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19923. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19924. get: function () {
  19925. return this._applyFog;
  19926. },
  19927. set: function (value) {
  19928. if (this._applyFog === value) {
  19929. return;
  19930. }
  19931. this._applyFog = value;
  19932. this._markSubMeshesAsMiscDirty();
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19938. /**
  19939. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19940. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19941. */
  19942. get: function () {
  19943. return this._layerMask;
  19944. },
  19945. set: function (value) {
  19946. if (value === this._layerMask) {
  19947. return;
  19948. }
  19949. this._layerMask = value;
  19950. this._resyncLightSources();
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19956. /**
  19957. * Gets or sets a collision mask used to mask collisions (default is -1).
  19958. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19959. */
  19960. get: function () {
  19961. return this._collisionMask;
  19962. },
  19963. set: function (mask) {
  19964. this._collisionMask = !isNaN(mask) ? mask : -1;
  19965. },
  19966. enumerable: true,
  19967. configurable: true
  19968. });
  19969. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19970. /**
  19971. * Gets or sets the current collision group mask (-1 by default).
  19972. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19973. */
  19974. get: function () {
  19975. return this._collisionGroup;
  19976. },
  19977. set: function (mask) {
  19978. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19979. },
  19980. enumerable: true,
  19981. configurable: true
  19982. });
  19983. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19984. /** @hidden */
  19985. get: function () {
  19986. return null;
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19992. get: function () {
  19993. return this._skeleton;
  19994. },
  19995. /**
  19996. * Gets or sets a skeleton to apply skining transformations
  19997. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19998. */
  19999. set: function (value) {
  20000. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20001. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20002. }
  20003. if (value && value.needInitialSkinMatrix) {
  20004. value._registerMeshWithPoseMatrix(this);
  20005. }
  20006. this._skeleton = value;
  20007. if (!this._skeleton) {
  20008. this._bonesTransformMatrices = null;
  20009. }
  20010. this._markSubMeshesAsAttributesDirty();
  20011. },
  20012. enumerable: true,
  20013. configurable: true
  20014. });
  20015. /**
  20016. * Returns the string "AbstractMesh"
  20017. * @returns "AbstractMesh"
  20018. */
  20019. AbstractMesh.prototype.getClassName = function () {
  20020. return "AbstractMesh";
  20021. };
  20022. /**
  20023. * Gets a string representation of the current mesh
  20024. * @param fullDetails defines a boolean indicating if full details must be included
  20025. * @returns a string representation of the current mesh
  20026. */
  20027. AbstractMesh.prototype.toString = function (fullDetails) {
  20028. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20029. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20030. if (this._skeleton) {
  20031. ret += ", skeleton: " + this._skeleton.name;
  20032. }
  20033. if (fullDetails) {
  20034. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20035. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20036. }
  20037. return ret;
  20038. };
  20039. /** @hidden */
  20040. AbstractMesh.prototype._rebuild = function () {
  20041. if (this._occlusionQuery) {
  20042. this._occlusionQuery = null;
  20043. }
  20044. if (this._edgesRenderer) {
  20045. this._edgesRenderer._rebuild();
  20046. }
  20047. if (!this.subMeshes) {
  20048. return;
  20049. }
  20050. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20051. var subMesh = _a[_i];
  20052. subMesh._rebuild();
  20053. }
  20054. };
  20055. /** @hidden */
  20056. AbstractMesh.prototype._resyncLightSources = function () {
  20057. this._lightSources.length = 0;
  20058. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20059. var light = _a[_i];
  20060. if (!light.isEnabled()) {
  20061. continue;
  20062. }
  20063. if (light.canAffectMesh(this)) {
  20064. this._lightSources.push(light);
  20065. }
  20066. }
  20067. this._markSubMeshesAsLightDirty();
  20068. };
  20069. /** @hidden */
  20070. AbstractMesh.prototype._resyncLighSource = function (light) {
  20071. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20072. var index = this._lightSources.indexOf(light);
  20073. if (index === -1) {
  20074. if (!isIn) {
  20075. return;
  20076. }
  20077. this._lightSources.push(light);
  20078. }
  20079. else {
  20080. if (isIn) {
  20081. return;
  20082. }
  20083. this._lightSources.splice(index, 1);
  20084. }
  20085. this._markSubMeshesAsLightDirty();
  20086. };
  20087. /** @hidden */
  20088. AbstractMesh.prototype._unBindEffect = function () {
  20089. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20090. var subMesh = _a[_i];
  20091. subMesh.setEffect(null);
  20092. }
  20093. };
  20094. /** @hidden */
  20095. AbstractMesh.prototype._removeLightSource = function (light) {
  20096. var index = this._lightSources.indexOf(light);
  20097. if (index === -1) {
  20098. return;
  20099. }
  20100. this._lightSources.splice(index, 1);
  20101. this._markSubMeshesAsLightDirty();
  20102. };
  20103. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20104. if (!this.subMeshes) {
  20105. return;
  20106. }
  20107. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20108. var subMesh = _a[_i];
  20109. if (subMesh._materialDefines) {
  20110. func(subMesh._materialDefines);
  20111. }
  20112. }
  20113. };
  20114. /** @hidden */
  20115. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20116. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20117. };
  20118. /** @hidden */
  20119. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20120. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20121. };
  20122. /** @hidden */
  20123. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20124. if (!this.subMeshes) {
  20125. return;
  20126. }
  20127. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20128. var subMesh = _a[_i];
  20129. var material = subMesh.getMaterial();
  20130. if (material) {
  20131. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20132. }
  20133. }
  20134. };
  20135. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20136. /**
  20137. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20138. */
  20139. get: function () {
  20140. return this._scaling;
  20141. },
  20142. set: function (newScaling) {
  20143. this._scaling = newScaling;
  20144. if (this.physicsImpostor) {
  20145. this.physicsImpostor.forceUpdate();
  20146. }
  20147. },
  20148. enumerable: true,
  20149. configurable: true
  20150. });
  20151. // Methods
  20152. /**
  20153. * Disables the mesh edge rendering mode
  20154. * @returns the currentAbstractMesh
  20155. */
  20156. AbstractMesh.prototype.disableEdgesRendering = function () {
  20157. if (this._edgesRenderer) {
  20158. this._edgesRenderer.dispose();
  20159. this._edgesRenderer = null;
  20160. }
  20161. return this;
  20162. };
  20163. /**
  20164. * Enables the edge rendering mode on the mesh.
  20165. * This mode makes the mesh edges visible
  20166. * @param epsilon defines the maximal distance between two angles to detect a face
  20167. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20168. * @returns the currentAbstractMesh
  20169. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20170. */
  20171. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20172. if (epsilon === void 0) { epsilon = 0.95; }
  20173. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20174. this.disableEdgesRendering();
  20175. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20176. return this;
  20177. };
  20178. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20179. /**
  20180. * Gets the edgesRenderer associated with the mesh
  20181. */
  20182. get: function () {
  20183. return this._edgesRenderer;
  20184. },
  20185. enumerable: true,
  20186. configurable: true
  20187. });
  20188. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20189. /**
  20190. * Returns true if the mesh is blocked. Implemented by child classes
  20191. */
  20192. get: function () {
  20193. return false;
  20194. },
  20195. enumerable: true,
  20196. configurable: true
  20197. });
  20198. /**
  20199. * Returns the mesh itself by default. Implemented by child classes
  20200. * @param camera defines the camera to use to pick the right LOD level
  20201. * @returns the currentAbstractMesh
  20202. */
  20203. AbstractMesh.prototype.getLOD = function (camera) {
  20204. return this;
  20205. };
  20206. /**
  20207. * Returns 0 by default. Implemented by child classes
  20208. * @returns an integer
  20209. */
  20210. AbstractMesh.prototype.getTotalVertices = function () {
  20211. return 0;
  20212. };
  20213. /**
  20214. * Returns null by default. Implemented by child classes
  20215. * @returns null
  20216. */
  20217. AbstractMesh.prototype.getIndices = function () {
  20218. return null;
  20219. };
  20220. /**
  20221. * Returns the array of the requested vertex data kind. Implemented by child classes
  20222. * @param kind defines the vertex data kind to use
  20223. * @returns null
  20224. */
  20225. AbstractMesh.prototype.getVerticesData = function (kind) {
  20226. return null;
  20227. };
  20228. /**
  20229. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20230. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20231. * Note that a new underlying VertexBuffer object is created each call.
  20232. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20233. * @param kind defines vertex data kind:
  20234. * * BABYLON.VertexBuffer.PositionKind
  20235. * * BABYLON.VertexBuffer.UVKind
  20236. * * BABYLON.VertexBuffer.UV2Kind
  20237. * * BABYLON.VertexBuffer.UV3Kind
  20238. * * BABYLON.VertexBuffer.UV4Kind
  20239. * * BABYLON.VertexBuffer.UV5Kind
  20240. * * BABYLON.VertexBuffer.UV6Kind
  20241. * * BABYLON.VertexBuffer.ColorKind
  20242. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20243. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20244. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20245. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20246. * @param data defines the data source
  20247. * @param updatable defines if the data must be flagged as updatable (or static)
  20248. * @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
  20249. * @returns the current mesh
  20250. */
  20251. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20252. return this;
  20253. };
  20254. /**
  20255. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20256. * If the mesh has no geometry, it is simply returned as it is.
  20257. * @param kind defines vertex data kind:
  20258. * * BABYLON.VertexBuffer.PositionKind
  20259. * * BABYLON.VertexBuffer.UVKind
  20260. * * BABYLON.VertexBuffer.UV2Kind
  20261. * * BABYLON.VertexBuffer.UV3Kind
  20262. * * BABYLON.VertexBuffer.UV4Kind
  20263. * * BABYLON.VertexBuffer.UV5Kind
  20264. * * BABYLON.VertexBuffer.UV6Kind
  20265. * * BABYLON.VertexBuffer.ColorKind
  20266. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20267. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20268. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20269. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20270. * @param data defines the data source
  20271. * @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
  20272. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20273. * @returns the current mesh
  20274. */
  20275. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20276. return this;
  20277. };
  20278. /**
  20279. * Sets the mesh indices,
  20280. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20281. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20282. * @param totalVertices Defines the total number of vertices
  20283. * @returns the current mesh
  20284. */
  20285. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20286. return this;
  20287. };
  20288. /**
  20289. * Gets a boolean indicating if specific vertex data is present
  20290. * @param kind defines the vertex data kind to use
  20291. * @returns true is data kind is present
  20292. */
  20293. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20294. return false;
  20295. };
  20296. /**
  20297. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20298. * @returns a BoundingInfo
  20299. */
  20300. AbstractMesh.prototype.getBoundingInfo = function () {
  20301. if (this._masterMesh) {
  20302. return this._masterMesh.getBoundingInfo();
  20303. }
  20304. if (!this._boundingInfo) {
  20305. // this._boundingInfo is being created here
  20306. this._updateBoundingInfo();
  20307. }
  20308. // cannot be null.
  20309. return this._boundingInfo;
  20310. };
  20311. /**
  20312. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20313. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20314. * @returns the current mesh
  20315. */
  20316. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20317. if (includeDescendants === void 0) { includeDescendants = true; }
  20318. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20319. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20320. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20321. if (maxDimension === 0) {
  20322. return this;
  20323. }
  20324. var scale = 1 / maxDimension;
  20325. this.scaling.scaleInPlace(scale);
  20326. return this;
  20327. };
  20328. /**
  20329. * Overwrite the current bounding info
  20330. * @param boundingInfo defines the new bounding info
  20331. * @returns the current mesh
  20332. */
  20333. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20334. this._boundingInfo = boundingInfo;
  20335. return this;
  20336. };
  20337. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20338. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20339. get: function () {
  20340. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20341. },
  20342. enumerable: true,
  20343. configurable: true
  20344. });
  20345. /** @hidden */
  20346. AbstractMesh.prototype._preActivate = function () {
  20347. };
  20348. /** @hidden */
  20349. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20350. };
  20351. /** @hidden */
  20352. AbstractMesh.prototype._activate = function (renderId) {
  20353. this._renderId = renderId;
  20354. };
  20355. /**
  20356. * Gets the current world matrix
  20357. * @returns a Matrix
  20358. */
  20359. AbstractMesh.prototype.getWorldMatrix = function () {
  20360. if (this._masterMesh) {
  20361. return this._masterMesh.getWorldMatrix();
  20362. }
  20363. return _super.prototype.getWorldMatrix.call(this);
  20364. };
  20365. /** @hidden */
  20366. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20367. if (this._masterMesh) {
  20368. return this._masterMesh._getWorldMatrixDeterminant();
  20369. }
  20370. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20371. };
  20372. // ================================== Point of View Movement =================================
  20373. /**
  20374. * Perform relative position change from the point of view of behind the front of the mesh.
  20375. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20376. * Supports definition of mesh facing forward or backward
  20377. * @param amountRight defines the distance on the right axis
  20378. * @param amountUp defines the distance on the up axis
  20379. * @param amountForward defines the distance on the forward axis
  20380. * @returns the current mesh
  20381. */
  20382. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20383. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20384. return this;
  20385. };
  20386. /**
  20387. * Calculate relative position change from the point of view of behind the front of the mesh.
  20388. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20389. * Supports definition of mesh facing forward or backward
  20390. * @param amountRight defines the distance on the right axis
  20391. * @param amountUp defines the distance on the up axis
  20392. * @param amountForward defines the distance on the forward axis
  20393. * @returns the new displacement vector
  20394. */
  20395. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20396. var rotMatrix = new BABYLON.Matrix();
  20397. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20398. rotQuaternion.toRotationMatrix(rotMatrix);
  20399. var translationDelta = BABYLON.Vector3.Zero();
  20400. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20401. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20402. return translationDelta;
  20403. };
  20404. // ================================== Point of View Rotation =================================
  20405. /**
  20406. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20407. * Supports definition of mesh facing forward or backward
  20408. * @param flipBack defines the flip
  20409. * @param twirlClockwise defines the twirl
  20410. * @param tiltRight defines the tilt
  20411. * @returns the current mesh
  20412. */
  20413. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20414. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20415. return this;
  20416. };
  20417. /**
  20418. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20419. * Supports definition of mesh facing forward or backward.
  20420. * @param flipBack defines the flip
  20421. * @param twirlClockwise defines the twirl
  20422. * @param tiltRight defines the tilt
  20423. * @returns the new rotation vector
  20424. */
  20425. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20426. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20427. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20428. };
  20429. /**
  20430. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20431. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20432. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20433. * @returns the new bounding vectors
  20434. */
  20435. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20436. if (includeDescendants === void 0) { includeDescendants = true; }
  20437. if (predicate === void 0) { predicate = null; }
  20438. // Ensures that all world matrix will be recomputed.
  20439. this.getScene().incrementRenderId();
  20440. this.computeWorldMatrix(true);
  20441. var min;
  20442. var max;
  20443. var boundingInfo = this.getBoundingInfo();
  20444. if (!this.subMeshes) {
  20445. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20446. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20447. }
  20448. else {
  20449. min = boundingInfo.boundingBox.minimumWorld;
  20450. max = boundingInfo.boundingBox.maximumWorld;
  20451. }
  20452. if (includeDescendants) {
  20453. var descendants = this.getDescendants(false);
  20454. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20455. var descendant = descendants_1[_i];
  20456. var childMesh = descendant;
  20457. childMesh.computeWorldMatrix(true);
  20458. // Filters meshes based on custom predicate function.
  20459. if (predicate && !predicate(childMesh)) {
  20460. continue;
  20461. }
  20462. //make sure we have the needed params to get mix and max
  20463. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20464. continue;
  20465. }
  20466. var childBoundingInfo = childMesh.getBoundingInfo();
  20467. var boundingBox = childBoundingInfo.boundingBox;
  20468. var minBox = boundingBox.minimumWorld;
  20469. var maxBox = boundingBox.maximumWorld;
  20470. BABYLON.Tools.CheckExtends(minBox, min, max);
  20471. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20472. }
  20473. }
  20474. return {
  20475. min: min,
  20476. max: max
  20477. };
  20478. };
  20479. /** @hidden */
  20480. AbstractMesh.prototype._updateBoundingInfo = function () {
  20481. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20482. this._boundingInfo.update(this.worldMatrixFromCache);
  20483. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20484. return this;
  20485. };
  20486. /** @hidden */
  20487. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20488. if (!this.subMeshes) {
  20489. return this;
  20490. }
  20491. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20492. var subMesh = this.subMeshes[subIndex];
  20493. if (!subMesh.IsGlobal) {
  20494. subMesh.updateBoundingInfo(matrix);
  20495. }
  20496. }
  20497. return this;
  20498. };
  20499. /** @hidden */
  20500. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20501. // Bounding info
  20502. this._updateBoundingInfo();
  20503. };
  20504. /**
  20505. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20506. * A mesh is in the frustum if its bounding box intersects the frustum
  20507. * @param frustumPlanes defines the frustum to test
  20508. * @returns true if the mesh is in the frustum planes
  20509. */
  20510. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20511. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20512. };
  20513. /**
  20514. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20515. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20516. * @param frustumPlanes defines the frustum to test
  20517. * @returns true if the mesh is completely in the frustum planes
  20518. */
  20519. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20520. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20521. };
  20522. /**
  20523. * True if the mesh intersects another mesh or a SolidParticle object
  20524. * @param mesh defines a target mesh or SolidParticle to test
  20525. * @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)
  20526. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20527. * @returns true if there is an intersection
  20528. */
  20529. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20530. if (precise === void 0) { precise = false; }
  20531. if (!this._boundingInfo || !mesh._boundingInfo) {
  20532. return false;
  20533. }
  20534. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20535. return true;
  20536. }
  20537. if (includeDescendants) {
  20538. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20539. var child = _a[_i];
  20540. if (child.intersectsMesh(mesh, precise, true)) {
  20541. return true;
  20542. }
  20543. }
  20544. }
  20545. return false;
  20546. };
  20547. /**
  20548. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20549. * @param point defines the point to test
  20550. * @returns true if there is an intersection
  20551. */
  20552. AbstractMesh.prototype.intersectsPoint = function (point) {
  20553. if (!this._boundingInfo) {
  20554. return false;
  20555. }
  20556. return this._boundingInfo.intersectsPoint(point);
  20557. };
  20558. /**
  20559. * Gets the current physics impostor
  20560. * @see http://doc.babylonjs.com/features/physics_engine
  20561. * @returns a physics impostor or null
  20562. */
  20563. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20564. return this.physicsImpostor;
  20565. };
  20566. /**
  20567. * Gets the position of the current mesh in camera space
  20568. * @param camera defines the camera to use
  20569. * @returns a position
  20570. */
  20571. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20572. if (camera === void 0) { camera = null; }
  20573. if (!camera) {
  20574. camera = this.getScene().activeCamera;
  20575. }
  20576. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20577. };
  20578. /**
  20579. * Returns the distance from the mesh to the active camera
  20580. * @param camera defines the camera to use
  20581. * @returns the distance
  20582. */
  20583. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20584. if (camera === void 0) { camera = null; }
  20585. if (!camera) {
  20586. camera = this.getScene().activeCamera;
  20587. }
  20588. return this.absolutePosition.subtract(camera.position).length();
  20589. };
  20590. /**
  20591. * Apply a physic impulse to the mesh
  20592. * @param force defines the force to apply
  20593. * @param contactPoint defines where to apply the force
  20594. * @returns the current mesh
  20595. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20596. */
  20597. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20598. if (!this.physicsImpostor) {
  20599. return this;
  20600. }
  20601. this.physicsImpostor.applyImpulse(force, contactPoint);
  20602. return this;
  20603. };
  20604. /**
  20605. * Creates a physic joint between two meshes
  20606. * @param otherMesh defines the other mesh to use
  20607. * @param pivot1 defines the pivot to use on this mesh
  20608. * @param pivot2 defines the pivot to use on the other mesh
  20609. * @param options defines additional options (can be plugin dependent)
  20610. * @returns the current mesh
  20611. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20612. */
  20613. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20614. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20615. return this;
  20616. }
  20617. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20618. mainPivot: pivot1,
  20619. connectedPivot: pivot2,
  20620. nativeParams: options
  20621. });
  20622. return this;
  20623. };
  20624. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20625. // Collisions
  20626. /**
  20627. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20628. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20629. */
  20630. get: function () {
  20631. return this._checkCollisions;
  20632. },
  20633. set: function (collisionEnabled) {
  20634. this._checkCollisions = collisionEnabled;
  20635. if (this.getScene().workerCollisions) {
  20636. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20637. }
  20638. },
  20639. enumerable: true,
  20640. configurable: true
  20641. });
  20642. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20643. /**
  20644. * Gets Collider object used to compute collisions (not physics)
  20645. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20646. */
  20647. get: function () {
  20648. return this._collider;
  20649. },
  20650. enumerable: true,
  20651. configurable: true
  20652. });
  20653. /**
  20654. * Move the mesh using collision engine
  20655. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20656. * @param displacement defines the requested displacement vector
  20657. * @returns the current mesh
  20658. */
  20659. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20660. var globalPosition = this.getAbsolutePosition();
  20661. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20662. if (!this._collider) {
  20663. this._collider = new BABYLON.Collider();
  20664. }
  20665. this._collider._radius = this.ellipsoid;
  20666. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20667. return this;
  20668. };
  20669. // Submeshes octree
  20670. /**
  20671. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20672. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20673. * @param maxCapacity defines the maximum size of each block (64 by default)
  20674. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20675. * @returns the new octree
  20676. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20677. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20678. */
  20679. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20680. if (maxCapacity === void 0) { maxCapacity = 64; }
  20681. if (maxDepth === void 0) { maxDepth = 2; }
  20682. if (!this._submeshesOctree) {
  20683. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20684. }
  20685. this.computeWorldMatrix(true);
  20686. var boundingInfo = this.getBoundingInfo();
  20687. // Update octree
  20688. var bbox = boundingInfo.boundingBox;
  20689. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20690. return this._submeshesOctree;
  20691. };
  20692. // Collisions
  20693. /** @hidden */
  20694. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20695. this._generatePointsArray();
  20696. if (!this._positions) {
  20697. return this;
  20698. }
  20699. // Transformation
  20700. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20701. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20702. subMesh._lastColliderWorldVertices = [];
  20703. subMesh._trianglePlanes = [];
  20704. var start = subMesh.verticesStart;
  20705. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20706. for (var i = start; i < end; i++) {
  20707. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20708. }
  20709. }
  20710. // Collide
  20711. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20712. if (collider.collisionFound) {
  20713. collider.collidedMesh = this;
  20714. }
  20715. return this;
  20716. };
  20717. /** @hidden */
  20718. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20719. var subMeshes;
  20720. var len;
  20721. // Octrees
  20722. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20723. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20724. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20725. len = intersections.length;
  20726. subMeshes = intersections.data;
  20727. }
  20728. else {
  20729. subMeshes = this.subMeshes;
  20730. len = subMeshes.length;
  20731. }
  20732. for (var index = 0; index < len; index++) {
  20733. var subMesh = subMeshes[index];
  20734. // Bounding test
  20735. if (len > 1 && !subMesh._checkCollision(collider))
  20736. continue;
  20737. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20738. }
  20739. return this;
  20740. };
  20741. /** @hidden */
  20742. AbstractMesh.prototype._checkCollision = function (collider) {
  20743. // Bounding box test
  20744. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20745. return this;
  20746. // Transformation matrix
  20747. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20748. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20749. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20750. return this;
  20751. };
  20752. // Picking
  20753. /** @hidden */
  20754. AbstractMesh.prototype._generatePointsArray = function () {
  20755. return false;
  20756. };
  20757. /**
  20758. * Checks if the passed Ray intersects with the mesh
  20759. * @param ray defines the ray to use
  20760. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20761. * @returns the picking info
  20762. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20763. */
  20764. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20765. var pickingInfo = new BABYLON.PickingInfo();
  20766. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20767. return pickingInfo;
  20768. }
  20769. if (!this._generatePointsArray()) {
  20770. return pickingInfo;
  20771. }
  20772. var intersectInfo = null;
  20773. // Octrees
  20774. var subMeshes;
  20775. var len;
  20776. if (this._submeshesOctree && this.useOctreeForPicking) {
  20777. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20778. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20779. len = intersections.length;
  20780. subMeshes = intersections.data;
  20781. }
  20782. else {
  20783. subMeshes = this.subMeshes;
  20784. len = subMeshes.length;
  20785. }
  20786. for (var index = 0; index < len; index++) {
  20787. var subMesh = subMeshes[index];
  20788. // Bounding test
  20789. if (len > 1 && !subMesh.canIntersects(ray))
  20790. continue;
  20791. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20792. if (currentIntersectInfo) {
  20793. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20794. intersectInfo = currentIntersectInfo;
  20795. intersectInfo.subMeshId = index;
  20796. if (fastCheck) {
  20797. break;
  20798. }
  20799. }
  20800. }
  20801. }
  20802. if (intersectInfo) {
  20803. // Get picked point
  20804. var world = this.getWorldMatrix();
  20805. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20806. var direction = ray.direction.clone();
  20807. direction = direction.scale(intersectInfo.distance);
  20808. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20809. var pickedPoint = worldOrigin.add(worldDirection);
  20810. // Return result
  20811. pickingInfo.hit = true;
  20812. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20813. pickingInfo.pickedPoint = pickedPoint;
  20814. pickingInfo.pickedMesh = this;
  20815. pickingInfo.bu = intersectInfo.bu || 0;
  20816. pickingInfo.bv = intersectInfo.bv || 0;
  20817. pickingInfo.faceId = intersectInfo.faceId;
  20818. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20819. return pickingInfo;
  20820. }
  20821. return pickingInfo;
  20822. };
  20823. /**
  20824. * Clones the current mesh
  20825. * @param name defines the mesh name
  20826. * @param newParent defines the new mesh parent
  20827. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20828. * @returns the new mesh
  20829. */
  20830. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20831. return null;
  20832. };
  20833. /**
  20834. * Disposes all the submeshes of the current meshnp
  20835. * @returns the current mesh
  20836. */
  20837. AbstractMesh.prototype.releaseSubMeshes = function () {
  20838. if (this.subMeshes) {
  20839. while (this.subMeshes.length) {
  20840. this.subMeshes[0].dispose();
  20841. }
  20842. }
  20843. else {
  20844. this.subMeshes = new Array();
  20845. }
  20846. return this;
  20847. };
  20848. /**
  20849. * Releases resources associated with this abstract mesh.
  20850. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20851. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20852. */
  20853. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20854. var _this = this;
  20855. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20856. var index;
  20857. // Smart Array Retainers.
  20858. this.getScene().freeActiveMeshes();
  20859. this.getScene().freeRenderingGroups();
  20860. // Action manager
  20861. if (this.actionManager !== undefined && this.actionManager !== null) {
  20862. this.actionManager.dispose();
  20863. this.actionManager = null;
  20864. }
  20865. // Skeleton
  20866. this._skeleton = null;
  20867. // Physics
  20868. if (this.physicsImpostor) {
  20869. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20870. }
  20871. // Intersections in progress
  20872. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20873. var other = this._intersectionsInProgress[index];
  20874. var pos = other._intersectionsInProgress.indexOf(this);
  20875. other._intersectionsInProgress.splice(pos, 1);
  20876. }
  20877. this._intersectionsInProgress = [];
  20878. // Lights
  20879. var lights = this.getScene().lights;
  20880. lights.forEach(function (light) {
  20881. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20882. if (meshIndex !== -1) {
  20883. light.includedOnlyMeshes.splice(meshIndex, 1);
  20884. }
  20885. meshIndex = light.excludedMeshes.indexOf(_this);
  20886. if (meshIndex !== -1) {
  20887. light.excludedMeshes.splice(meshIndex, 1);
  20888. }
  20889. // Shadow generators
  20890. var generator = light.getShadowGenerator();
  20891. if (generator) {
  20892. var shadowMap = generator.getShadowMap();
  20893. if (shadowMap && shadowMap.renderList) {
  20894. meshIndex = shadowMap.renderList.indexOf(_this);
  20895. if (meshIndex !== -1) {
  20896. shadowMap.renderList.splice(meshIndex, 1);
  20897. }
  20898. }
  20899. }
  20900. });
  20901. // Edges
  20902. if (this._edgesRenderer) {
  20903. this._edgesRenderer.dispose();
  20904. this._edgesRenderer = null;
  20905. }
  20906. // SubMeshes
  20907. if (this.getClassName() !== "InstancedMesh") {
  20908. this.releaseSubMeshes();
  20909. }
  20910. // Octree
  20911. var sceneOctree = this.getScene().selectionOctree;
  20912. if (sceneOctree !== undefined && sceneOctree !== null) {
  20913. var index = sceneOctree.dynamicContent.indexOf(this);
  20914. if (index !== -1) {
  20915. sceneOctree.dynamicContent.splice(index, 1);
  20916. }
  20917. }
  20918. // Query
  20919. var engine = this.getScene().getEngine();
  20920. if (this._occlusionQuery) {
  20921. this._isOcclusionQueryInProgress = false;
  20922. engine.deleteQuery(this._occlusionQuery);
  20923. this._occlusionQuery = null;
  20924. }
  20925. // Engine
  20926. engine.wipeCaches();
  20927. // Remove from scene
  20928. this.getScene().removeMesh(this);
  20929. if (disposeMaterialAndTextures) {
  20930. if (this.material) {
  20931. this.material.dispose(false, true);
  20932. }
  20933. }
  20934. if (!doNotRecurse) {
  20935. // Particles
  20936. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20937. if (this.getScene().particleSystems[index].emitter === this) {
  20938. this.getScene().particleSystems[index].dispose();
  20939. index--;
  20940. }
  20941. }
  20942. }
  20943. // facet data
  20944. if (this._facetDataEnabled) {
  20945. this.disableFacetData();
  20946. }
  20947. this.onAfterWorldMatrixUpdateObservable.clear();
  20948. this.onCollideObservable.clear();
  20949. this.onCollisionPositionChangeObservable.clear();
  20950. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20951. };
  20952. /**
  20953. * Adds the passed mesh as a child to the current mesh
  20954. * @param mesh defines the child mesh
  20955. * @returns the current mesh
  20956. */
  20957. AbstractMesh.prototype.addChild = function (mesh) {
  20958. mesh.setParent(this);
  20959. return this;
  20960. };
  20961. /**
  20962. * Removes the passed mesh from the current mesh children list
  20963. * @param mesh defines the child mesh
  20964. * @returns the current mesh
  20965. */
  20966. AbstractMesh.prototype.removeChild = function (mesh) {
  20967. mesh.setParent(null);
  20968. return this;
  20969. };
  20970. // Facet data
  20971. /** @hidden */
  20972. AbstractMesh.prototype._initFacetData = function () {
  20973. if (!this._facetNormals) {
  20974. this._facetNormals = new Array();
  20975. }
  20976. if (!this._facetPositions) {
  20977. this._facetPositions = new Array();
  20978. }
  20979. if (!this._facetPartitioning) {
  20980. this._facetPartitioning = new Array();
  20981. }
  20982. this._facetNb = (this.getIndices().length / 3) | 0;
  20983. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20984. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20985. for (var f = 0; f < this._facetNb; f++) {
  20986. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20987. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20988. }
  20989. this._facetDataEnabled = true;
  20990. return this;
  20991. };
  20992. /**
  20993. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20994. * This method can be called within the render loop.
  20995. * 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
  20996. * @returns the current mesh
  20997. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20998. */
  20999. AbstractMesh.prototype.updateFacetData = function () {
  21000. if (!this._facetDataEnabled) {
  21001. this._initFacetData();
  21002. }
  21003. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21004. var indices = this.getIndices();
  21005. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21006. var bInfo = this.getBoundingInfo();
  21007. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21008. // init arrays, matrix and sort function on first call
  21009. this._facetDepthSortEnabled = true;
  21010. if (indices instanceof Uint16Array) {
  21011. this._depthSortedIndices = new Uint16Array(indices);
  21012. }
  21013. else if (indices instanceof Uint32Array) {
  21014. this._depthSortedIndices = new Uint32Array(indices);
  21015. }
  21016. else {
  21017. var needs32bits = false;
  21018. for (var i = 0; i < indices.length; i++) {
  21019. if (indices[i] > 65535) {
  21020. needs32bits = true;
  21021. break;
  21022. }
  21023. }
  21024. if (needs32bits) {
  21025. this._depthSortedIndices = new Uint32Array(indices);
  21026. }
  21027. else {
  21028. this._depthSortedIndices = new Uint16Array(indices);
  21029. }
  21030. }
  21031. this._facetDepthSortFunction = function (f1, f2) {
  21032. return (f2.sqDistance - f1.sqDistance);
  21033. };
  21034. if (!this._facetDepthSortFrom) {
  21035. var camera = this.getScene().activeCamera;
  21036. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21037. }
  21038. this._depthSortedFacets = [];
  21039. for (var f = 0; f < this._facetNb; f++) {
  21040. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21041. this._depthSortedFacets.push(depthSortedFacet);
  21042. }
  21043. this._invertedMatrix = BABYLON.Matrix.Identity();
  21044. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21045. }
  21046. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21047. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21048. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21049. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21050. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21051. this._subDiv.max = this._partitioningSubdivisions;
  21052. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21053. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21054. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21055. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21056. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21057. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21058. // set the parameters for ComputeNormals()
  21059. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21060. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21061. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21062. this._facetParameters.bInfo = bInfo;
  21063. this._facetParameters.bbSize = this._bbSize;
  21064. this._facetParameters.subDiv = this._subDiv;
  21065. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21066. this._facetParameters.depthSort = this._facetDepthSort;
  21067. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21068. this.computeWorldMatrix(true);
  21069. this._worldMatrix.invertToRef(this._invertedMatrix);
  21070. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21071. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21072. }
  21073. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21074. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21075. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21076. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21077. var l = (this._depthSortedIndices.length / 3) | 0;
  21078. for (var f = 0; f < l; f++) {
  21079. var sind = this._depthSortedFacets[f].ind;
  21080. this._depthSortedIndices[f * 3] = indices[sind];
  21081. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21082. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21083. }
  21084. this.updateIndices(this._depthSortedIndices);
  21085. }
  21086. return this;
  21087. };
  21088. /**
  21089. * Returns the facetLocalNormals array.
  21090. * The normals are expressed in the mesh local spac
  21091. * @returns an array of Vector3
  21092. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21093. */
  21094. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21095. if (!this._facetNormals) {
  21096. this.updateFacetData();
  21097. }
  21098. return this._facetNormals;
  21099. };
  21100. /**
  21101. * Returns the facetLocalPositions array.
  21102. * The facet positions are expressed in the mesh local space
  21103. * @returns an array of Vector3
  21104. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21105. */
  21106. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21107. if (!this._facetPositions) {
  21108. this.updateFacetData();
  21109. }
  21110. return this._facetPositions;
  21111. };
  21112. /**
  21113. * Returns the facetLocalPartioning array
  21114. * @returns an array of array of numbers
  21115. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21116. */
  21117. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21118. if (!this._facetPartitioning) {
  21119. this.updateFacetData();
  21120. }
  21121. return this._facetPartitioning;
  21122. };
  21123. /**
  21124. * Returns the i-th facet position in the world system.
  21125. * This method allocates a new Vector3 per call
  21126. * @param i defines the facet index
  21127. * @returns a new Vector3
  21128. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21129. */
  21130. AbstractMesh.prototype.getFacetPosition = function (i) {
  21131. var pos = BABYLON.Vector3.Zero();
  21132. this.getFacetPositionToRef(i, pos);
  21133. return pos;
  21134. };
  21135. /**
  21136. * Sets the reference Vector3 with the i-th facet position in the world system
  21137. * @param i defines the facet index
  21138. * @param ref defines the target vector
  21139. * @returns the current mesh
  21140. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21141. */
  21142. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21143. var localPos = (this.getFacetLocalPositions())[i];
  21144. var world = this.getWorldMatrix();
  21145. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21146. return this;
  21147. };
  21148. /**
  21149. * Returns the i-th facet normal in the world system.
  21150. * This method allocates a new Vector3 per call
  21151. * @param i defines the facet index
  21152. * @returns a new Vector3
  21153. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21154. */
  21155. AbstractMesh.prototype.getFacetNormal = function (i) {
  21156. var norm = BABYLON.Vector3.Zero();
  21157. this.getFacetNormalToRef(i, norm);
  21158. return norm;
  21159. };
  21160. /**
  21161. * Sets the reference Vector3 with the i-th facet normal in the world system
  21162. * @param i defines the facet index
  21163. * @param ref defines the target vector
  21164. * @returns the current mesh
  21165. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21166. */
  21167. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21168. var localNorm = (this.getFacetLocalNormals())[i];
  21169. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21170. return this;
  21171. };
  21172. /**
  21173. * 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)
  21174. * @param x defines x coordinate
  21175. * @param y defines y coordinate
  21176. * @param z defines z coordinate
  21177. * @returns the array of facet indexes
  21178. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21179. */
  21180. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21181. var bInfo = this.getBoundingInfo();
  21182. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21183. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21184. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21185. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21186. return null;
  21187. }
  21188. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21189. };
  21190. /**
  21191. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21192. * @param projected sets as the (x,y,z) world projection on the facet
  21193. * @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
  21194. * @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
  21195. * @param x defines x coordinate
  21196. * @param y defines y coordinate
  21197. * @param z defines z coordinate
  21198. * @returns the face index if found (or null instead)
  21199. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21200. */
  21201. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21202. if (checkFace === void 0) { checkFace = false; }
  21203. if (facing === void 0) { facing = true; }
  21204. var world = this.getWorldMatrix();
  21205. var invMat = BABYLON.Tmp.Matrix[5];
  21206. world.invertToRef(invMat);
  21207. var invVect = BABYLON.Tmp.Vector3[8];
  21208. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21209. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21210. if (projected) {
  21211. // tranform the local computed projected vector to world coordinates
  21212. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21213. }
  21214. return closest;
  21215. };
  21216. /**
  21217. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21218. * @param projected sets as the (x,y,z) local projection on the facet
  21219. * @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
  21220. * @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
  21221. * @param x defines x coordinate
  21222. * @param y defines y coordinate
  21223. * @param z defines z coordinate
  21224. * @returns the face index if found (or null instead)
  21225. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21226. */
  21227. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21228. if (checkFace === void 0) { checkFace = false; }
  21229. if (facing === void 0) { facing = true; }
  21230. var closest = null;
  21231. var tmpx = 0.0;
  21232. var tmpy = 0.0;
  21233. var tmpz = 0.0;
  21234. var d = 0.0; // tmp dot facet normal * facet position
  21235. var t0 = 0.0;
  21236. var projx = 0.0;
  21237. var projy = 0.0;
  21238. var projz = 0.0;
  21239. // Get all the facets in the same partitioning block than (x, y, z)
  21240. var facetPositions = this.getFacetLocalPositions();
  21241. var facetNormals = this.getFacetLocalNormals();
  21242. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21243. if (!facetsInBlock) {
  21244. return null;
  21245. }
  21246. // Get the closest facet to (x, y, z)
  21247. var shortest = Number.MAX_VALUE; // init distance vars
  21248. var tmpDistance = shortest;
  21249. var fib; // current facet in the block
  21250. var norm; // current facet normal
  21251. var p0; // current facet barycenter position
  21252. // loop on all the facets in the current partitioning block
  21253. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21254. fib = facetsInBlock[idx];
  21255. norm = facetNormals[fib];
  21256. p0 = facetPositions[fib];
  21257. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21258. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21259. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21260. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21261. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21262. projx = x + norm.x * t0;
  21263. projy = y + norm.y * t0;
  21264. projz = z + norm.z * t0;
  21265. tmpx = projx - x;
  21266. tmpy = projy - y;
  21267. tmpz = projz - z;
  21268. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21269. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21270. shortest = tmpDistance;
  21271. closest = fib;
  21272. if (projected) {
  21273. projected.x = projx;
  21274. projected.y = projy;
  21275. projected.z = projz;
  21276. }
  21277. }
  21278. }
  21279. }
  21280. return closest;
  21281. };
  21282. /**
  21283. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21284. * @returns the parameters
  21285. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21286. */
  21287. AbstractMesh.prototype.getFacetDataParameters = function () {
  21288. return this._facetParameters;
  21289. };
  21290. /**
  21291. * Disables the feature FacetData and frees the related memory
  21292. * @returns the current mesh
  21293. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21294. */
  21295. AbstractMesh.prototype.disableFacetData = function () {
  21296. if (this._facetDataEnabled) {
  21297. this._facetDataEnabled = false;
  21298. this._facetPositions = new Array();
  21299. this._facetNormals = new Array();
  21300. this._facetPartitioning = new Array();
  21301. this._facetParameters = null;
  21302. this._depthSortedIndices = new Uint32Array(0);
  21303. }
  21304. return this;
  21305. };
  21306. /**
  21307. * Updates the AbstractMesh indices array
  21308. * @param indices defines the data source
  21309. * @returns the current mesh
  21310. */
  21311. AbstractMesh.prototype.updateIndices = function (indices) {
  21312. return this;
  21313. };
  21314. /**
  21315. * Creates new normals data for the mesh
  21316. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21317. * @returns the current mesh
  21318. */
  21319. AbstractMesh.prototype.createNormals = function (updatable) {
  21320. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21321. var indices = this.getIndices();
  21322. var normals;
  21323. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21324. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21325. }
  21326. else {
  21327. normals = [];
  21328. }
  21329. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21330. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21331. return this;
  21332. };
  21333. /**
  21334. * Align the mesh with a normal
  21335. * @param normal defines the normal to use
  21336. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21337. * @returns the current mesh
  21338. */
  21339. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21340. if (!upDirection) {
  21341. upDirection = BABYLON.Axis.Y;
  21342. }
  21343. var axisX = BABYLON.Tmp.Vector3[0];
  21344. var axisZ = BABYLON.Tmp.Vector3[1];
  21345. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21346. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21347. if (this.rotationQuaternion) {
  21348. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21349. }
  21350. else {
  21351. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21352. }
  21353. return this;
  21354. };
  21355. /** @hidden */
  21356. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21357. var engine = this.getEngine();
  21358. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21359. this._isOccluded = false;
  21360. return;
  21361. }
  21362. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21363. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21364. if (isOcclusionQueryAvailable) {
  21365. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21366. this._isOcclusionQueryInProgress = false;
  21367. this._occlusionInternalRetryCounter = 0;
  21368. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21369. }
  21370. else {
  21371. this._occlusionInternalRetryCounter++;
  21372. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21373. this._isOcclusionQueryInProgress = false;
  21374. this._occlusionInternalRetryCounter = 0;
  21375. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21376. // if strict continue the last state of the object.
  21377. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21378. }
  21379. else {
  21380. return;
  21381. }
  21382. }
  21383. }
  21384. var scene = this.getScene();
  21385. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21386. if (!this._occlusionQuery) {
  21387. this._occlusionQuery = engine.createQuery();
  21388. }
  21389. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21390. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21391. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21392. this._isOcclusionQueryInProgress = true;
  21393. };
  21394. /** No occlusion */
  21395. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21396. /** Occlusion set to optimisitic */
  21397. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21398. /** Occlusion set to strict */
  21399. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21400. /** Use an accurante occlusion algorithm */
  21401. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21402. /** Use a conservative occlusion algorithm */
  21403. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21404. return AbstractMesh;
  21405. }(BABYLON.TransformNode));
  21406. BABYLON.AbstractMesh = AbstractMesh;
  21407. })(BABYLON || (BABYLON = {}));
  21408. //# sourceMappingURL=babylon.abstractMesh.js.map
  21409. var BABYLON;
  21410. (function (BABYLON) {
  21411. /**
  21412. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21413. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21414. * 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.
  21415. */
  21416. var Light = /** @class */ (function (_super) {
  21417. __extends(Light, _super);
  21418. /**
  21419. * Creates a Light object in the scene.
  21420. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21421. * @param name The firendly name of the light
  21422. * @param scene The scene the light belongs too
  21423. */
  21424. function Light(name, scene) {
  21425. var _this = _super.call(this, name, scene) || this;
  21426. /**
  21427. * Diffuse gives the basic color to an object.
  21428. */
  21429. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21430. /**
  21431. * Specular produces a highlight color on an object.
  21432. * Note: This is note affecting PBR materials.
  21433. */
  21434. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21435. /**
  21436. * Strength of the light.
  21437. * Note: By default it is define in the framework own unit.
  21438. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21439. */
  21440. _this.intensity = 1.0;
  21441. /**
  21442. * Defines how far from the source the light is impacting in scene units.
  21443. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21444. */
  21445. _this.range = Number.MAX_VALUE;
  21446. /**
  21447. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21448. * of light.
  21449. */
  21450. _this._photometricScale = 1.0;
  21451. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21452. _this._radius = 0.00001;
  21453. /**
  21454. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21455. * exceeding the number allowed of the materials.
  21456. */
  21457. _this.renderPriority = 0;
  21458. _this._shadowEnabled = true;
  21459. _this._excludeWithLayerMask = 0;
  21460. _this._includeOnlyWithLayerMask = 0;
  21461. _this._lightmapMode = 0;
  21462. /**
  21463. * @hidden Internal use only.
  21464. */
  21465. _this._excludedMeshesIds = new Array();
  21466. /**
  21467. * @hidden Internal use only.
  21468. */
  21469. _this._includedOnlyMeshesIds = new Array();
  21470. _this.getScene().addLight(_this);
  21471. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21472. _this._buildUniformLayout();
  21473. _this.includedOnlyMeshes = new Array();
  21474. _this.excludedMeshes = new Array();
  21475. _this._resyncMeshes();
  21476. return _this;
  21477. }
  21478. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21479. /**
  21480. * If every light affecting the material is in this lightmapMode,
  21481. * material.lightmapTexture adds or multiplies
  21482. * (depends on material.useLightmapAsShadowmap)
  21483. * after every other light calculations.
  21484. */
  21485. get: function () {
  21486. return Light._LIGHTMAP_DEFAULT;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21492. /**
  21493. * material.lightmapTexture as only diffuse lighting from this light
  21494. * adds only specular lighting from this light
  21495. * adds dynamic shadows
  21496. */
  21497. get: function () {
  21498. return Light._LIGHTMAP_SPECULAR;
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21504. /**
  21505. * material.lightmapTexture as only lighting
  21506. * no light calculation from this light
  21507. * only adds dynamic shadows from this light
  21508. */
  21509. get: function () {
  21510. return Light._LIGHTMAP_SHADOWSONLY;
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21516. /**
  21517. * Each light type uses the default quantity according to its type:
  21518. * point/spot lights use luminous intensity
  21519. * directional lights use illuminance
  21520. */
  21521. get: function () {
  21522. return Light._INTENSITYMODE_AUTOMATIC;
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21528. /**
  21529. * lumen (lm)
  21530. */
  21531. get: function () {
  21532. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21538. /**
  21539. * candela (lm/sr)
  21540. */
  21541. get: function () {
  21542. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21543. },
  21544. enumerable: true,
  21545. configurable: true
  21546. });
  21547. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21548. /**
  21549. * lux (lm/m^2)
  21550. */
  21551. get: function () {
  21552. return Light._INTENSITYMODE_ILLUMINANCE;
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21558. /**
  21559. * nit (cd/m^2)
  21560. */
  21561. get: function () {
  21562. return Light._INTENSITYMODE_LUMINANCE;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21568. /**
  21569. * Light type const id of the point light.
  21570. */
  21571. get: function () {
  21572. return Light._LIGHTTYPEID_POINTLIGHT;
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21578. /**
  21579. * Light type const id of the directional light.
  21580. */
  21581. get: function () {
  21582. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21583. },
  21584. enumerable: true,
  21585. configurable: true
  21586. });
  21587. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21588. /**
  21589. * Light type const id of the spot light.
  21590. */
  21591. get: function () {
  21592. return Light._LIGHTTYPEID_SPOTLIGHT;
  21593. },
  21594. enumerable: true,
  21595. configurable: true
  21596. });
  21597. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21598. /**
  21599. * Light type const id of the hemispheric light.
  21600. */
  21601. get: function () {
  21602. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21603. },
  21604. enumerable: true,
  21605. configurable: true
  21606. });
  21607. Object.defineProperty(Light.prototype, "intensityMode", {
  21608. /**
  21609. * Gets the photometric scale used to interpret the intensity.
  21610. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21611. */
  21612. get: function () {
  21613. return this._intensityMode;
  21614. },
  21615. /**
  21616. * Sets the photometric scale used to interpret the intensity.
  21617. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21618. */
  21619. set: function (value) {
  21620. this._intensityMode = value;
  21621. this._computePhotometricScale();
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. ;
  21627. ;
  21628. Object.defineProperty(Light.prototype, "radius", {
  21629. /**
  21630. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21631. */
  21632. get: function () {
  21633. return this._radius;
  21634. },
  21635. /**
  21636. * sets the light radius used by PBR Materials to simulate soft area lights.
  21637. */
  21638. set: function (value) {
  21639. this._radius = value;
  21640. this._computePhotometricScale();
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. ;
  21646. ;
  21647. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21648. /**
  21649. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21650. * the current shadow generator.
  21651. */
  21652. get: function () {
  21653. return this._shadowEnabled;
  21654. },
  21655. /**
  21656. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21657. * the current shadow generator.
  21658. */
  21659. set: function (value) {
  21660. if (this._shadowEnabled === value) {
  21661. return;
  21662. }
  21663. this._shadowEnabled = value;
  21664. this._markMeshesAsLightDirty();
  21665. },
  21666. enumerable: true,
  21667. configurable: true
  21668. });
  21669. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21670. /**
  21671. * Gets the only meshes impacted by this light.
  21672. */
  21673. get: function () {
  21674. return this._includedOnlyMeshes;
  21675. },
  21676. /**
  21677. * Sets the only meshes impacted by this light.
  21678. */
  21679. set: function (value) {
  21680. this._includedOnlyMeshes = value;
  21681. this._hookArrayForIncludedOnly(value);
  21682. },
  21683. enumerable: true,
  21684. configurable: true
  21685. });
  21686. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21687. /**
  21688. * Gets the meshes not impacted by this light.
  21689. */
  21690. get: function () {
  21691. return this._excludedMeshes;
  21692. },
  21693. /**
  21694. * Sets the meshes not impacted by this light.
  21695. */
  21696. set: function (value) {
  21697. this._excludedMeshes = value;
  21698. this._hookArrayForExcluded(value);
  21699. },
  21700. enumerable: true,
  21701. configurable: true
  21702. });
  21703. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21704. /**
  21705. * Gets the layer id use to find what meshes are not impacted by the light.
  21706. * Inactive if 0
  21707. */
  21708. get: function () {
  21709. return this._excludeWithLayerMask;
  21710. },
  21711. /**
  21712. * Sets the layer id use to find what meshes are not impacted by the light.
  21713. * Inactive if 0
  21714. */
  21715. set: function (value) {
  21716. this._excludeWithLayerMask = value;
  21717. this._resyncMeshes();
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21723. /**
  21724. * Gets the layer id use to find what meshes are impacted by the light.
  21725. * Inactive if 0
  21726. */
  21727. get: function () {
  21728. return this._includeOnlyWithLayerMask;
  21729. },
  21730. /**
  21731. * Sets the layer id use to find what meshes are impacted by the light.
  21732. * Inactive if 0
  21733. */
  21734. set: function (value) {
  21735. this._includeOnlyWithLayerMask = value;
  21736. this._resyncMeshes();
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Light.prototype, "lightmapMode", {
  21742. /**
  21743. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21744. */
  21745. get: function () {
  21746. return this._lightmapMode;
  21747. },
  21748. /**
  21749. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21750. */
  21751. set: function (value) {
  21752. if (this._lightmapMode === value) {
  21753. return;
  21754. }
  21755. this._lightmapMode = value;
  21756. this._markMeshesAsLightDirty();
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. /**
  21762. * Returns the string "Light".
  21763. * @returns the class name
  21764. */
  21765. Light.prototype.getClassName = function () {
  21766. return "Light";
  21767. };
  21768. /**
  21769. * Converts the light information to a readable string for debug purpose.
  21770. * @param fullDetails Supports for multiple levels of logging within scene loading
  21771. * @returns the human readable light info
  21772. */
  21773. Light.prototype.toString = function (fullDetails) {
  21774. var ret = "Name: " + this.name;
  21775. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21776. if (this.animations) {
  21777. for (var i = 0; i < this.animations.length; i++) {
  21778. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21779. }
  21780. }
  21781. if (fullDetails) {
  21782. }
  21783. return ret;
  21784. };
  21785. /**
  21786. * Set the enabled state of this node.
  21787. * @param value - the new enabled state
  21788. */
  21789. Light.prototype.setEnabled = function (value) {
  21790. _super.prototype.setEnabled.call(this, value);
  21791. this._resyncMeshes();
  21792. };
  21793. /**
  21794. * Returns the Light associated shadow generator if any.
  21795. * @return the associated shadow generator.
  21796. */
  21797. Light.prototype.getShadowGenerator = function () {
  21798. return this._shadowGenerator;
  21799. };
  21800. /**
  21801. * Returns a Vector3, the absolute light position in the World.
  21802. * @returns the world space position of the light
  21803. */
  21804. Light.prototype.getAbsolutePosition = function () {
  21805. return BABYLON.Vector3.Zero();
  21806. };
  21807. /**
  21808. * Specifies if the light will affect the passed mesh.
  21809. * @param mesh The mesh to test against the light
  21810. * @return true the mesh is affected otherwise, false.
  21811. */
  21812. Light.prototype.canAffectMesh = function (mesh) {
  21813. if (!mesh) {
  21814. return true;
  21815. }
  21816. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21817. return false;
  21818. }
  21819. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21820. return false;
  21821. }
  21822. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21823. return false;
  21824. }
  21825. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21826. return false;
  21827. }
  21828. return true;
  21829. };
  21830. /**
  21831. * Computes and Returns the light World matrix.
  21832. * @returns the world matrix
  21833. */
  21834. Light.prototype.getWorldMatrix = function () {
  21835. this._currentRenderId = this.getScene().getRenderId();
  21836. this._childRenderId = this._currentRenderId;
  21837. var worldMatrix = this._getWorldMatrix();
  21838. if (this.parent && this.parent.getWorldMatrix) {
  21839. if (!this._parentedWorldMatrix) {
  21840. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21841. }
  21842. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21843. this._markSyncedWithParent();
  21844. return this._parentedWorldMatrix;
  21845. }
  21846. return worldMatrix;
  21847. };
  21848. /**
  21849. * Sort function to order lights for rendering.
  21850. * @param a First Light object to compare to second.
  21851. * @param b Second Light object to compare first.
  21852. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21853. */
  21854. Light.CompareLightsPriority = function (a, b) {
  21855. //shadow-casting lights have priority over non-shadow-casting lights
  21856. //the renderPrioirty is a secondary sort criterion
  21857. if (a.shadowEnabled !== b.shadowEnabled) {
  21858. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21859. }
  21860. return b.renderPriority - a.renderPriority;
  21861. };
  21862. /**
  21863. * Releases resources associated with this node.
  21864. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21865. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21866. */
  21867. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21868. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21869. if (this._shadowGenerator) {
  21870. this._shadowGenerator.dispose();
  21871. this._shadowGenerator = null;
  21872. }
  21873. // Animations
  21874. this.getScene().stopAnimation(this);
  21875. // Remove from meshes
  21876. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21877. var mesh = _a[_i];
  21878. mesh._removeLightSource(this);
  21879. }
  21880. this._uniformBuffer.dispose();
  21881. // Remove from scene
  21882. this.getScene().removeLight(this);
  21883. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21884. };
  21885. /**
  21886. * Returns the light type ID (integer).
  21887. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21888. */
  21889. Light.prototype.getTypeID = function () {
  21890. return 0;
  21891. };
  21892. /**
  21893. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21894. * @returns the scaled intensity in intensity mode unit
  21895. */
  21896. Light.prototype.getScaledIntensity = function () {
  21897. return this._photometricScale * this.intensity;
  21898. };
  21899. /**
  21900. * Returns a new Light object, named "name", from the current one.
  21901. * @param name The name of the cloned light
  21902. * @returns the new created light
  21903. */
  21904. Light.prototype.clone = function (name) {
  21905. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21906. if (!constructor) {
  21907. return null;
  21908. }
  21909. return BABYLON.SerializationHelper.Clone(constructor, this);
  21910. };
  21911. /**
  21912. * Serializes the current light into a Serialization object.
  21913. * @returns the serialized object.
  21914. */
  21915. Light.prototype.serialize = function () {
  21916. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21917. // Type
  21918. serializationObject.type = this.getTypeID();
  21919. // Parent
  21920. if (this.parent) {
  21921. serializationObject.parentId = this.parent.id;
  21922. }
  21923. // Inclusion / exclusions
  21924. if (this.excludedMeshes.length > 0) {
  21925. serializationObject.excludedMeshesIds = [];
  21926. this.excludedMeshes.forEach(function (mesh) {
  21927. serializationObject.excludedMeshesIds.push(mesh.id);
  21928. });
  21929. }
  21930. if (this.includedOnlyMeshes.length > 0) {
  21931. serializationObject.includedOnlyMeshesIds = [];
  21932. this.includedOnlyMeshes.forEach(function (mesh) {
  21933. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21934. });
  21935. }
  21936. // Animations
  21937. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21938. serializationObject.ranges = this.serializeAnimationRanges();
  21939. return serializationObject;
  21940. };
  21941. /**
  21942. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21943. * This new light is named "name" and added to the passed scene.
  21944. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21945. * @param name The friendly name of the light
  21946. * @param scene The scene the new light will belong to
  21947. * @returns the constructor function
  21948. */
  21949. Light.GetConstructorFromName = function (type, name, scene) {
  21950. switch (type) {
  21951. case 0:
  21952. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21953. case 1:
  21954. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21955. case 2:
  21956. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21957. case 3:
  21958. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21959. }
  21960. return null;
  21961. };
  21962. /**
  21963. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21964. * @param parsedLight The JSON representation of the light
  21965. * @param scene The scene to create the parsed light in
  21966. * @returns the created light after parsing
  21967. */
  21968. Light.Parse = function (parsedLight, scene) {
  21969. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21970. if (!constructor) {
  21971. return null;
  21972. }
  21973. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21974. // Inclusion / exclusions
  21975. if (parsedLight.excludedMeshesIds) {
  21976. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21977. }
  21978. if (parsedLight.includedOnlyMeshesIds) {
  21979. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21980. }
  21981. // Parent
  21982. if (parsedLight.parentId) {
  21983. light._waitingParentId = parsedLight.parentId;
  21984. }
  21985. // Animations
  21986. if (parsedLight.animations) {
  21987. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21988. var parsedAnimation = parsedLight.animations[animationIndex];
  21989. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21990. }
  21991. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21992. }
  21993. if (parsedLight.autoAnimate) {
  21994. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21995. }
  21996. return light;
  21997. };
  21998. Light.prototype._hookArrayForExcluded = function (array) {
  21999. var _this = this;
  22000. var oldPush = array.push;
  22001. array.push = function () {
  22002. var items = [];
  22003. for (var _i = 0; _i < arguments.length; _i++) {
  22004. items[_i] = arguments[_i];
  22005. }
  22006. var result = oldPush.apply(array, items);
  22007. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22008. var item = items_1[_a];
  22009. item._resyncLighSource(_this);
  22010. }
  22011. return result;
  22012. };
  22013. var oldSplice = array.splice;
  22014. array.splice = function (index, deleteCount) {
  22015. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22016. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22017. var item = deleted_1[_i];
  22018. item._resyncLighSource(_this);
  22019. }
  22020. return deleted;
  22021. };
  22022. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22023. var item = array_1[_i];
  22024. item._resyncLighSource(this);
  22025. }
  22026. };
  22027. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22028. var _this = this;
  22029. var oldPush = array.push;
  22030. array.push = function () {
  22031. var items = [];
  22032. for (var _i = 0; _i < arguments.length; _i++) {
  22033. items[_i] = arguments[_i];
  22034. }
  22035. var result = oldPush.apply(array, items);
  22036. _this._resyncMeshes();
  22037. return result;
  22038. };
  22039. var oldSplice = array.splice;
  22040. array.splice = function (index, deleteCount) {
  22041. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22042. _this._resyncMeshes();
  22043. return deleted;
  22044. };
  22045. this._resyncMeshes();
  22046. };
  22047. Light.prototype._resyncMeshes = function () {
  22048. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22049. var mesh = _a[_i];
  22050. mesh._resyncLighSource(this);
  22051. }
  22052. };
  22053. /**
  22054. * Forces the meshes to update their light related information in their rendering used effects
  22055. * @hidden Internal Use Only
  22056. */
  22057. Light.prototype._markMeshesAsLightDirty = function () {
  22058. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22059. var mesh = _a[_i];
  22060. if (mesh._lightSources.indexOf(this) !== -1) {
  22061. mesh._markSubMeshesAsLightDirty();
  22062. }
  22063. }
  22064. };
  22065. /**
  22066. * Recomputes the cached photometric scale if needed.
  22067. */
  22068. Light.prototype._computePhotometricScale = function () {
  22069. this._photometricScale = this._getPhotometricScale();
  22070. this.getScene().resetCachedMaterial();
  22071. };
  22072. /**
  22073. * Returns the Photometric Scale according to the light type and intensity mode.
  22074. */
  22075. Light.prototype._getPhotometricScale = function () {
  22076. var photometricScale = 0.0;
  22077. var lightTypeID = this.getTypeID();
  22078. //get photometric mode
  22079. var photometricMode = this.intensityMode;
  22080. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22081. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22082. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22083. }
  22084. else {
  22085. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22086. }
  22087. }
  22088. //compute photometric scale
  22089. switch (lightTypeID) {
  22090. case Light.LIGHTTYPEID_POINTLIGHT:
  22091. case Light.LIGHTTYPEID_SPOTLIGHT:
  22092. switch (photometricMode) {
  22093. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22094. photometricScale = 1.0 / (4.0 * Math.PI);
  22095. break;
  22096. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22097. photometricScale = 1.0;
  22098. break;
  22099. case Light.INTENSITYMODE_LUMINANCE:
  22100. photometricScale = this.radius * this.radius;
  22101. break;
  22102. }
  22103. break;
  22104. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22105. switch (photometricMode) {
  22106. case Light.INTENSITYMODE_ILLUMINANCE:
  22107. photometricScale = 1.0;
  22108. break;
  22109. case Light.INTENSITYMODE_LUMINANCE:
  22110. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22111. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22112. var apexAngleRadians = this.radius;
  22113. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22114. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22115. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22116. photometricScale = solidAngle;
  22117. break;
  22118. }
  22119. break;
  22120. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22121. // No fall off in hemisperic light.
  22122. photometricScale = 1.0;
  22123. break;
  22124. }
  22125. return photometricScale;
  22126. };
  22127. /**
  22128. * Reorder the light in the scene according to their defined priority.
  22129. * @hidden Internal Use Only
  22130. */
  22131. Light.prototype._reorderLightsInScene = function () {
  22132. var scene = this.getScene();
  22133. if (this._renderPriority != 0) {
  22134. scene.requireLightSorting = true;
  22135. }
  22136. this.getScene().sortLightsByPriority();
  22137. };
  22138. //lightmapMode Consts
  22139. Light._LIGHTMAP_DEFAULT = 0;
  22140. Light._LIGHTMAP_SPECULAR = 1;
  22141. Light._LIGHTMAP_SHADOWSONLY = 2;
  22142. // Intensity Mode Consts
  22143. Light._INTENSITYMODE_AUTOMATIC = 0;
  22144. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22145. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22146. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22147. Light._INTENSITYMODE_LUMINANCE = 4;
  22148. // Light types ids const.
  22149. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22150. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22151. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22152. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22153. __decorate([
  22154. BABYLON.serializeAsColor3()
  22155. ], Light.prototype, "diffuse", void 0);
  22156. __decorate([
  22157. BABYLON.serializeAsColor3()
  22158. ], Light.prototype, "specular", void 0);
  22159. __decorate([
  22160. BABYLON.serialize()
  22161. ], Light.prototype, "intensity", void 0);
  22162. __decorate([
  22163. BABYLON.serialize()
  22164. ], Light.prototype, "range", void 0);
  22165. __decorate([
  22166. BABYLON.serialize()
  22167. ], Light.prototype, "intensityMode", null);
  22168. __decorate([
  22169. BABYLON.serialize()
  22170. ], Light.prototype, "radius", null);
  22171. __decorate([
  22172. BABYLON.serialize()
  22173. ], Light.prototype, "_renderPriority", void 0);
  22174. __decorate([
  22175. BABYLON.expandToProperty("_reorderLightsInScene")
  22176. ], Light.prototype, "renderPriority", void 0);
  22177. __decorate([
  22178. BABYLON.serialize("shadowEnabled")
  22179. ], Light.prototype, "_shadowEnabled", void 0);
  22180. __decorate([
  22181. BABYLON.serialize("excludeWithLayerMask")
  22182. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22183. __decorate([
  22184. BABYLON.serialize("includeOnlyWithLayerMask")
  22185. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22186. __decorate([
  22187. BABYLON.serialize("lightmapMode")
  22188. ], Light.prototype, "_lightmapMode", void 0);
  22189. return Light;
  22190. }(BABYLON.Node));
  22191. BABYLON.Light = Light;
  22192. })(BABYLON || (BABYLON = {}));
  22193. //# sourceMappingURL=babylon.light.js.map
  22194. var BABYLON;
  22195. (function (BABYLON) {
  22196. var Camera = /** @class */ (function (_super) {
  22197. __extends(Camera, _super);
  22198. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22199. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22200. var _this = _super.call(this, name, scene) || this;
  22201. /**
  22202. * The vector the camera should consider as up.
  22203. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22204. */
  22205. _this.upVector = BABYLON.Vector3.Up();
  22206. _this.orthoLeft = null;
  22207. _this.orthoRight = null;
  22208. _this.orthoBottom = null;
  22209. _this.orthoTop = null;
  22210. /**
  22211. * FOV is set in Radians. (default is 0.8)
  22212. */
  22213. _this.fov = 0.8;
  22214. _this.minZ = 1;
  22215. _this.maxZ = 10000.0;
  22216. _this.inertia = 0.9;
  22217. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22218. _this.isIntermediate = false;
  22219. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22220. /**
  22221. * Restricts the camera to viewing objects with the same layerMask.
  22222. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22223. */
  22224. _this.layerMask = 0x0FFFFFFF;
  22225. /**
  22226. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22227. */
  22228. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22229. // Camera rig members
  22230. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22231. _this._rigCameras = new Array();
  22232. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22233. _this._skipRendering = false;
  22234. _this.customRenderTargets = new Array();
  22235. // Observables
  22236. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22237. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22238. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22239. _this.onRestoreStateObservable = new BABYLON.Observable();
  22240. // Cache
  22241. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22242. _this._projectionMatrix = new BABYLON.Matrix();
  22243. _this._doNotComputeProjectionMatrix = false;
  22244. _this._worldMatrix = BABYLON.Matrix.Identity();
  22245. _this._postProcesses = new Array();
  22246. _this._transformMatrix = BABYLON.Matrix.Zero();
  22247. _this._activeMeshes = new BABYLON.SmartArray(256);
  22248. _this._globalPosition = BABYLON.Vector3.Zero();
  22249. _this._refreshFrustumPlanes = true;
  22250. _this.getScene().addCamera(_this);
  22251. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22252. _this.getScene().activeCamera = _this;
  22253. }
  22254. _this.position = position;
  22255. return _this;
  22256. }
  22257. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22258. get: function () {
  22259. return Camera._PERSPECTIVE_CAMERA;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22265. get: function () {
  22266. return Camera._ORTHOGRAPHIC_CAMERA;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22272. /**
  22273. * This is the default FOV mode for perspective cameras.
  22274. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22275. *
  22276. */
  22277. get: function () {
  22278. return Camera._FOVMODE_VERTICAL_FIXED;
  22279. },
  22280. enumerable: true,
  22281. configurable: true
  22282. });
  22283. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22284. /**
  22285. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22286. *
  22287. */
  22288. get: function () {
  22289. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22290. },
  22291. enumerable: true,
  22292. configurable: true
  22293. });
  22294. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22295. get: function () {
  22296. return Camera._RIG_MODE_NONE;
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22302. get: function () {
  22303. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22309. get: function () {
  22310. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22311. },
  22312. enumerable: true,
  22313. configurable: true
  22314. });
  22315. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22316. get: function () {
  22317. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22318. },
  22319. enumerable: true,
  22320. configurable: true
  22321. });
  22322. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22323. get: function () {
  22324. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22325. },
  22326. enumerable: true,
  22327. configurable: true
  22328. });
  22329. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22330. get: function () {
  22331. return Camera._RIG_MODE_VR;
  22332. },
  22333. enumerable: true,
  22334. configurable: true
  22335. });
  22336. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22337. get: function () {
  22338. return Camera._RIG_MODE_WEBVR;
  22339. },
  22340. enumerable: true,
  22341. configurable: true
  22342. });
  22343. /**
  22344. * Store current camera state (fov, position, etc..)
  22345. */
  22346. Camera.prototype.storeState = function () {
  22347. this._stateStored = true;
  22348. this._storedFov = this.fov;
  22349. return this;
  22350. };
  22351. /**
  22352. * Restores the camera state values if it has been stored. You must call storeState() first
  22353. */
  22354. Camera.prototype._restoreStateValues = function () {
  22355. if (!this._stateStored) {
  22356. return false;
  22357. }
  22358. this.fov = this._storedFov;
  22359. return true;
  22360. };
  22361. /**
  22362. * Restored camera state. You must call storeState() first
  22363. */
  22364. Camera.prototype.restoreState = function () {
  22365. if (this._restoreStateValues()) {
  22366. this.onRestoreStateObservable.notifyObservers(this);
  22367. return true;
  22368. }
  22369. return false;
  22370. };
  22371. Camera.prototype.getClassName = function () {
  22372. return "Camera";
  22373. };
  22374. /**
  22375. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22376. */
  22377. Camera.prototype.toString = function (fullDetails) {
  22378. var ret = "Name: " + this.name;
  22379. ret += ", type: " + this.getClassName();
  22380. if (this.animations) {
  22381. for (var i = 0; i < this.animations.length; i++) {
  22382. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22383. }
  22384. }
  22385. if (fullDetails) {
  22386. }
  22387. return ret;
  22388. };
  22389. Object.defineProperty(Camera.prototype, "globalPosition", {
  22390. get: function () {
  22391. return this._globalPosition;
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. Camera.prototype.getActiveMeshes = function () {
  22397. return this._activeMeshes;
  22398. };
  22399. Camera.prototype.isActiveMesh = function (mesh) {
  22400. return (this._activeMeshes.indexOf(mesh) !== -1);
  22401. };
  22402. /**
  22403. * Is this camera ready to be used/rendered
  22404. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22405. * @return true if the camera is ready
  22406. */
  22407. Camera.prototype.isReady = function (completeCheck) {
  22408. if (completeCheck === void 0) { completeCheck = false; }
  22409. if (completeCheck) {
  22410. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22411. var pp = _a[_i];
  22412. if (pp && !pp.isReady()) {
  22413. return false;
  22414. }
  22415. }
  22416. }
  22417. return _super.prototype.isReady.call(this, completeCheck);
  22418. };
  22419. //Cache
  22420. Camera.prototype._initCache = function () {
  22421. _super.prototype._initCache.call(this);
  22422. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22423. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22424. this._cache.mode = undefined;
  22425. this._cache.minZ = undefined;
  22426. this._cache.maxZ = undefined;
  22427. this._cache.fov = undefined;
  22428. this._cache.fovMode = undefined;
  22429. this._cache.aspectRatio = undefined;
  22430. this._cache.orthoLeft = undefined;
  22431. this._cache.orthoRight = undefined;
  22432. this._cache.orthoBottom = undefined;
  22433. this._cache.orthoTop = undefined;
  22434. this._cache.renderWidth = undefined;
  22435. this._cache.renderHeight = undefined;
  22436. };
  22437. Camera.prototype._updateCache = function (ignoreParentClass) {
  22438. if (!ignoreParentClass) {
  22439. _super.prototype._updateCache.call(this);
  22440. }
  22441. this._cache.position.copyFrom(this.position);
  22442. this._cache.upVector.copyFrom(this.upVector);
  22443. };
  22444. // Synchronized
  22445. Camera.prototype._isSynchronized = function () {
  22446. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22447. };
  22448. Camera.prototype._isSynchronizedViewMatrix = function () {
  22449. if (!_super.prototype._isSynchronized.call(this))
  22450. return false;
  22451. return this._cache.position.equals(this.position)
  22452. && this._cache.upVector.equals(this.upVector)
  22453. && this.isSynchronizedWithParent();
  22454. };
  22455. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22456. var check = this._cache.mode === this.mode
  22457. && this._cache.minZ === this.minZ
  22458. && this._cache.maxZ === this.maxZ;
  22459. if (!check) {
  22460. return false;
  22461. }
  22462. var engine = this.getEngine();
  22463. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22464. check = this._cache.fov === this.fov
  22465. && this._cache.fovMode === this.fovMode
  22466. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22467. }
  22468. else {
  22469. check = this._cache.orthoLeft === this.orthoLeft
  22470. && this._cache.orthoRight === this.orthoRight
  22471. && this._cache.orthoBottom === this.orthoBottom
  22472. && this._cache.orthoTop === this.orthoTop
  22473. && this._cache.renderWidth === engine.getRenderWidth()
  22474. && this._cache.renderHeight === engine.getRenderHeight();
  22475. }
  22476. return check;
  22477. };
  22478. // Controls
  22479. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22480. };
  22481. Camera.prototype.detachControl = function (element) {
  22482. };
  22483. Camera.prototype.update = function () {
  22484. this._checkInputs();
  22485. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22486. this._updateRigCameras();
  22487. }
  22488. };
  22489. Camera.prototype._checkInputs = function () {
  22490. this.onAfterCheckInputsObservable.notifyObservers(this);
  22491. };
  22492. Object.defineProperty(Camera.prototype, "rigCameras", {
  22493. get: function () {
  22494. return this._rigCameras;
  22495. },
  22496. enumerable: true,
  22497. configurable: true
  22498. });
  22499. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22500. get: function () {
  22501. return this._rigPostProcess;
  22502. },
  22503. enumerable: true,
  22504. configurable: true
  22505. });
  22506. /**
  22507. * Internal, gets the first post proces.
  22508. * @returns the first post process to be run on this camera.
  22509. */
  22510. Camera.prototype._getFirstPostProcess = function () {
  22511. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22512. if (this._postProcesses[ppIndex] !== null) {
  22513. return this._postProcesses[ppIndex];
  22514. }
  22515. }
  22516. return null;
  22517. };
  22518. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22519. // invalidate framebuffer
  22520. var firstPostProcess = this._getFirstPostProcess();
  22521. if (firstPostProcess) {
  22522. firstPostProcess.markTextureDirty();
  22523. }
  22524. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22525. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22526. var cam = this._rigCameras[i];
  22527. var rigPostProcess = cam._rigPostProcess;
  22528. // for VR rig, there does not have to be a post process
  22529. if (rigPostProcess) {
  22530. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22531. if (isPass) {
  22532. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22533. cam.isIntermediate = this._postProcesses.length === 0;
  22534. }
  22535. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22536. rigPostProcess.markTextureDirty();
  22537. }
  22538. else {
  22539. cam._postProcesses = this._postProcesses.slice(0);
  22540. }
  22541. }
  22542. };
  22543. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22544. if (insertAt === void 0) { insertAt = null; }
  22545. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22546. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22547. return 0;
  22548. }
  22549. if (insertAt == null || insertAt < 0) {
  22550. this._postProcesses.push(postProcess);
  22551. }
  22552. else if (this._postProcesses[insertAt] === null) {
  22553. this._postProcesses[insertAt] = postProcess;
  22554. }
  22555. else {
  22556. this._postProcesses.splice(insertAt, 0, postProcess);
  22557. }
  22558. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22559. return this._postProcesses.indexOf(postProcess);
  22560. };
  22561. Camera.prototype.detachPostProcess = function (postProcess) {
  22562. var idx = this._postProcesses.indexOf(postProcess);
  22563. if (idx !== -1) {
  22564. this._postProcesses[idx] = null;
  22565. }
  22566. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22567. };
  22568. Camera.prototype.getWorldMatrix = function () {
  22569. if (this._isSynchronizedViewMatrix()) {
  22570. return this._worldMatrix;
  22571. }
  22572. // Getting the the view matrix will also compute the world matrix.
  22573. this.getViewMatrix();
  22574. return this._worldMatrix;
  22575. };
  22576. Camera.prototype._getViewMatrix = function () {
  22577. return BABYLON.Matrix.Identity();
  22578. };
  22579. Camera.prototype.getViewMatrix = function (force) {
  22580. if (!force && this._isSynchronizedViewMatrix()) {
  22581. return this._computedViewMatrix;
  22582. }
  22583. this.updateCache();
  22584. this._computedViewMatrix = this._getViewMatrix();
  22585. this._currentRenderId = this.getScene().getRenderId();
  22586. this._childRenderId = this._currentRenderId;
  22587. this._refreshFrustumPlanes = true;
  22588. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22589. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22590. }
  22591. this.onViewMatrixChangedObservable.notifyObservers(this);
  22592. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22593. return this._computedViewMatrix;
  22594. };
  22595. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22596. this._doNotComputeProjectionMatrix = true;
  22597. if (projection !== undefined) {
  22598. this._projectionMatrix = projection;
  22599. }
  22600. };
  22601. ;
  22602. Camera.prototype.unfreezeProjectionMatrix = function () {
  22603. this._doNotComputeProjectionMatrix = false;
  22604. };
  22605. ;
  22606. Camera.prototype.getProjectionMatrix = function (force) {
  22607. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22608. return this._projectionMatrix;
  22609. }
  22610. // Cache
  22611. this._cache.mode = this.mode;
  22612. this._cache.minZ = this.minZ;
  22613. this._cache.maxZ = this.maxZ;
  22614. // Matrix
  22615. this._refreshFrustumPlanes = true;
  22616. var engine = this.getEngine();
  22617. var scene = this.getScene();
  22618. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22619. this._cache.fov = this.fov;
  22620. this._cache.fovMode = this.fovMode;
  22621. this._cache.aspectRatio = engine.getAspectRatio(this);
  22622. if (this.minZ <= 0) {
  22623. this.minZ = 0.1;
  22624. }
  22625. if (scene.useRightHandedSystem) {
  22626. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22627. }
  22628. else {
  22629. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22630. }
  22631. }
  22632. else {
  22633. var halfWidth = engine.getRenderWidth() / 2.0;
  22634. var halfHeight = engine.getRenderHeight() / 2.0;
  22635. if (scene.useRightHandedSystem) {
  22636. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22637. }
  22638. else {
  22639. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22640. }
  22641. this._cache.orthoLeft = this.orthoLeft;
  22642. this._cache.orthoRight = this.orthoRight;
  22643. this._cache.orthoBottom = this.orthoBottom;
  22644. this._cache.orthoTop = this.orthoTop;
  22645. this._cache.renderWidth = engine.getRenderWidth();
  22646. this._cache.renderHeight = engine.getRenderHeight();
  22647. }
  22648. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22649. return this._projectionMatrix;
  22650. };
  22651. Camera.prototype.getTranformationMatrix = function () {
  22652. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22653. return this._transformMatrix;
  22654. };
  22655. Camera.prototype.updateFrustumPlanes = function () {
  22656. if (!this._refreshFrustumPlanes) {
  22657. return;
  22658. }
  22659. this.getTranformationMatrix();
  22660. if (!this._frustumPlanes) {
  22661. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22662. }
  22663. else {
  22664. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22665. }
  22666. this._refreshFrustumPlanes = false;
  22667. };
  22668. Camera.prototype.isInFrustum = function (target) {
  22669. this.updateFrustumPlanes();
  22670. return target.isInFrustum(this._frustumPlanes);
  22671. };
  22672. Camera.prototype.isCompletelyInFrustum = function (target) {
  22673. this.updateFrustumPlanes();
  22674. return target.isCompletelyInFrustum(this._frustumPlanes);
  22675. };
  22676. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22677. if (length === void 0) { length = 100; }
  22678. if (!transform) {
  22679. transform = this.getWorldMatrix();
  22680. }
  22681. if (!origin) {
  22682. origin = this.position;
  22683. }
  22684. var forward = new BABYLON.Vector3(0, 0, 1);
  22685. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22686. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22687. return new BABYLON.Ray(origin, direction, length);
  22688. };
  22689. /**
  22690. * Releases resources associated with this node.
  22691. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22692. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22693. */
  22694. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22695. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22696. // Observables
  22697. this.onViewMatrixChangedObservable.clear();
  22698. this.onProjectionMatrixChangedObservable.clear();
  22699. this.onAfterCheckInputsObservable.clear();
  22700. this.onRestoreStateObservable.clear();
  22701. // Inputs
  22702. if (this.inputs) {
  22703. this.inputs.clear();
  22704. }
  22705. // Animations
  22706. this.getScene().stopAnimation(this);
  22707. // Remove from scene
  22708. this.getScene().removeCamera(this);
  22709. while (this._rigCameras.length > 0) {
  22710. var camera = this._rigCameras.pop();
  22711. if (camera) {
  22712. camera.dispose();
  22713. }
  22714. }
  22715. // Postprocesses
  22716. if (this._rigPostProcess) {
  22717. this._rigPostProcess.dispose(this);
  22718. this._rigPostProcess = null;
  22719. this._postProcesses = [];
  22720. }
  22721. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22722. this._rigPostProcess = null;
  22723. this._postProcesses = [];
  22724. }
  22725. else {
  22726. var i = this._postProcesses.length;
  22727. while (--i >= 0) {
  22728. var postProcess = this._postProcesses[i];
  22729. if (postProcess) {
  22730. postProcess.dispose(this);
  22731. }
  22732. }
  22733. }
  22734. // Render targets
  22735. var i = this.customRenderTargets.length;
  22736. while (--i >= 0) {
  22737. this.customRenderTargets[i].dispose();
  22738. }
  22739. this.customRenderTargets = [];
  22740. // Active Meshes
  22741. this._activeMeshes.dispose();
  22742. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22743. };
  22744. Object.defineProperty(Camera.prototype, "leftCamera", {
  22745. // ---- Camera rigs section ----
  22746. get: function () {
  22747. if (this._rigCameras.length < 1) {
  22748. return null;
  22749. }
  22750. return this._rigCameras[0];
  22751. },
  22752. enumerable: true,
  22753. configurable: true
  22754. });
  22755. Object.defineProperty(Camera.prototype, "rightCamera", {
  22756. get: function () {
  22757. if (this._rigCameras.length < 2) {
  22758. return null;
  22759. }
  22760. return this._rigCameras[1];
  22761. },
  22762. enumerable: true,
  22763. configurable: true
  22764. });
  22765. Camera.prototype.getLeftTarget = function () {
  22766. if (this._rigCameras.length < 1) {
  22767. return null;
  22768. }
  22769. return this._rigCameras[0].getTarget();
  22770. };
  22771. Camera.prototype.getRightTarget = function () {
  22772. if (this._rigCameras.length < 2) {
  22773. return null;
  22774. }
  22775. return this._rigCameras[1].getTarget();
  22776. };
  22777. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22778. if (this.cameraRigMode === mode) {
  22779. return;
  22780. }
  22781. while (this._rigCameras.length > 0) {
  22782. var camera = this._rigCameras.pop();
  22783. if (camera) {
  22784. camera.dispose();
  22785. }
  22786. }
  22787. this.cameraRigMode = mode;
  22788. this._cameraRigParams = {};
  22789. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22790. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22791. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22792. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22793. // create the rig cameras, unless none
  22794. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22795. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22796. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22797. if (leftCamera && rightCamera) {
  22798. this._rigCameras.push(leftCamera);
  22799. this._rigCameras.push(rightCamera);
  22800. }
  22801. }
  22802. switch (this.cameraRigMode) {
  22803. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22804. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22805. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22806. break;
  22807. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22808. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22809. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22810. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22811. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22812. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22813. break;
  22814. case Camera.RIG_MODE_VR:
  22815. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22816. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22817. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22818. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22819. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22820. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22821. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22822. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22823. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22824. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22825. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22826. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22827. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22828. if (metrics.compensateDistortion) {
  22829. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22830. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22831. }
  22832. break;
  22833. case Camera.RIG_MODE_WEBVR:
  22834. if (rigParams.vrDisplay) {
  22835. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22836. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22837. //Left eye
  22838. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22839. this._rigCameras[0].setCameraRigParameter("left", true);
  22840. //leaving this for future reference
  22841. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22842. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22843. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22844. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22845. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22846. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22847. this._rigCameras[0].parent = this;
  22848. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22849. //Right eye
  22850. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22851. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22852. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22853. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22854. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22855. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22856. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22857. this._rigCameras[1].parent = this;
  22858. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22859. if (Camera.UseAlternateWebVRRendering) {
  22860. this._rigCameras[1]._skipRendering = true;
  22861. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22862. }
  22863. }
  22864. break;
  22865. }
  22866. this._cascadePostProcessesToRigCams();
  22867. this.update();
  22868. };
  22869. Camera.prototype._getVRProjectionMatrix = function () {
  22870. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22871. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22872. return this._projectionMatrix;
  22873. };
  22874. Camera.prototype._updateCameraRotationMatrix = function () {
  22875. //Here for WebVR
  22876. };
  22877. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22878. //Here for WebVR
  22879. };
  22880. /**
  22881. * This function MUST be overwritten by the different WebVR cameras available.
  22882. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22883. */
  22884. Camera.prototype._getWebVRProjectionMatrix = function () {
  22885. return BABYLON.Matrix.Identity();
  22886. };
  22887. /**
  22888. * This function MUST be overwritten by the different WebVR cameras available.
  22889. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22890. */
  22891. Camera.prototype._getWebVRViewMatrix = function () {
  22892. return BABYLON.Matrix.Identity();
  22893. };
  22894. Camera.prototype.setCameraRigParameter = function (name, value) {
  22895. if (!this._cameraRigParams) {
  22896. this._cameraRigParams = {};
  22897. }
  22898. this._cameraRigParams[name] = value;
  22899. //provisionnally:
  22900. if (name === "interaxialDistance") {
  22901. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22902. }
  22903. };
  22904. /**
  22905. * needs to be overridden by children so sub has required properties to be copied
  22906. */
  22907. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22908. return null;
  22909. };
  22910. /**
  22911. * May need to be overridden by children
  22912. */
  22913. Camera.prototype._updateRigCameras = function () {
  22914. for (var i = 0; i < this._rigCameras.length; i++) {
  22915. this._rigCameras[i].minZ = this.minZ;
  22916. this._rigCameras[i].maxZ = this.maxZ;
  22917. this._rigCameras[i].fov = this.fov;
  22918. }
  22919. // only update viewport when ANAGLYPH
  22920. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22921. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22922. }
  22923. };
  22924. Camera.prototype._setupInputs = function () {
  22925. };
  22926. Camera.prototype.serialize = function () {
  22927. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22928. // Type
  22929. serializationObject.type = this.getClassName();
  22930. // Parent
  22931. if (this.parent) {
  22932. serializationObject.parentId = this.parent.id;
  22933. }
  22934. if (this.inputs) {
  22935. this.inputs.serialize(serializationObject);
  22936. }
  22937. // Animations
  22938. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22939. serializationObject.ranges = this.serializeAnimationRanges();
  22940. return serializationObject;
  22941. };
  22942. Camera.prototype.clone = function (name) {
  22943. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22944. };
  22945. Camera.prototype.getDirection = function (localAxis) {
  22946. var result = BABYLON.Vector3.Zero();
  22947. this.getDirectionToRef(localAxis, result);
  22948. return result;
  22949. };
  22950. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22951. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22952. };
  22953. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22954. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22955. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22956. switch (type) {
  22957. case "ArcRotateCamera":
  22958. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22959. case "DeviceOrientationCamera":
  22960. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22961. case "FollowCamera":
  22962. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22963. case "ArcFollowCamera":
  22964. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22965. case "GamepadCamera":
  22966. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22967. case "TouchCamera":
  22968. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22969. case "VirtualJoysticksCamera":
  22970. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22971. case "WebVRFreeCamera":
  22972. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22973. case "WebVRGamepadCamera":
  22974. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22975. case "VRDeviceOrientationFreeCamera":
  22976. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22977. case "VRDeviceOrientationGamepadCamera":
  22978. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22979. case "AnaglyphArcRotateCamera":
  22980. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22981. case "AnaglyphFreeCamera":
  22982. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22983. case "AnaglyphGamepadCamera":
  22984. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22985. case "AnaglyphUniversalCamera":
  22986. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22987. case "StereoscopicArcRotateCamera":
  22988. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22989. case "StereoscopicFreeCamera":
  22990. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22991. case "StereoscopicGamepadCamera":
  22992. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22993. case "StereoscopicUniversalCamera":
  22994. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22995. case "FreeCamera": // Forcing Universal here
  22996. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22997. default: // Universal Camera is the default value
  22998. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22999. }
  23000. };
  23001. Camera.prototype.computeWorldMatrix = function () {
  23002. return this.getWorldMatrix();
  23003. };
  23004. Camera.Parse = function (parsedCamera, scene) {
  23005. var type = parsedCamera.type;
  23006. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23007. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23008. // Parent
  23009. if (parsedCamera.parentId) {
  23010. camera._waitingParentId = parsedCamera.parentId;
  23011. }
  23012. //If camera has an input manager, let it parse inputs settings
  23013. if (camera.inputs) {
  23014. camera.inputs.parse(parsedCamera);
  23015. camera._setupInputs();
  23016. }
  23017. if (camera.setPosition) { // need to force position
  23018. camera.position.copyFromFloats(0, 0, 0);
  23019. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23020. }
  23021. // Target
  23022. if (parsedCamera.target) {
  23023. if (camera.setTarget) {
  23024. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23025. }
  23026. }
  23027. // Apply 3d rig, when found
  23028. if (parsedCamera.cameraRigMode) {
  23029. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23030. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23031. }
  23032. // Animations
  23033. if (parsedCamera.animations) {
  23034. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23035. var parsedAnimation = parsedCamera.animations[animationIndex];
  23036. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23037. }
  23038. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23039. }
  23040. if (parsedCamera.autoAnimate) {
  23041. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23042. }
  23043. return camera;
  23044. };
  23045. // Statics
  23046. Camera._PERSPECTIVE_CAMERA = 0;
  23047. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23048. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23049. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23050. Camera._RIG_MODE_NONE = 0;
  23051. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23052. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23053. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23054. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23055. Camera._RIG_MODE_VR = 20;
  23056. Camera._RIG_MODE_WEBVR = 21;
  23057. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23058. Camera.UseAlternateWebVRRendering = false;
  23059. __decorate([
  23060. BABYLON.serializeAsVector3()
  23061. ], Camera.prototype, "position", void 0);
  23062. __decorate([
  23063. BABYLON.serializeAsVector3()
  23064. ], Camera.prototype, "upVector", void 0);
  23065. __decorate([
  23066. BABYLON.serialize()
  23067. ], Camera.prototype, "orthoLeft", void 0);
  23068. __decorate([
  23069. BABYLON.serialize()
  23070. ], Camera.prototype, "orthoRight", void 0);
  23071. __decorate([
  23072. BABYLON.serialize()
  23073. ], Camera.prototype, "orthoBottom", void 0);
  23074. __decorate([
  23075. BABYLON.serialize()
  23076. ], Camera.prototype, "orthoTop", void 0);
  23077. __decorate([
  23078. BABYLON.serialize()
  23079. ], Camera.prototype, "fov", void 0);
  23080. __decorate([
  23081. BABYLON.serialize()
  23082. ], Camera.prototype, "minZ", void 0);
  23083. __decorate([
  23084. BABYLON.serialize()
  23085. ], Camera.prototype, "maxZ", void 0);
  23086. __decorate([
  23087. BABYLON.serialize()
  23088. ], Camera.prototype, "inertia", void 0);
  23089. __decorate([
  23090. BABYLON.serialize()
  23091. ], Camera.prototype, "mode", void 0);
  23092. __decorate([
  23093. BABYLON.serialize()
  23094. ], Camera.prototype, "layerMask", void 0);
  23095. __decorate([
  23096. BABYLON.serialize()
  23097. ], Camera.prototype, "fovMode", void 0);
  23098. __decorate([
  23099. BABYLON.serialize()
  23100. ], Camera.prototype, "cameraRigMode", void 0);
  23101. __decorate([
  23102. BABYLON.serialize()
  23103. ], Camera.prototype, "interaxialDistance", void 0);
  23104. __decorate([
  23105. BABYLON.serialize()
  23106. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23107. return Camera;
  23108. }(BABYLON.Node));
  23109. BABYLON.Camera = Camera;
  23110. })(BABYLON || (BABYLON = {}));
  23111. //# sourceMappingURL=babylon.camera.js.map
  23112. var BABYLON;
  23113. (function (BABYLON) {
  23114. var RenderingManager = /** @class */ (function () {
  23115. function RenderingManager(scene) {
  23116. this._renderingGroups = new Array();
  23117. this._autoClearDepthStencil = {};
  23118. this._customOpaqueSortCompareFn = {};
  23119. this._customAlphaTestSortCompareFn = {};
  23120. this._customTransparentSortCompareFn = {};
  23121. this._renderinGroupInfo = null;
  23122. this._scene = scene;
  23123. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23124. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23125. }
  23126. }
  23127. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23128. if (depth === void 0) { depth = true; }
  23129. if (stencil === void 0) { stencil = true; }
  23130. if (this._depthStencilBufferAlreadyCleaned) {
  23131. return;
  23132. }
  23133. this._scene.getEngine().clear(null, false, depth, stencil);
  23134. this._depthStencilBufferAlreadyCleaned = true;
  23135. };
  23136. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23137. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23138. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23139. var info = null;
  23140. if (observable) {
  23141. if (!this._renderinGroupInfo) {
  23142. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23143. }
  23144. info = this._renderinGroupInfo;
  23145. info.scene = this._scene;
  23146. info.camera = this._scene.activeCamera;
  23147. }
  23148. // Dispatch sprites
  23149. if (renderSprites) {
  23150. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23151. var manager = this._scene.spriteManagers[index];
  23152. this.dispatchSprites(manager);
  23153. }
  23154. }
  23155. // Render
  23156. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23157. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23158. var renderingGroup = this._renderingGroups[index];
  23159. if (!renderingGroup && !observable)
  23160. continue;
  23161. var renderingGroupMask = 0;
  23162. // Fire PRECLEAR stage
  23163. if (observable && info) {
  23164. renderingGroupMask = Math.pow(2, index);
  23165. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23166. info.renderingGroupId = index;
  23167. observable.notifyObservers(info, renderingGroupMask);
  23168. }
  23169. // Clear depth/stencil if needed
  23170. if (RenderingManager.AUTOCLEAR) {
  23171. var autoClear = this._autoClearDepthStencil[index];
  23172. if (autoClear && autoClear.autoClear) {
  23173. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23174. }
  23175. }
  23176. if (observable && info) {
  23177. // Fire PREOPAQUE stage
  23178. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23179. observable.notifyObservers(info, renderingGroupMask);
  23180. // Fire PRETRANSPARENT stage
  23181. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23182. observable.notifyObservers(info, renderingGroupMask);
  23183. }
  23184. if (renderingGroup)
  23185. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23186. // Fire POSTTRANSPARENT stage
  23187. if (observable && info) {
  23188. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23189. observable.notifyObservers(info, renderingGroupMask);
  23190. }
  23191. }
  23192. };
  23193. RenderingManager.prototype.reset = function () {
  23194. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23195. var renderingGroup = this._renderingGroups[index];
  23196. if (renderingGroup) {
  23197. renderingGroup.prepare();
  23198. }
  23199. }
  23200. };
  23201. RenderingManager.prototype.dispose = function () {
  23202. this.freeRenderingGroups();
  23203. this._renderingGroups.length = 0;
  23204. };
  23205. /**
  23206. * Clear the info related to rendering groups preventing retention points during dispose.
  23207. */
  23208. RenderingManager.prototype.freeRenderingGroups = function () {
  23209. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23210. var renderingGroup = this._renderingGroups[index];
  23211. if (renderingGroup) {
  23212. renderingGroup.dispose();
  23213. }
  23214. }
  23215. };
  23216. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23217. if (this._renderingGroups[renderingGroupId] === undefined) {
  23218. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23219. }
  23220. };
  23221. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23222. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23223. this._prepareRenderingGroup(renderingGroupId);
  23224. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23225. };
  23226. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23227. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23228. this._prepareRenderingGroup(renderingGroupId);
  23229. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23230. };
  23231. /**
  23232. * @param subMesh The submesh to dispatch
  23233. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23234. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23235. */
  23236. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23237. if (mesh === undefined) {
  23238. mesh = subMesh.getMesh();
  23239. }
  23240. var renderingGroupId = mesh.renderingGroupId || 0;
  23241. this._prepareRenderingGroup(renderingGroupId);
  23242. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23243. };
  23244. /**
  23245. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23246. * This allowed control for front to back rendering or reversly depending of the special needs.
  23247. *
  23248. * @param renderingGroupId The rendering group id corresponding to its index
  23249. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23250. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23251. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23252. */
  23253. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23254. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23255. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23256. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23257. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23258. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23259. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23260. if (this._renderingGroups[renderingGroupId]) {
  23261. var group = this._renderingGroups[renderingGroupId];
  23262. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23263. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23264. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23265. }
  23266. };
  23267. /**
  23268. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23269. *
  23270. * @param renderingGroupId The rendering group id corresponding to its index
  23271. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23272. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23273. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23274. */
  23275. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23276. if (depth === void 0) { depth = true; }
  23277. if (stencil === void 0) { stencil = true; }
  23278. this._autoClearDepthStencil[renderingGroupId] = {
  23279. autoClear: autoClearDepthStencil,
  23280. depth: depth,
  23281. stencil: stencil
  23282. };
  23283. };
  23284. /**
  23285. * The max id used for rendering groups (not included)
  23286. */
  23287. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23288. /**
  23289. * The min id used for rendering groups (included)
  23290. */
  23291. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23292. /**
  23293. * Used to globally prevent autoclearing scenes.
  23294. */
  23295. RenderingManager.AUTOCLEAR = true;
  23296. return RenderingManager;
  23297. }());
  23298. BABYLON.RenderingManager = RenderingManager;
  23299. })(BABYLON || (BABYLON = {}));
  23300. //# sourceMappingURL=babylon.renderingManager.js.map
  23301. var BABYLON;
  23302. (function (BABYLON) {
  23303. var RenderingGroup = /** @class */ (function () {
  23304. /**
  23305. * Creates a new rendering group.
  23306. * @param index The rendering group index
  23307. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23308. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23309. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23310. */
  23311. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23312. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23313. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23314. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23315. this.index = index;
  23316. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23317. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23318. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23319. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23320. this._particleSystems = new BABYLON.SmartArray(256);
  23321. this._spriteManagers = new BABYLON.SmartArray(256);
  23322. this._edgesRenderers = new BABYLON.SmartArray(16);
  23323. this._scene = scene;
  23324. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23325. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23326. this.transparentSortCompareFn = transparentSortCompareFn;
  23327. }
  23328. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23329. /**
  23330. * Set the opaque sort comparison function.
  23331. * If null the sub meshes will be render in the order they were created
  23332. */
  23333. set: function (value) {
  23334. this._opaqueSortCompareFn = value;
  23335. if (value) {
  23336. this._renderOpaque = this.renderOpaqueSorted;
  23337. }
  23338. else {
  23339. this._renderOpaque = RenderingGroup.renderUnsorted;
  23340. }
  23341. },
  23342. enumerable: true,
  23343. configurable: true
  23344. });
  23345. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23346. /**
  23347. * Set the alpha test sort comparison function.
  23348. * If null the sub meshes will be render in the order they were created
  23349. */
  23350. set: function (value) {
  23351. this._alphaTestSortCompareFn = value;
  23352. if (value) {
  23353. this._renderAlphaTest = this.renderAlphaTestSorted;
  23354. }
  23355. else {
  23356. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23357. }
  23358. },
  23359. enumerable: true,
  23360. configurable: true
  23361. });
  23362. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23363. /**
  23364. * Set the transparent sort comparison function.
  23365. * If null the sub meshes will be render in the order they were created
  23366. */
  23367. set: function (value) {
  23368. if (value) {
  23369. this._transparentSortCompareFn = value;
  23370. }
  23371. else {
  23372. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23373. }
  23374. this._renderTransparent = this.renderTransparentSorted;
  23375. },
  23376. enumerable: true,
  23377. configurable: true
  23378. });
  23379. /**
  23380. * Render all the sub meshes contained in the group.
  23381. * @param customRenderFunction Used to override the default render behaviour of the group.
  23382. * @returns true if rendered some submeshes.
  23383. */
  23384. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23385. if (customRenderFunction) {
  23386. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23387. return;
  23388. }
  23389. var engine = this._scene.getEngine();
  23390. // Depth only
  23391. if (this._depthOnlySubMeshes.length !== 0) {
  23392. engine.setColorWrite(false);
  23393. this._renderAlphaTest(this._depthOnlySubMeshes);
  23394. engine.setColorWrite(true);
  23395. }
  23396. // Opaque
  23397. if (this._opaqueSubMeshes.length !== 0) {
  23398. this._renderOpaque(this._opaqueSubMeshes);
  23399. }
  23400. // Alpha test
  23401. if (this._alphaTestSubMeshes.length !== 0) {
  23402. this._renderAlphaTest(this._alphaTestSubMeshes);
  23403. }
  23404. var stencilState = engine.getStencilBuffer();
  23405. engine.setStencilBuffer(false);
  23406. // Sprites
  23407. if (renderSprites) {
  23408. this._renderSprites();
  23409. }
  23410. // Particles
  23411. if (renderParticles) {
  23412. this._renderParticles(activeMeshes);
  23413. }
  23414. if (this.onBeforeTransparentRendering) {
  23415. this.onBeforeTransparentRendering();
  23416. }
  23417. // Transparent
  23418. if (this._transparentSubMeshes.length !== 0) {
  23419. this._renderTransparent(this._transparentSubMeshes);
  23420. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23421. }
  23422. // Set back stencil to false in case it changes before the edge renderer.
  23423. engine.setStencilBuffer(false);
  23424. // Edges
  23425. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23426. this._edgesRenderers.data[edgesRendererIndex].render();
  23427. }
  23428. // Restore Stencil state.
  23429. engine.setStencilBuffer(stencilState);
  23430. };
  23431. /**
  23432. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23433. * @param subMeshes The submeshes to render
  23434. */
  23435. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23436. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23437. };
  23438. /**
  23439. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23440. * @param subMeshes The submeshes to render
  23441. */
  23442. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23443. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23444. };
  23445. /**
  23446. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23447. * @param subMeshes The submeshes to render
  23448. */
  23449. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23450. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23451. };
  23452. /**
  23453. * Renders the submeshes in a specified order.
  23454. * @param subMeshes The submeshes to sort before render
  23455. * @param sortCompareFn The comparison function use to sort
  23456. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23457. * @param transparent Specifies to activate blending if true
  23458. */
  23459. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23460. var subIndex = 0;
  23461. var subMesh;
  23462. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23463. for (; subIndex < subMeshes.length; subIndex++) {
  23464. subMesh = subMeshes.data[subIndex];
  23465. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23466. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23467. }
  23468. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23469. if (sortCompareFn) {
  23470. sortedArray.sort(sortCompareFn);
  23471. }
  23472. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23473. subMesh = sortedArray[subIndex];
  23474. if (transparent) {
  23475. var material = subMesh.getMaterial();
  23476. if (material && material.needDepthPrePass) {
  23477. var engine = material.getScene().getEngine();
  23478. engine.setColorWrite(false);
  23479. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23480. subMesh.render(false);
  23481. engine.setColorWrite(true);
  23482. }
  23483. }
  23484. subMesh.render(transparent);
  23485. }
  23486. };
  23487. /**
  23488. * Renders the submeshes in the order they were dispatched (no sort applied).
  23489. * @param subMeshes The submeshes to render
  23490. */
  23491. RenderingGroup.renderUnsorted = function (subMeshes) {
  23492. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23493. var submesh = subMeshes.data[subIndex];
  23494. submesh.render(false);
  23495. }
  23496. };
  23497. /**
  23498. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23499. * are rendered back to front if in the same alpha index.
  23500. *
  23501. * @param a The first submesh
  23502. * @param b The second submesh
  23503. * @returns The result of the comparison
  23504. */
  23505. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23506. // Alpha index first
  23507. if (a._alphaIndex > b._alphaIndex) {
  23508. return 1;
  23509. }
  23510. if (a._alphaIndex < b._alphaIndex) {
  23511. return -1;
  23512. }
  23513. // Then distance to camera
  23514. return RenderingGroup.backToFrontSortCompare(a, b);
  23515. };
  23516. /**
  23517. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23518. * are rendered back to front.
  23519. *
  23520. * @param a The first submesh
  23521. * @param b The second submesh
  23522. * @returns The result of the comparison
  23523. */
  23524. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23525. // Then distance to camera
  23526. if (a._distanceToCamera < b._distanceToCamera) {
  23527. return 1;
  23528. }
  23529. if (a._distanceToCamera > b._distanceToCamera) {
  23530. return -1;
  23531. }
  23532. return 0;
  23533. };
  23534. /**
  23535. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23536. * are rendered front to back (prevent overdraw).
  23537. *
  23538. * @param a The first submesh
  23539. * @param b The second submesh
  23540. * @returns The result of the comparison
  23541. */
  23542. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23543. // Then distance to camera
  23544. if (a._distanceToCamera < b._distanceToCamera) {
  23545. return -1;
  23546. }
  23547. if (a._distanceToCamera > b._distanceToCamera) {
  23548. return 1;
  23549. }
  23550. return 0;
  23551. };
  23552. /**
  23553. * Resets the different lists of submeshes to prepare a new frame.
  23554. */
  23555. RenderingGroup.prototype.prepare = function () {
  23556. this._opaqueSubMeshes.reset();
  23557. this._transparentSubMeshes.reset();
  23558. this._alphaTestSubMeshes.reset();
  23559. this._depthOnlySubMeshes.reset();
  23560. this._particleSystems.reset();
  23561. this._spriteManagers.reset();
  23562. this._edgesRenderers.reset();
  23563. };
  23564. RenderingGroup.prototype.dispose = function () {
  23565. this._opaqueSubMeshes.dispose();
  23566. this._transparentSubMeshes.dispose();
  23567. this._alphaTestSubMeshes.dispose();
  23568. this._depthOnlySubMeshes.dispose();
  23569. this._particleSystems.dispose();
  23570. this._spriteManagers.dispose();
  23571. this._edgesRenderers.dispose();
  23572. };
  23573. /**
  23574. * Inserts the submesh in its correct queue depending on its material.
  23575. * @param subMesh The submesh to dispatch
  23576. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23577. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23578. */
  23579. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23580. // Get mesh and materials if not provided
  23581. if (mesh === undefined) {
  23582. mesh = subMesh.getMesh();
  23583. }
  23584. if (material === undefined) {
  23585. material = subMesh.getMaterial();
  23586. }
  23587. if (material === null || material === undefined) {
  23588. return;
  23589. }
  23590. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23591. this._transparentSubMeshes.push(subMesh);
  23592. }
  23593. else if (material.needAlphaTesting()) { // Alpha test
  23594. if (material.needDepthPrePass) {
  23595. this._depthOnlySubMeshes.push(subMesh);
  23596. }
  23597. this._alphaTestSubMeshes.push(subMesh);
  23598. }
  23599. else {
  23600. if (material.needDepthPrePass) {
  23601. this._depthOnlySubMeshes.push(subMesh);
  23602. }
  23603. this._opaqueSubMeshes.push(subMesh); // Opaque
  23604. }
  23605. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23606. this._edgesRenderers.push(mesh._edgesRenderer);
  23607. }
  23608. };
  23609. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23610. this._spriteManagers.push(spriteManager);
  23611. };
  23612. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23613. this._particleSystems.push(particleSystem);
  23614. };
  23615. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23616. if (this._particleSystems.length === 0) {
  23617. return;
  23618. }
  23619. // Particles
  23620. var activeCamera = this._scene.activeCamera;
  23621. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23622. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23623. var particleSystem = this._particleSystems.data[particleIndex];
  23624. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23625. continue;
  23626. }
  23627. var emitter = particleSystem.emitter;
  23628. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23629. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23630. }
  23631. }
  23632. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23633. };
  23634. RenderingGroup.prototype._renderSprites = function () {
  23635. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23636. return;
  23637. }
  23638. // Sprites
  23639. var activeCamera = this._scene.activeCamera;
  23640. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23641. for (var id = 0; id < this._spriteManagers.length; id++) {
  23642. var spriteManager = this._spriteManagers.data[id];
  23643. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23644. spriteManager.render();
  23645. }
  23646. }
  23647. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23648. };
  23649. return RenderingGroup;
  23650. }());
  23651. BABYLON.RenderingGroup = RenderingGroup;
  23652. })(BABYLON || (BABYLON = {}));
  23653. //# sourceMappingURL=babylon.renderingGroup.js.map
  23654. var BABYLON;
  23655. (function (BABYLON) {
  23656. /** @hidden */
  23657. var ClickInfo = /** @class */ (function () {
  23658. function ClickInfo() {
  23659. this._singleClick = false;
  23660. this._doubleClick = false;
  23661. this._hasSwiped = false;
  23662. this._ignore = false;
  23663. }
  23664. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23665. get: function () {
  23666. return this._singleClick;
  23667. },
  23668. set: function (b) {
  23669. this._singleClick = b;
  23670. },
  23671. enumerable: true,
  23672. configurable: true
  23673. });
  23674. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23675. get: function () {
  23676. return this._doubleClick;
  23677. },
  23678. set: function (b) {
  23679. this._doubleClick = b;
  23680. },
  23681. enumerable: true,
  23682. configurable: true
  23683. });
  23684. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23685. get: function () {
  23686. return this._hasSwiped;
  23687. },
  23688. set: function (b) {
  23689. this._hasSwiped = b;
  23690. },
  23691. enumerable: true,
  23692. configurable: true
  23693. });
  23694. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23695. get: function () {
  23696. return this._ignore;
  23697. },
  23698. set: function (b) {
  23699. this._ignore = b;
  23700. },
  23701. enumerable: true,
  23702. configurable: true
  23703. });
  23704. return ClickInfo;
  23705. }());
  23706. /**
  23707. * This class is used by the onRenderingGroupObservable
  23708. */
  23709. var RenderingGroupInfo = /** @class */ (function () {
  23710. function RenderingGroupInfo() {
  23711. }
  23712. /**
  23713. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23714. * This stage will be fired no matter what
  23715. */
  23716. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23717. /**
  23718. * Called before opaque object are rendered.
  23719. * This stage will be fired only if there's 3D Opaque content to render
  23720. */
  23721. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23722. /**
  23723. * Called after the opaque objects are rendered and before the transparent ones
  23724. * This stage will be fired only if there's 3D transparent content to render
  23725. */
  23726. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23727. /**
  23728. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23729. * This stage will be fired no matter what
  23730. */
  23731. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23732. return RenderingGroupInfo;
  23733. }());
  23734. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23735. /**
  23736. * Represents a scene to be rendered by the engine.
  23737. * @see http://doc.babylonjs.com/features/scene
  23738. */
  23739. var Scene = /** @class */ (function () {
  23740. /**
  23741. * Creates a new Scene
  23742. * @param engine defines the engine to use to render this scene
  23743. */
  23744. function Scene(engine) {
  23745. // Members
  23746. /**
  23747. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23748. */
  23749. this.autoClear = true;
  23750. /**
  23751. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23752. */
  23753. this.autoClearDepthAndStencil = true;
  23754. /**
  23755. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23756. */
  23757. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23758. /**
  23759. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23760. */
  23761. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23762. this._forceWireframe = false;
  23763. this._forcePointsCloud = false;
  23764. /**
  23765. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23766. */
  23767. this.forceShowBoundingBoxes = false;
  23768. /**
  23769. * Gets or sets a boolean indicating if animations are enabled
  23770. */
  23771. this.animationsEnabled = true;
  23772. this._animationPropertiesOverride = null;
  23773. /**
  23774. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23775. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23776. */
  23777. this.useConstantAnimationDeltaTime = false;
  23778. /**
  23779. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23780. * Please note that it requires to run a ray cast through the scene on every frame
  23781. */
  23782. this.constantlyUpdateMeshUnderPointer = false;
  23783. /**
  23784. * Defines the HTML cursor to use when hovering over interactive elements
  23785. */
  23786. this.hoverCursor = "pointer";
  23787. /**
  23788. * Defines the HTML default cursor to use (empty by default)
  23789. */
  23790. this.defaultCursor = "";
  23791. /**
  23792. * This is used to call preventDefault() on pointer down
  23793. * in order to block unwanted artifacts like system double clicks
  23794. */
  23795. this.preventDefaultOnPointerDown = true;
  23796. // Metadata
  23797. /**
  23798. * Gets or sets user defined metadata
  23799. */
  23800. this.metadata = null;
  23801. /**
  23802. * Use this array to add regular expressions used to disable offline support for specific urls
  23803. */
  23804. this.disableOfflineSupportExceptionRules = new Array();
  23805. /**
  23806. * An event triggered when the scene is disposed.
  23807. */
  23808. this.onDisposeObservable = new BABYLON.Observable();
  23809. this._onDisposeObserver = null;
  23810. /**
  23811. * An event triggered before rendering the scene (right after animations and physics)
  23812. */
  23813. this.onBeforeRenderObservable = new BABYLON.Observable();
  23814. this._onBeforeRenderObserver = null;
  23815. /**
  23816. * An event triggered after rendering the scene
  23817. */
  23818. this.onAfterRenderObservable = new BABYLON.Observable();
  23819. this._onAfterRenderObserver = null;
  23820. /**
  23821. * An event triggered before animating the scene
  23822. */
  23823. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23824. /**
  23825. * An event triggered after animations processing
  23826. */
  23827. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23828. /**
  23829. * An event triggered before draw calls are ready to be sent
  23830. */
  23831. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23832. /**
  23833. * An event triggered after draw calls have been sent
  23834. */
  23835. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23836. /**
  23837. * An event triggered when physic simulation is about to be run
  23838. */
  23839. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23840. /**
  23841. * An event triggered when physic simulation has been done
  23842. */
  23843. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23844. /**
  23845. * An event triggered when the scene is ready
  23846. */
  23847. this.onReadyObservable = new BABYLON.Observable();
  23848. /**
  23849. * An event triggered before rendering a camera
  23850. */
  23851. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23852. this._onBeforeCameraRenderObserver = null;
  23853. /**
  23854. * An event triggered after rendering a camera
  23855. */
  23856. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23857. this._onAfterCameraRenderObserver = null;
  23858. /**
  23859. * An event triggered when active meshes evaluation is about to start
  23860. */
  23861. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23862. /**
  23863. * An event triggered when active meshes evaluation is done
  23864. */
  23865. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23866. /**
  23867. * An event triggered when particles rendering is about to start
  23868. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23869. */
  23870. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23871. /**
  23872. * An event triggered when particles rendering is done
  23873. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23874. */
  23875. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23876. /**
  23877. * An event triggered when sprites rendering is about to start
  23878. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23879. */
  23880. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23881. /**
  23882. * An event triggered when sprites rendering is done
  23883. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23884. */
  23885. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23886. /**
  23887. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23888. */
  23889. this.onDataLoadedObservable = new BABYLON.Observable();
  23890. /**
  23891. * An event triggered when a camera is created
  23892. */
  23893. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23894. /**
  23895. * An event triggered when a camera is removed
  23896. */
  23897. this.onCameraRemovedObservable = new BABYLON.Observable();
  23898. /**
  23899. * An event triggered when a light is created
  23900. */
  23901. this.onNewLightAddedObservable = new BABYLON.Observable();
  23902. /**
  23903. * An event triggered when a light is removed
  23904. */
  23905. this.onLightRemovedObservable = new BABYLON.Observable();
  23906. /**
  23907. * An event triggered when a geometry is created
  23908. */
  23909. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23910. /**
  23911. * An event triggered when a geometry is removed
  23912. */
  23913. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23914. /**
  23915. * An event triggered when a transform node is created
  23916. */
  23917. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23918. /**
  23919. * An event triggered when a transform node is removed
  23920. */
  23921. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23922. /**
  23923. * An event triggered when a mesh is created
  23924. */
  23925. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23926. /**
  23927. * An event triggered when a mesh is removed
  23928. */
  23929. this.onMeshRemovedObservable = new BABYLON.Observable();
  23930. /**
  23931. * An event triggered when render targets are about to be rendered
  23932. * Can happen multiple times per frame.
  23933. */
  23934. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23935. /**
  23936. * An event triggered when render targets were rendered.
  23937. * Can happen multiple times per frame.
  23938. */
  23939. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23940. /**
  23941. * An event triggered before calculating deterministic simulation step
  23942. */
  23943. this.onBeforeStepObservable = new BABYLON.Observable();
  23944. /**
  23945. * An event triggered after calculating deterministic simulation step
  23946. */
  23947. this.onAfterStepObservable = new BABYLON.Observable();
  23948. /**
  23949. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23950. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23951. * 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)
  23952. */
  23953. this.onRenderingGroupObservable = new BABYLON.Observable();
  23954. // Animations
  23955. /**
  23956. * Gets a list of Animations associated with the scene
  23957. */
  23958. this.animations = [];
  23959. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23960. /**
  23961. * 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).
  23962. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23963. */
  23964. this.onPrePointerObservable = new BABYLON.Observable();
  23965. /**
  23966. * Observable event triggered each time an input event is received from the rendering canvas
  23967. */
  23968. this.onPointerObservable = new BABYLON.Observable();
  23969. this._meshPickProceed = false;
  23970. this._currentPickResult = null;
  23971. this._previousPickResult = null;
  23972. this._totalPointersPressed = 0;
  23973. this._doubleClickOccured = false;
  23974. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23975. this.cameraToUseForPointers = null;
  23976. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23977. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23978. this._startingPointerTime = 0;
  23979. this._previousStartingPointerTime = 0;
  23980. this._pointerCaptures = {};
  23981. // Deterministic lockstep
  23982. this._timeAccumulator = 0;
  23983. this._currentStepId = 0;
  23984. this._currentInternalStep = 0;
  23985. // Keyboard
  23986. /**
  23987. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23988. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23989. */
  23990. this.onPreKeyboardObservable = new BABYLON.Observable();
  23991. /**
  23992. * Observable event triggered each time an keyboard event is received from the hosting window
  23993. */
  23994. this.onKeyboardObservable = new BABYLON.Observable();
  23995. // Coordinates system
  23996. this._useRightHandedSystem = false;
  23997. // Fog
  23998. this._fogEnabled = true;
  23999. this._fogMode = Scene.FOGMODE_NONE;
  24000. /**
  24001. * Gets or sets the fog color to use
  24002. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24003. */
  24004. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24005. /**
  24006. * Gets or sets the fog density to use
  24007. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24008. */
  24009. this.fogDensity = 0.1;
  24010. /**
  24011. * Gets or sets the fog start distance to use
  24012. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24013. */
  24014. this.fogStart = 0;
  24015. /**
  24016. * Gets or sets the fog end distance to use
  24017. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24018. */
  24019. this.fogEnd = 1000.0;
  24020. // Lights
  24021. this._shadowsEnabled = true;
  24022. this._lightsEnabled = true;
  24023. /**
  24024. * All of the lights added to this scene
  24025. * @see http://doc.babylonjs.com/babylon101/lights
  24026. */
  24027. this.lights = new Array();
  24028. // Cameras
  24029. /** All of the cameras added to this scene.
  24030. * @see http://doc.babylonjs.com/babylon101/cameras
  24031. */
  24032. this.cameras = new Array();
  24033. /** All of the active cameras added to this scene. */
  24034. this.activeCameras = new Array();
  24035. // Meshes
  24036. /**
  24037. * All of the tranform nodes added to this scene
  24038. * @see http://doc.babylonjs.com/how_to/transformnode
  24039. */
  24040. this.transformNodes = new Array();
  24041. /**
  24042. * All of the (abstract) meshes added to this scene
  24043. */
  24044. this.meshes = new Array();
  24045. /**
  24046. * All of the animation groups added to this scene
  24047. * @see http://doc.babylonjs.com/how_to/group
  24048. */
  24049. this.animationGroups = new Array();
  24050. // Geometries
  24051. this._geometries = new Array();
  24052. /**
  24053. * All of the materials added to this scene
  24054. * @see http://doc.babylonjs.com/babylon101/materials
  24055. */
  24056. this.materials = new Array();
  24057. /**
  24058. * All of the multi-materials added to this scene
  24059. * @see http://doc.babylonjs.com/how_to/multi_materials
  24060. */
  24061. this.multiMaterials = new Array();
  24062. // Textures
  24063. this._texturesEnabled = true;
  24064. /**
  24065. * All of the textures added to this scene
  24066. */
  24067. this.textures = new Array();
  24068. // Particles
  24069. /**
  24070. * Gets or sets a boolean indicating if particles are enabled on this scene
  24071. */
  24072. this.particlesEnabled = true;
  24073. /**
  24074. * All of the particle systems added to this scene
  24075. * @see http://doc.babylonjs.com/babylon101/particles
  24076. */
  24077. this.particleSystems = new Array();
  24078. // Sprites
  24079. /**
  24080. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24081. */
  24082. this.spritesEnabled = true;
  24083. /**
  24084. * All of the sprite managers added to this scene
  24085. * @see http://doc.babylonjs.com/babylon101/sprites
  24086. */
  24087. this.spriteManagers = new Array();
  24088. /**
  24089. * The list of layers (background and foreground) of the scene
  24090. */
  24091. this.layers = new Array();
  24092. /**
  24093. * The list of effect layers (highlights/glow) added to the scene
  24094. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24095. * @see http://doc.babylonjs.com/how_to/glow_layer
  24096. */
  24097. this.effectLayers = new Array();
  24098. // Skeletons
  24099. this._skeletonsEnabled = true;
  24100. /**
  24101. * The list of skeletons added to the scene
  24102. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24103. */
  24104. this.skeletons = new Array();
  24105. // Morph targets
  24106. /**
  24107. * The list of morph target managers added to the scene
  24108. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24109. */
  24110. this.morphTargetManagers = new Array();
  24111. // Lens flares
  24112. /**
  24113. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24114. */
  24115. this.lensFlaresEnabled = true;
  24116. /**
  24117. * The list of lens flare system added to the scene
  24118. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24119. */
  24120. this.lensFlareSystems = new Array();
  24121. // Collisions
  24122. /**
  24123. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24124. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24125. */
  24126. this.collisionsEnabled = true;
  24127. /**
  24128. * Defines the gravity applied to this scene (used only for collisions)
  24129. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24130. */
  24131. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24132. // Postprocesses
  24133. /**
  24134. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24135. */
  24136. this.postProcessesEnabled = true;
  24137. /**
  24138. * The list of postprocesses added to the scene
  24139. */
  24140. this.postProcesses = new Array();
  24141. // Customs render targets
  24142. /**
  24143. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24144. */
  24145. this.renderTargetsEnabled = true;
  24146. /**
  24147. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24148. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24149. */
  24150. this.dumpNextRenderTargets = false;
  24151. /**
  24152. * The list of user defined render targets added to the scene
  24153. */
  24154. this.customRenderTargets = new Array();
  24155. /**
  24156. * Gets the list of meshes imported to the scene through SceneLoader
  24157. */
  24158. this.importedMeshesFiles = new Array();
  24159. // Probes
  24160. /**
  24161. * Gets or sets a boolean indicating if probes are enabled on this scene
  24162. */
  24163. this.probesEnabled = true;
  24164. /**
  24165. * The list of reflection probes added to the scene
  24166. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24167. */
  24168. this.reflectionProbes = new Array();
  24169. /** @hidden */
  24170. this._actionManagers = new Array();
  24171. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24172. // Procedural textures
  24173. /**
  24174. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24175. */
  24176. this.proceduralTexturesEnabled = true;
  24177. /**
  24178. * The list of procedural textures added to the scene
  24179. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24180. */
  24181. this.proceduralTextures = new Array();
  24182. /**
  24183. * The list of sound tracks added to the scene
  24184. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24185. */
  24186. this.soundTracks = new Array();
  24187. this._audioEnabled = true;
  24188. this._headphone = false;
  24189. // Performance counters
  24190. this._totalVertices = new BABYLON.PerfCounter();
  24191. /** @hidden */
  24192. this._activeIndices = new BABYLON.PerfCounter();
  24193. /** @hidden */
  24194. this._activeParticles = new BABYLON.PerfCounter();
  24195. /** @hidden */
  24196. this._activeBones = new BABYLON.PerfCounter();
  24197. this._animationTime = 0;
  24198. /**
  24199. * Gets or sets a general scale for animation speed
  24200. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24201. */
  24202. this.animationTimeScale = 1;
  24203. this._renderId = 0;
  24204. this._executeWhenReadyTimeoutId = -1;
  24205. this._intermediateRendering = false;
  24206. this._viewUpdateFlag = -1;
  24207. this._projectionUpdateFlag = -1;
  24208. this._alternateViewUpdateFlag = -1;
  24209. this._alternateProjectionUpdateFlag = -1;
  24210. /** @hidden */
  24211. this._toBeDisposed = new BABYLON.SmartArray(256);
  24212. this._activeRequests = new Array();
  24213. this._pendingData = new Array();
  24214. this._isDisposed = false;
  24215. /**
  24216. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24217. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24218. */
  24219. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24220. this._activeMeshes = new BABYLON.SmartArray(256);
  24221. this._processedMaterials = new BABYLON.SmartArray(256);
  24222. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24223. /** @hidden */
  24224. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24225. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24226. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24227. /** @hidden */
  24228. this._activeAnimatables = new Array();
  24229. this._transformMatrix = BABYLON.Matrix.Zero();
  24230. this._useAlternateCameraConfiguration = false;
  24231. this._alternateRendering = false;
  24232. /**
  24233. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24234. * This is useful if there are more lights that the maximum simulteanous authorized
  24235. */
  24236. this.requireLightSorting = false;
  24237. this._depthRenderer = {};
  24238. this._activeMeshesFrozen = false;
  24239. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24240. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24241. this._engine.scenes.push(this);
  24242. this._uid = null;
  24243. this._renderingManager = new BABYLON.RenderingManager(this);
  24244. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24245. if (BABYLON.OutlineRenderer) {
  24246. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24247. }
  24248. if (BABYLON.Tools.IsWindowObjectExist()) {
  24249. this.attachControl();
  24250. }
  24251. //simplification queue
  24252. if (BABYLON.SimplificationQueue) {
  24253. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24254. }
  24255. //collision coordinator initialization. For now legacy per default.
  24256. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24257. // Uniform Buffer
  24258. this._createUbo();
  24259. // Default Image processing definition.
  24260. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24261. }
  24262. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24263. /** The fog is deactivated */
  24264. get: function () {
  24265. return Scene._FOGMODE_NONE;
  24266. },
  24267. enumerable: true,
  24268. configurable: true
  24269. });
  24270. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24271. /** The fog density is following an exponential function */
  24272. get: function () {
  24273. return Scene._FOGMODE_EXP;
  24274. },
  24275. enumerable: true,
  24276. configurable: true
  24277. });
  24278. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24279. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24280. get: function () {
  24281. return Scene._FOGMODE_EXP2;
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24287. /** The fog density is following a linear function. */
  24288. get: function () {
  24289. return Scene._FOGMODE_LINEAR;
  24290. },
  24291. enumerable: true,
  24292. configurable: true
  24293. });
  24294. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24295. /**
  24296. * Texture used in all pbr material as the reflection texture.
  24297. * As in the majority of the scene they are the same (exception for multi room and so on),
  24298. * this is easier to reference from here than from all the materials.
  24299. */
  24300. get: function () {
  24301. return this._environmentTexture;
  24302. },
  24303. /**
  24304. * Texture used in all pbr material as the reflection texture.
  24305. * As in the majority of the scene they are the same (exception for multi room and so on),
  24306. * this is easier to set here than in all the materials.
  24307. */
  24308. set: function (value) {
  24309. if (this._environmentTexture === value) {
  24310. return;
  24311. }
  24312. this._environmentTexture = value;
  24313. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24314. },
  24315. enumerable: true,
  24316. configurable: true
  24317. });
  24318. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24319. /**
  24320. * Default image processing configuration used either in the rendering
  24321. * Forward main pass or through the imageProcessingPostProcess if present.
  24322. * As in the majority of the scene they are the same (exception for multi camera),
  24323. * this is easier to reference from here than from all the materials and post process.
  24324. *
  24325. * No setter as we it is a shared configuration, you can set the values instead.
  24326. */
  24327. get: function () {
  24328. return this._imageProcessingConfiguration;
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24334. get: function () {
  24335. return this._forceWireframe;
  24336. },
  24337. /**
  24338. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24339. */
  24340. set: function (value) {
  24341. if (this._forceWireframe === value) {
  24342. return;
  24343. }
  24344. this._forceWireframe = value;
  24345. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24346. },
  24347. enumerable: true,
  24348. configurable: true
  24349. });
  24350. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24351. get: function () {
  24352. return this._forcePointsCloud;
  24353. },
  24354. /**
  24355. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24356. */
  24357. set: function (value) {
  24358. if (this._forcePointsCloud === value) {
  24359. return;
  24360. }
  24361. this._forcePointsCloud = value;
  24362. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24363. },
  24364. enumerable: true,
  24365. configurable: true
  24366. });
  24367. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24368. /**
  24369. * Gets or sets the animation properties override
  24370. */
  24371. get: function () {
  24372. return this._animationPropertiesOverride;
  24373. },
  24374. set: function (value) {
  24375. this._animationPropertiesOverride = value;
  24376. },
  24377. enumerable: true,
  24378. configurable: true
  24379. });
  24380. Object.defineProperty(Scene.prototype, "onDispose", {
  24381. /** Sets a function to be executed when this scene is disposed. */
  24382. set: function (callback) {
  24383. if (this._onDisposeObserver) {
  24384. this.onDisposeObservable.remove(this._onDisposeObserver);
  24385. }
  24386. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24387. },
  24388. enumerable: true,
  24389. configurable: true
  24390. });
  24391. Object.defineProperty(Scene.prototype, "beforeRender", {
  24392. /** Sets a function to be executed before rendering this scene */
  24393. set: function (callback) {
  24394. if (this._onBeforeRenderObserver) {
  24395. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24396. }
  24397. if (callback) {
  24398. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24399. }
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(Scene.prototype, "afterRender", {
  24405. /** Sets a function to be executed after rendering this scene */
  24406. set: function (callback) {
  24407. if (this._onAfterRenderObserver) {
  24408. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24409. }
  24410. if (callback) {
  24411. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24412. }
  24413. },
  24414. enumerable: true,
  24415. configurable: true
  24416. });
  24417. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24418. /** Sets a function to be executed before rendering a camera*/
  24419. set: function (callback) {
  24420. if (this._onBeforeCameraRenderObserver) {
  24421. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24422. }
  24423. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24424. },
  24425. enumerable: true,
  24426. configurable: true
  24427. });
  24428. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24429. /** Sets a function to be executed after rendering a camera*/
  24430. set: function (callback) {
  24431. if (this._onAfterCameraRenderObserver) {
  24432. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24433. }
  24434. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24435. },
  24436. enumerable: true,
  24437. configurable: true
  24438. });
  24439. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24440. /**
  24441. * Gets the gamepad manager associated with the scene
  24442. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24443. */
  24444. get: function () {
  24445. if (!this._gamepadManager) {
  24446. this._gamepadManager = new BABYLON.GamepadManager(this);
  24447. }
  24448. return this._gamepadManager;
  24449. },
  24450. enumerable: true,
  24451. configurable: true
  24452. });
  24453. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24454. /**
  24455. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24456. */
  24457. get: function () {
  24458. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24464. get: function () {
  24465. return this._useRightHandedSystem;
  24466. },
  24467. /**
  24468. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24469. */
  24470. set: function (value) {
  24471. if (this._useRightHandedSystem === value) {
  24472. return;
  24473. }
  24474. this._useRightHandedSystem = value;
  24475. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. /**
  24481. * Sets the step Id used by deterministic lock step
  24482. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24483. * @param newStepId defines the step Id
  24484. */
  24485. Scene.prototype.setStepId = function (newStepId) {
  24486. this._currentStepId = newStepId;
  24487. };
  24488. ;
  24489. /**
  24490. * Gets the step Id used by deterministic lock step
  24491. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24492. * @returns the step Id
  24493. */
  24494. Scene.prototype.getStepId = function () {
  24495. return this._currentStepId;
  24496. };
  24497. ;
  24498. /**
  24499. * Gets the internal step used by deterministic lock step
  24500. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24501. * @returns the internal step
  24502. */
  24503. Scene.prototype.getInternalStep = function () {
  24504. return this._currentInternalStep;
  24505. };
  24506. ;
  24507. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24508. get: function () {
  24509. return this._fogEnabled;
  24510. },
  24511. /**
  24512. * Gets or sets a boolean indicating if fog is enabled on this scene
  24513. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24514. */
  24515. set: function (value) {
  24516. if (this._fogEnabled === value) {
  24517. return;
  24518. }
  24519. this._fogEnabled = value;
  24520. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24521. },
  24522. enumerable: true,
  24523. configurable: true
  24524. });
  24525. Object.defineProperty(Scene.prototype, "fogMode", {
  24526. get: function () {
  24527. return this._fogMode;
  24528. },
  24529. /**
  24530. * Gets or sets the fog mode to use
  24531. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24532. */
  24533. set: function (value) {
  24534. if (this._fogMode === value) {
  24535. return;
  24536. }
  24537. this._fogMode = value;
  24538. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24544. get: function () {
  24545. return this._shadowsEnabled;
  24546. },
  24547. /**
  24548. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24549. */
  24550. set: function (value) {
  24551. if (this._shadowsEnabled === value) {
  24552. return;
  24553. }
  24554. this._shadowsEnabled = value;
  24555. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24556. },
  24557. enumerable: true,
  24558. configurable: true
  24559. });
  24560. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24561. get: function () {
  24562. return this._lightsEnabled;
  24563. },
  24564. /**
  24565. * Gets or sets a boolean indicating if lights are enabled on this scene
  24566. */
  24567. set: function (value) {
  24568. if (this._lightsEnabled === value) {
  24569. return;
  24570. }
  24571. this._lightsEnabled = value;
  24572. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24578. /** The default material used on meshes when no material is affected */
  24579. get: function () {
  24580. if (!this._defaultMaterial) {
  24581. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24582. }
  24583. return this._defaultMaterial;
  24584. },
  24585. /** The default material used on meshes when no material is affected */
  24586. set: function (value) {
  24587. this._defaultMaterial = value;
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24593. get: function () {
  24594. return this._texturesEnabled;
  24595. },
  24596. /**
  24597. * Gets or sets a boolean indicating if textures are enabled on this scene
  24598. */
  24599. set: function (value) {
  24600. if (this._texturesEnabled === value) {
  24601. return;
  24602. }
  24603. this._texturesEnabled = value;
  24604. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24605. },
  24606. enumerable: true,
  24607. configurable: true
  24608. });
  24609. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24610. get: function () {
  24611. return this._skeletonsEnabled;
  24612. },
  24613. /**
  24614. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24615. */
  24616. set: function (value) {
  24617. if (this._skeletonsEnabled === value) {
  24618. return;
  24619. }
  24620. this._skeletonsEnabled = value;
  24621. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24627. /**
  24628. * Gets the postprocess render pipeline manager
  24629. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24630. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24631. */
  24632. get: function () {
  24633. if (!this._postProcessRenderPipelineManager) {
  24634. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24635. }
  24636. return this._postProcessRenderPipelineManager;
  24637. },
  24638. enumerable: true,
  24639. configurable: true
  24640. });
  24641. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24642. /**
  24643. * Gets the main soundtrack associated with the scene
  24644. */
  24645. get: function () {
  24646. if (!this._mainSoundTrack) {
  24647. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24648. }
  24649. return this._mainSoundTrack;
  24650. },
  24651. enumerable: true,
  24652. configurable: true
  24653. });
  24654. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24655. /** @hidden */
  24656. get: function () {
  24657. return this._alternateRendering;
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24663. /**
  24664. * Gets the list of frustum planes (built from the active camera)
  24665. */
  24666. get: function () {
  24667. return this._frustumPlanes;
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24673. /**
  24674. * Gets the current geometry buffer associated to the scene.
  24675. */
  24676. get: function () {
  24677. return this._geometryBufferRenderer;
  24678. },
  24679. /**
  24680. * Sets the current geometry buffer for the scene.
  24681. */
  24682. set: function (geometryBufferRenderer) {
  24683. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24684. this._geometryBufferRenderer = geometryBufferRenderer;
  24685. }
  24686. },
  24687. enumerable: true,
  24688. configurable: true
  24689. });
  24690. Object.defineProperty(Scene.prototype, "debugLayer", {
  24691. /**
  24692. * Gets the debug layer associated with the scene
  24693. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24694. */
  24695. get: function () {
  24696. if (!this._debugLayer) {
  24697. this._debugLayer = new BABYLON.DebugLayer(this);
  24698. }
  24699. return this._debugLayer;
  24700. },
  24701. enumerable: true,
  24702. configurable: true
  24703. });
  24704. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24705. /**
  24706. * Gets a boolean indicating if collisions are processed on a web worker
  24707. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24708. */
  24709. get: function () {
  24710. return this._workerCollisions;
  24711. },
  24712. set: function (enabled) {
  24713. if (!BABYLON.CollisionCoordinatorLegacy) {
  24714. return;
  24715. }
  24716. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24717. this._workerCollisions = enabled;
  24718. if (this.collisionCoordinator) {
  24719. this.collisionCoordinator.destroy();
  24720. }
  24721. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24722. this.collisionCoordinator.init(this);
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24728. /**
  24729. * Gets the octree used to boost mesh selection (picking)
  24730. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24731. */
  24732. get: function () {
  24733. return this._selectionOctree;
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24739. /**
  24740. * Gets the mesh that is currently under the pointer
  24741. */
  24742. get: function () {
  24743. return this._pointerOverMesh;
  24744. },
  24745. enumerable: true,
  24746. configurable: true
  24747. });
  24748. Object.defineProperty(Scene.prototype, "pointerX", {
  24749. /**
  24750. * Gets the current on-screen X position of the pointer
  24751. */
  24752. get: function () {
  24753. return this._pointerX;
  24754. },
  24755. enumerable: true,
  24756. configurable: true
  24757. });
  24758. Object.defineProperty(Scene.prototype, "pointerY", {
  24759. /**
  24760. * Gets the current on-screen Y position of the pointer
  24761. */
  24762. get: function () {
  24763. return this._pointerY;
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. /**
  24769. * Gets the cached material (ie. the latest rendered one)
  24770. * @returns the cached material
  24771. */
  24772. Scene.prototype.getCachedMaterial = function () {
  24773. return this._cachedMaterial;
  24774. };
  24775. /**
  24776. * Gets the cached effect (ie. the latest rendered one)
  24777. * @returns the cached effect
  24778. */
  24779. Scene.prototype.getCachedEffect = function () {
  24780. return this._cachedEffect;
  24781. };
  24782. /**
  24783. * Gets the cached visibility state (ie. the latest rendered one)
  24784. * @returns the cached visibility state
  24785. */
  24786. Scene.prototype.getCachedVisibility = function () {
  24787. return this._cachedVisibility;
  24788. };
  24789. /**
  24790. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24791. * @param material defines the current material
  24792. * @param effect defines the current effect
  24793. * @param visibility defines the current visibility state
  24794. * @returns true if one parameter is not cached
  24795. */
  24796. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24797. if (visibility === void 0) { visibility = 1; }
  24798. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24799. };
  24800. /**
  24801. * Gets the bounding box renderer associated with the scene
  24802. * @returns a BoundingBoxRenderer
  24803. */
  24804. Scene.prototype.getBoundingBoxRenderer = function () {
  24805. if (!this._boundingBoxRenderer) {
  24806. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24807. }
  24808. return this._boundingBoxRenderer;
  24809. };
  24810. /**
  24811. * Gets the outline renderer associated with the scene
  24812. * @returns a OutlineRenderer
  24813. */
  24814. Scene.prototype.getOutlineRenderer = function () {
  24815. return this._outlineRenderer;
  24816. };
  24817. /**
  24818. * Gets the engine associated with the scene
  24819. * @returns an Engine
  24820. */
  24821. Scene.prototype.getEngine = function () {
  24822. return this._engine;
  24823. };
  24824. /**
  24825. * Gets the total number of vertices rendered per frame
  24826. * @returns the total number of vertices rendered per frame
  24827. */
  24828. Scene.prototype.getTotalVertices = function () {
  24829. return this._totalVertices.current;
  24830. };
  24831. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24832. /**
  24833. * Gets the performance counter for total vertices
  24834. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24835. */
  24836. get: function () {
  24837. return this._totalVertices;
  24838. },
  24839. enumerable: true,
  24840. configurable: true
  24841. });
  24842. /**
  24843. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24844. * @returns the total number of active indices rendered per frame
  24845. */
  24846. Scene.prototype.getActiveIndices = function () {
  24847. return this._activeIndices.current;
  24848. };
  24849. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24850. /**
  24851. * Gets the performance counter for active indices
  24852. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24853. */
  24854. get: function () {
  24855. return this._activeIndices;
  24856. },
  24857. enumerable: true,
  24858. configurable: true
  24859. });
  24860. /**
  24861. * Gets the total number of active particles rendered per frame
  24862. * @returns the total number of active particles rendered per frame
  24863. */
  24864. Scene.prototype.getActiveParticles = function () {
  24865. return this._activeParticles.current;
  24866. };
  24867. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24868. /**
  24869. * Gets the performance counter for active particles
  24870. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24871. */
  24872. get: function () {
  24873. return this._activeParticles;
  24874. },
  24875. enumerable: true,
  24876. configurable: true
  24877. });
  24878. /**
  24879. * Gets the total number of active bones rendered per frame
  24880. * @returns the total number of active bones rendered per frame
  24881. */
  24882. Scene.prototype.getActiveBones = function () {
  24883. return this._activeBones.current;
  24884. };
  24885. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24886. /**
  24887. * Gets the performance counter for active bones
  24888. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24889. */
  24890. get: function () {
  24891. return this._activeBones;
  24892. },
  24893. enumerable: true,
  24894. configurable: true
  24895. });
  24896. /** @hidden */
  24897. Scene.prototype.getInterFramePerfCounter = function () {
  24898. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24899. return 0;
  24900. };
  24901. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24902. /** @hidden */
  24903. get: function () {
  24904. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24905. return null;
  24906. },
  24907. enumerable: true,
  24908. configurable: true
  24909. });
  24910. /** @hidden */
  24911. Scene.prototype.getLastFrameDuration = function () {
  24912. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24913. return 0;
  24914. };
  24915. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24916. /** @hidden */
  24917. get: function () {
  24918. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24919. return null;
  24920. },
  24921. enumerable: true,
  24922. configurable: true
  24923. });
  24924. /** @hidden */
  24925. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24926. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24927. return 0;
  24928. };
  24929. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24930. /** @hidden */
  24931. get: function () {
  24932. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24933. return null;
  24934. },
  24935. enumerable: true,
  24936. configurable: true
  24937. });
  24938. /**
  24939. * Gets the array of active meshes
  24940. * @returns an array of AbstractMesh
  24941. */
  24942. Scene.prototype.getActiveMeshes = function () {
  24943. return this._activeMeshes;
  24944. };
  24945. /** @hidden */
  24946. Scene.prototype.getRenderTargetsDuration = function () {
  24947. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24948. return 0;
  24949. };
  24950. /** @hidden */
  24951. Scene.prototype.getRenderDuration = function () {
  24952. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24953. return 0;
  24954. };
  24955. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24956. /** @hidden */
  24957. get: function () {
  24958. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24959. return null;
  24960. },
  24961. enumerable: true,
  24962. configurable: true
  24963. });
  24964. /** @hidden */
  24965. Scene.prototype.getParticlesDuration = function () {
  24966. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24967. return 0;
  24968. };
  24969. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24970. /** @hidden */
  24971. get: function () {
  24972. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24973. return null;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. /** @hidden */
  24979. Scene.prototype.getSpritesDuration = function () {
  24980. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24981. return 0;
  24982. };
  24983. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24984. /** @hidden */
  24985. get: function () {
  24986. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24987. return null;
  24988. },
  24989. enumerable: true,
  24990. configurable: true
  24991. });
  24992. /**
  24993. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24994. * @returns a number
  24995. */
  24996. Scene.prototype.getAnimationRatio = function () {
  24997. return this._animationRatio;
  24998. };
  24999. /**
  25000. * Gets an unique Id for the current frame
  25001. * @returns a number
  25002. */
  25003. Scene.prototype.getRenderId = function () {
  25004. return this._renderId;
  25005. };
  25006. /** Call this function if you want to manually increment the render Id*/
  25007. Scene.prototype.incrementRenderId = function () {
  25008. this._renderId++;
  25009. };
  25010. Scene.prototype._updatePointerPosition = function (evt) {
  25011. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25012. if (!canvasRect) {
  25013. return;
  25014. }
  25015. this._pointerX = evt.clientX - canvasRect.left;
  25016. this._pointerY = evt.clientY - canvasRect.top;
  25017. this._unTranslatedPointerX = this._pointerX;
  25018. this._unTranslatedPointerY = this._pointerY;
  25019. };
  25020. Scene.prototype._createUbo = function () {
  25021. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25022. this._sceneUbo.addUniform("viewProjection", 16);
  25023. this._sceneUbo.addUniform("view", 16);
  25024. };
  25025. Scene.prototype._createAlternateUbo = function () {
  25026. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25027. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25028. this._alternateSceneUbo.addUniform("view", 16);
  25029. };
  25030. // Pointers handling
  25031. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25032. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25033. if (result) {
  25034. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25035. }
  25036. return result;
  25037. };
  25038. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25039. if (pointerInfo.pickInfo) {
  25040. if (!pointerInfo.pickInfo.ray) {
  25041. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25042. }
  25043. }
  25044. };
  25045. /**
  25046. * Use this method to simulate a pointer move on a mesh
  25047. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25048. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25049. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25050. * @returns the current scene
  25051. */
  25052. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25053. var evt = new PointerEvent("pointermove", pointerEventInit);
  25054. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25055. return this;
  25056. }
  25057. return this._processPointerMove(pickResult, evt);
  25058. };
  25059. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25060. var canvas = this._engine.getRenderingCanvas();
  25061. if (!canvas) {
  25062. return this;
  25063. }
  25064. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25065. this.setPointerOverSprite(null);
  25066. this.setPointerOverMesh(pickResult.pickedMesh);
  25067. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25068. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25069. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25070. }
  25071. else {
  25072. canvas.style.cursor = this.hoverCursor;
  25073. }
  25074. }
  25075. else {
  25076. canvas.style.cursor = this.defaultCursor;
  25077. }
  25078. }
  25079. else {
  25080. this.setPointerOverMesh(null);
  25081. // Sprites
  25082. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25083. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25084. this.setPointerOverSprite(pickResult.pickedSprite);
  25085. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25086. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25087. }
  25088. else {
  25089. canvas.style.cursor = this.hoverCursor;
  25090. }
  25091. }
  25092. else {
  25093. this.setPointerOverSprite(null);
  25094. // Restore pointer
  25095. canvas.style.cursor = this.defaultCursor;
  25096. }
  25097. }
  25098. if (pickResult) {
  25099. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25100. if (this.onPointerMove) {
  25101. this.onPointerMove(evt, pickResult, type);
  25102. }
  25103. if (this.onPointerObservable.hasObservers()) {
  25104. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25105. this._setRayOnPointerInfo(pi);
  25106. this.onPointerObservable.notifyObservers(pi, type);
  25107. }
  25108. }
  25109. return this;
  25110. };
  25111. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25112. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25113. if (pickResult) {
  25114. pi.ray = pickResult.ray;
  25115. }
  25116. this.onPrePointerObservable.notifyObservers(pi, type);
  25117. if (pi.skipOnPointerObservable) {
  25118. return true;
  25119. }
  25120. else {
  25121. return false;
  25122. }
  25123. };
  25124. /**
  25125. * Use this method to simulate a pointer down on a mesh
  25126. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25127. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25128. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25129. * @returns the current scene
  25130. */
  25131. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25132. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25133. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25134. return this;
  25135. }
  25136. return this._processPointerDown(pickResult, evt);
  25137. };
  25138. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25139. var _this = this;
  25140. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25141. this._pickedDownMesh = pickResult.pickedMesh;
  25142. var actionManager = pickResult.pickedMesh.actionManager;
  25143. if (actionManager) {
  25144. if (actionManager.hasPickTriggers) {
  25145. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25146. switch (evt.button) {
  25147. case 0:
  25148. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25149. break;
  25150. case 1:
  25151. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25152. break;
  25153. case 2:
  25154. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25155. break;
  25156. }
  25157. }
  25158. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25159. window.setTimeout(function () {
  25160. 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);
  25161. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25162. if (_this._totalPointersPressed !== 0 &&
  25163. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25164. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25165. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25166. _this._startingPointerTime = 0;
  25167. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25168. }
  25169. }
  25170. }, Scene.LongPressDelay);
  25171. }
  25172. }
  25173. }
  25174. if (pickResult) {
  25175. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25176. if (this.onPointerDown) {
  25177. this.onPointerDown(evt, pickResult, type);
  25178. }
  25179. if (this.onPointerObservable.hasObservers()) {
  25180. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25181. this._setRayOnPointerInfo(pi);
  25182. this.onPointerObservable.notifyObservers(pi, type);
  25183. }
  25184. }
  25185. return this;
  25186. };
  25187. /**
  25188. * Use this method to simulate a pointer up on a mesh
  25189. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25190. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25191. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25192. * @returns the current scene
  25193. */
  25194. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25195. var evt = new PointerEvent("pointerup", pointerEventInit);
  25196. var clickInfo = new ClickInfo();
  25197. clickInfo.singleClick = true;
  25198. clickInfo.ignore = true;
  25199. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25200. return this;
  25201. }
  25202. return this._processPointerUp(pickResult, evt, clickInfo);
  25203. };
  25204. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25205. if (pickResult && pickResult && pickResult.pickedMesh) {
  25206. this._pickedUpMesh = pickResult.pickedMesh;
  25207. if (this._pickedDownMesh === this._pickedUpMesh) {
  25208. if (this.onPointerPick) {
  25209. this.onPointerPick(evt, pickResult);
  25210. }
  25211. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25212. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25213. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25214. this._setRayOnPointerInfo(pi);
  25215. this.onPointerObservable.notifyObservers(pi, type_1);
  25216. }
  25217. }
  25218. if (pickResult.pickedMesh.actionManager) {
  25219. if (clickInfo.ignore) {
  25220. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25221. }
  25222. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25223. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25224. }
  25225. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25226. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25227. }
  25228. }
  25229. }
  25230. if (this._pickedDownMesh &&
  25231. this._pickedDownMesh.actionManager &&
  25232. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25233. this._pickedDownMesh !== this._pickedUpMesh) {
  25234. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25235. }
  25236. var type = BABYLON.PointerEventTypes.POINTERUP;
  25237. if (this.onPointerObservable.hasObservers()) {
  25238. if (!clickInfo.ignore) {
  25239. if (!clickInfo.hasSwiped) {
  25240. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25241. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25242. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25243. this._setRayOnPointerInfo(pi);
  25244. this.onPointerObservable.notifyObservers(pi, type_2);
  25245. }
  25246. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25247. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25248. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25249. this._setRayOnPointerInfo(pi);
  25250. this.onPointerObservable.notifyObservers(pi, type_3);
  25251. }
  25252. }
  25253. }
  25254. else {
  25255. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25256. this._setRayOnPointerInfo(pi);
  25257. this.onPointerObservable.notifyObservers(pi, type);
  25258. }
  25259. }
  25260. if (this.onPointerUp) {
  25261. this.onPointerUp(evt, pickResult, type);
  25262. }
  25263. return this;
  25264. };
  25265. /**
  25266. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25267. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25268. * @returns true if the pointer was captured
  25269. */
  25270. Scene.prototype.isPointerCaptured = function (pointerId) {
  25271. if (pointerId === void 0) { pointerId = 0; }
  25272. return this._pointerCaptures[pointerId];
  25273. };
  25274. /**
  25275. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25276. * @param attachUp defines if you want to attach events to pointerup
  25277. * @param attachDown defines if you want to attach events to pointerdown
  25278. * @param attachMove defines if you want to attach events to pointermove
  25279. */
  25280. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25281. var _this = this;
  25282. if (attachUp === void 0) { attachUp = true; }
  25283. if (attachDown === void 0) { attachDown = true; }
  25284. if (attachMove === void 0) { attachMove = true; }
  25285. this._initActionManager = function (act, clickInfo) {
  25286. if (!_this._meshPickProceed) {
  25287. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25288. _this._currentPickResult = pickResult;
  25289. if (pickResult) {
  25290. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25291. }
  25292. _this._meshPickProceed = true;
  25293. }
  25294. return act;
  25295. };
  25296. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25297. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25298. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25299. btn !== _this._previousButtonPressed) {
  25300. _this._doubleClickOccured = false;
  25301. clickInfo.singleClick = true;
  25302. clickInfo.ignore = false;
  25303. cb(clickInfo, _this._currentPickResult);
  25304. }
  25305. };
  25306. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25307. var clickInfo = new ClickInfo();
  25308. _this._currentPickResult = null;
  25309. var act = null;
  25310. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25311. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25312. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25313. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25314. act = _this._initActionManager(act, clickInfo);
  25315. if (act)
  25316. checkPicking = act.hasPickTriggers;
  25317. }
  25318. if (checkPicking) {
  25319. var btn = evt.button;
  25320. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25321. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25322. if (!clickInfo.hasSwiped) {
  25323. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25324. if (!checkSingleClickImmediately) {
  25325. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25326. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25327. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25328. act = _this._initActionManager(act, clickInfo);
  25329. if (act)
  25330. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25331. }
  25332. }
  25333. if (checkSingleClickImmediately) {
  25334. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25335. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25336. btn !== _this._previousButtonPressed) {
  25337. clickInfo.singleClick = true;
  25338. cb(clickInfo, _this._currentPickResult);
  25339. }
  25340. }
  25341. // at least one double click is required to be check and exclusive double click is enabled
  25342. else {
  25343. // wait that no double click has been raised during the double click delay
  25344. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25345. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25346. }
  25347. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25348. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25349. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25350. act = _this._initActionManager(act, clickInfo);
  25351. if (act)
  25352. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25353. }
  25354. if (checkDoubleClick) {
  25355. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25356. if (btn === _this._previousButtonPressed &&
  25357. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25358. !_this._doubleClickOccured) {
  25359. // pointer has not moved for 2 clicks, it's a double click
  25360. if (!clickInfo.hasSwiped &&
  25361. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25362. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25363. _this._previousStartingPointerTime = 0;
  25364. _this._doubleClickOccured = true;
  25365. clickInfo.doubleClick = true;
  25366. clickInfo.ignore = false;
  25367. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25368. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25369. }
  25370. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25371. cb(clickInfo, _this._currentPickResult);
  25372. }
  25373. // if the two successive clicks are too far, it's just two simple clicks
  25374. else {
  25375. _this._doubleClickOccured = false;
  25376. _this._previousStartingPointerTime = _this._startingPointerTime;
  25377. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25378. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25379. _this._previousButtonPressed = btn;
  25380. if (Scene.ExclusiveDoubleClickMode) {
  25381. if (_this._previousDelayedSimpleClickTimeout) {
  25382. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25383. }
  25384. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25385. cb(clickInfo, _this._previousPickResult);
  25386. }
  25387. else {
  25388. cb(clickInfo, _this._currentPickResult);
  25389. }
  25390. }
  25391. }
  25392. // just the first click of the double has been raised
  25393. else {
  25394. _this._doubleClickOccured = false;
  25395. _this._previousStartingPointerTime = _this._startingPointerTime;
  25396. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25397. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25398. _this._previousButtonPressed = btn;
  25399. }
  25400. }
  25401. }
  25402. }
  25403. clickInfo.ignore = true;
  25404. cb(clickInfo, _this._currentPickResult);
  25405. };
  25406. this._spritePredicate = function (sprite) {
  25407. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25408. };
  25409. this._onPointerMove = function (evt) {
  25410. _this._updatePointerPosition(evt);
  25411. // PreObservable support
  25412. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25413. return;
  25414. }
  25415. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25416. return;
  25417. }
  25418. if (!_this.pointerMovePredicate) {
  25419. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25420. }
  25421. // Meshes
  25422. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25423. _this._processPointerMove(pickResult, evt);
  25424. };
  25425. this._onPointerDown = function (evt) {
  25426. _this._totalPointersPressed++;
  25427. _this._pickedDownMesh = null;
  25428. _this._meshPickProceed = false;
  25429. _this._updatePointerPosition(evt);
  25430. if (_this.preventDefaultOnPointerDown && canvas) {
  25431. evt.preventDefault();
  25432. canvas.focus();
  25433. }
  25434. // PreObservable support
  25435. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25436. return;
  25437. }
  25438. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25439. return;
  25440. }
  25441. _this._pointerCaptures[evt.pointerId] = true;
  25442. _this._startingPointerPosition.x = _this._pointerX;
  25443. _this._startingPointerPosition.y = _this._pointerY;
  25444. _this._startingPointerTime = Date.now();
  25445. if (!_this.pointerDownPredicate) {
  25446. _this.pointerDownPredicate = function (mesh) {
  25447. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25448. };
  25449. }
  25450. // Meshes
  25451. _this._pickedDownMesh = null;
  25452. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25453. _this._processPointerDown(pickResult, evt);
  25454. // Sprites
  25455. _this._pickedDownSprite = null;
  25456. if (_this.spriteManagers.length > 0) {
  25457. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25458. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25459. if (pickResult.pickedSprite.actionManager) {
  25460. _this._pickedDownSprite = pickResult.pickedSprite;
  25461. switch (evt.button) {
  25462. case 0:
  25463. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25464. break;
  25465. case 1:
  25466. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25467. break;
  25468. case 2:
  25469. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25470. break;
  25471. }
  25472. if (pickResult.pickedSprite.actionManager) {
  25473. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25474. }
  25475. }
  25476. }
  25477. }
  25478. };
  25479. this._onPointerUp = function (evt) {
  25480. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25481. return; // So we need to test it the pointer down was pressed before.
  25482. }
  25483. _this._totalPointersPressed--;
  25484. _this._pickedUpMesh = null;
  25485. _this._meshPickProceed = false;
  25486. _this._updatePointerPosition(evt);
  25487. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25488. // PreObservable support
  25489. if (_this.onPrePointerObservable.hasObservers()) {
  25490. if (!clickInfo.ignore) {
  25491. if (!clickInfo.hasSwiped) {
  25492. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25493. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25494. return;
  25495. }
  25496. }
  25497. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25498. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25499. return;
  25500. }
  25501. }
  25502. }
  25503. }
  25504. else {
  25505. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25506. return;
  25507. }
  25508. }
  25509. }
  25510. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25511. return;
  25512. }
  25513. _this._pointerCaptures[evt.pointerId] = false;
  25514. if (!_this.pointerUpPredicate) {
  25515. _this.pointerUpPredicate = function (mesh) {
  25516. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25517. };
  25518. }
  25519. // Meshes
  25520. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25521. _this._initActionManager(null, clickInfo);
  25522. }
  25523. if (!pickResult) {
  25524. pickResult = _this._currentPickResult;
  25525. }
  25526. _this._processPointerUp(pickResult, evt, clickInfo);
  25527. // Sprites
  25528. if (!clickInfo.ignore) {
  25529. if (_this.spriteManagers.length > 0) {
  25530. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25531. if (spritePickResult) {
  25532. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25533. if (spritePickResult.pickedSprite.actionManager) {
  25534. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25535. if (spritePickResult.pickedSprite.actionManager) {
  25536. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25537. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25538. }
  25539. }
  25540. }
  25541. }
  25542. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25543. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25544. }
  25545. }
  25546. }
  25547. }
  25548. _this._previousPickResult = _this._currentPickResult;
  25549. });
  25550. };
  25551. this._onKeyDown = function (evt) {
  25552. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25553. if (_this.onPreKeyboardObservable.hasObservers()) {
  25554. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25555. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25556. if (pi.skipOnPointerObservable) {
  25557. return;
  25558. }
  25559. }
  25560. if (_this.onKeyboardObservable.hasObservers()) {
  25561. var pi = new BABYLON.KeyboardInfo(type, evt);
  25562. _this.onKeyboardObservable.notifyObservers(pi, type);
  25563. }
  25564. if (_this.actionManager) {
  25565. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25566. }
  25567. };
  25568. this._onKeyUp = function (evt) {
  25569. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25570. if (_this.onPreKeyboardObservable.hasObservers()) {
  25571. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25572. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25573. if (pi.skipOnPointerObservable) {
  25574. return;
  25575. }
  25576. }
  25577. if (_this.onKeyboardObservable.hasObservers()) {
  25578. var pi = new BABYLON.KeyboardInfo(type, evt);
  25579. _this.onKeyboardObservable.notifyObservers(pi, type);
  25580. }
  25581. if (_this.actionManager) {
  25582. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25583. }
  25584. };
  25585. var engine = this.getEngine();
  25586. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25587. if (!canvas) {
  25588. return;
  25589. }
  25590. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25591. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25592. });
  25593. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25594. if (!canvas) {
  25595. return;
  25596. }
  25597. canvas.removeEventListener("keydown", _this._onKeyDown);
  25598. canvas.removeEventListener("keyup", _this._onKeyUp);
  25599. });
  25600. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25601. var canvas = this._engine.getRenderingCanvas();
  25602. if (!canvas) {
  25603. return;
  25604. }
  25605. if (attachMove) {
  25606. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25607. // Wheel
  25608. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25609. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25610. }
  25611. if (attachDown) {
  25612. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25613. }
  25614. if (attachUp) {
  25615. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25616. }
  25617. canvas.tabIndex = 1;
  25618. };
  25619. /** Detaches all event handlers*/
  25620. Scene.prototype.detachControl = function () {
  25621. var engine = this.getEngine();
  25622. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25623. var canvas = engine.getRenderingCanvas();
  25624. if (!canvas) {
  25625. return;
  25626. }
  25627. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25628. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25629. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25630. if (this._onCanvasBlurObserver) {
  25631. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25632. }
  25633. if (this._onCanvasFocusObserver) {
  25634. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25635. }
  25636. // Wheel
  25637. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25638. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25639. // Keyboard
  25640. canvas.removeEventListener("keydown", this._onKeyDown);
  25641. canvas.removeEventListener("keyup", this._onKeyUp);
  25642. // Observables
  25643. this.onKeyboardObservable.clear();
  25644. this.onPreKeyboardObservable.clear();
  25645. this.onPointerObservable.clear();
  25646. this.onPrePointerObservable.clear();
  25647. };
  25648. /**
  25649. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25650. * Delay loaded resources are not taking in account
  25651. * @return true if all required resources are ready
  25652. */
  25653. Scene.prototype.isReady = function () {
  25654. if (this._isDisposed) {
  25655. return false;
  25656. }
  25657. if (this._pendingData.length > 0) {
  25658. return false;
  25659. }
  25660. var index;
  25661. var engine = this.getEngine();
  25662. // Geometries
  25663. for (index = 0; index < this._geometries.length; index++) {
  25664. var geometry = this._geometries[index];
  25665. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25666. return false;
  25667. }
  25668. }
  25669. // Meshes
  25670. for (index = 0; index < this.meshes.length; index++) {
  25671. var mesh = this.meshes[index];
  25672. if (!mesh.isEnabled()) {
  25673. continue;
  25674. }
  25675. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25676. continue;
  25677. }
  25678. if (!mesh.isReady(true)) {
  25679. return false;
  25680. }
  25681. // Effect layers
  25682. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25683. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25684. var layer = _a[_i];
  25685. if (!layer.hasMesh(mesh)) {
  25686. continue;
  25687. }
  25688. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25689. var subMesh = _c[_b];
  25690. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25691. return false;
  25692. }
  25693. }
  25694. }
  25695. }
  25696. // Post-processes
  25697. if (this.activeCameras && this.activeCameras.length > 0) {
  25698. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25699. var camera = _e[_d];
  25700. if (!camera.isReady(true)) {
  25701. return false;
  25702. }
  25703. }
  25704. }
  25705. else if (this.activeCamera) {
  25706. if (!this.activeCamera.isReady(true)) {
  25707. return false;
  25708. }
  25709. }
  25710. // Particles
  25711. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25712. var particleSystem = _g[_f];
  25713. if (!particleSystem.isReady()) {
  25714. return false;
  25715. }
  25716. }
  25717. return true;
  25718. };
  25719. /** Resets all cached information relative to material (including effect and visibility) */
  25720. Scene.prototype.resetCachedMaterial = function () {
  25721. this._cachedMaterial = null;
  25722. this._cachedEffect = null;
  25723. this._cachedVisibility = null;
  25724. };
  25725. /**
  25726. * Registers a function to be called before every frame render
  25727. * @param func defines the function to register
  25728. */
  25729. Scene.prototype.registerBeforeRender = function (func) {
  25730. this.onBeforeRenderObservable.add(func);
  25731. };
  25732. /**
  25733. * Unregisters a function called before every frame render
  25734. * @param func defines the function to unregister
  25735. */
  25736. Scene.prototype.unregisterBeforeRender = function (func) {
  25737. this.onBeforeRenderObservable.removeCallback(func);
  25738. };
  25739. /**
  25740. * Registers a function to be called after every frame render
  25741. * @param func defines the function to register
  25742. */
  25743. Scene.prototype.registerAfterRender = function (func) {
  25744. this.onAfterRenderObservable.add(func);
  25745. };
  25746. /**
  25747. * Unregisters a function called after every frame render
  25748. * @param func defines the function to unregister
  25749. */
  25750. Scene.prototype.unregisterAfterRender = function (func) {
  25751. this.onAfterRenderObservable.removeCallback(func);
  25752. };
  25753. Scene.prototype._executeOnceBeforeRender = function (func) {
  25754. var _this = this;
  25755. var execFunc = function () {
  25756. func();
  25757. setTimeout(function () {
  25758. _this.unregisterBeforeRender(execFunc);
  25759. });
  25760. };
  25761. this.registerBeforeRender(execFunc);
  25762. };
  25763. /**
  25764. * The provided function will run before render once and will be disposed afterwards.
  25765. * A timeout delay can be provided so that the function will be executed in N ms.
  25766. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25767. * @param func The function to be executed.
  25768. * @param timeout optional delay in ms
  25769. */
  25770. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25771. var _this = this;
  25772. if (timeout !== undefined) {
  25773. setTimeout(function () {
  25774. _this._executeOnceBeforeRender(func);
  25775. }, timeout);
  25776. }
  25777. else {
  25778. this._executeOnceBeforeRender(func);
  25779. }
  25780. };
  25781. /** @hidden */
  25782. Scene.prototype._addPendingData = function (data) {
  25783. this._pendingData.push(data);
  25784. };
  25785. /** @hidden */
  25786. Scene.prototype._removePendingData = function (data) {
  25787. var wasLoading = this.isLoading;
  25788. var index = this._pendingData.indexOf(data);
  25789. if (index !== -1) {
  25790. this._pendingData.splice(index, 1);
  25791. }
  25792. if (wasLoading && !this.isLoading) {
  25793. this.onDataLoadedObservable.notifyObservers(this);
  25794. }
  25795. };
  25796. /**
  25797. * Returns the number of items waiting to be loaded
  25798. * @returns the number of items waiting to be loaded
  25799. */
  25800. Scene.prototype.getWaitingItemsCount = function () {
  25801. return this._pendingData.length;
  25802. };
  25803. Object.defineProperty(Scene.prototype, "isLoading", {
  25804. /**
  25805. * Returns a boolean indicating if the scene is still loading data
  25806. */
  25807. get: function () {
  25808. return this._pendingData.length > 0;
  25809. },
  25810. enumerable: true,
  25811. configurable: true
  25812. });
  25813. /**
  25814. * Registers a function to be executed when the scene is ready
  25815. * @param {Function} func - the function to be executed
  25816. */
  25817. Scene.prototype.executeWhenReady = function (func) {
  25818. var _this = this;
  25819. this.onReadyObservable.add(func);
  25820. if (this._executeWhenReadyTimeoutId !== -1) {
  25821. return;
  25822. }
  25823. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25824. _this._checkIsReady();
  25825. }, 150);
  25826. };
  25827. /**
  25828. * Returns a promise that resolves when the scene is ready
  25829. * @returns A promise that resolves when the scene is ready
  25830. */
  25831. Scene.prototype.whenReadyAsync = function () {
  25832. var _this = this;
  25833. return new Promise(function (resolve) {
  25834. _this.executeWhenReady(function () {
  25835. resolve();
  25836. });
  25837. });
  25838. };
  25839. /** @hidden */
  25840. Scene.prototype._checkIsReady = function () {
  25841. var _this = this;
  25842. if (this.isReady()) {
  25843. this.onReadyObservable.notifyObservers(this);
  25844. this.onReadyObservable.clear();
  25845. this._executeWhenReadyTimeoutId = -1;
  25846. return;
  25847. }
  25848. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25849. _this._checkIsReady();
  25850. }, 150);
  25851. };
  25852. // Animations
  25853. /**
  25854. * Will start the animation sequence of a given target
  25855. * @param target defines the target
  25856. * @param from defines from which frame should animation start
  25857. * @param to defines until which frame should animation run.
  25858. * @param weight defines the weight to apply to the animation (1.0 by default)
  25859. * @param loop defines if the animation loops
  25860. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25861. * @param onAnimationEnd defines the function to be executed when the animation ends
  25862. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25863. * @returns the animatable object created for this animation
  25864. */
  25865. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25866. if (weight === void 0) { weight = 1.0; }
  25867. if (speedRatio === void 0) { speedRatio = 1.0; }
  25868. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25869. returnedAnimatable.weight = weight;
  25870. return returnedAnimatable;
  25871. };
  25872. /**
  25873. * Will start the animation sequence of a given target
  25874. * @param target defines the target
  25875. * @param from defines from which frame should animation start
  25876. * @param to defines until which frame should animation run.
  25877. * @param loop defines if the animation loops
  25878. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25879. * @param onAnimationEnd defines the function to be executed when the animation ends
  25880. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25881. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25882. * @returns the animatable object created for this animation
  25883. */
  25884. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25885. if (speedRatio === void 0) { speedRatio = 1.0; }
  25886. if (stopCurrent === void 0) { stopCurrent = true; }
  25887. if (from > to && speedRatio > 0) {
  25888. speedRatio *= -1;
  25889. }
  25890. if (stopCurrent) {
  25891. this.stopAnimation(target);
  25892. }
  25893. if (!animatable) {
  25894. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25895. }
  25896. // Local animations
  25897. if (target.animations) {
  25898. animatable.appendAnimations(target, target.animations);
  25899. }
  25900. // Children animations
  25901. if (target.getAnimatables) {
  25902. var animatables = target.getAnimatables();
  25903. for (var index = 0; index < animatables.length; index++) {
  25904. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25905. }
  25906. }
  25907. animatable.reset();
  25908. return animatable;
  25909. };
  25910. /**
  25911. * Begin a new animation on a given node
  25912. * @param target defines the target where the animation will take place
  25913. * @param animations defines the list of animations to start
  25914. * @param from defines the initial value
  25915. * @param to defines the final value
  25916. * @param loop defines if you want animation to loop (off by default)
  25917. * @param speedRatio defines the speed ratio to apply to all animations
  25918. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25919. * @returns the list of created animatables
  25920. */
  25921. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25922. if (speedRatio === undefined) {
  25923. speedRatio = 1.0;
  25924. }
  25925. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25926. return animatable;
  25927. };
  25928. /**
  25929. * Begin a new animation on a given node and its hierarchy
  25930. * @param target defines the root node where the animation will take place
  25931. * @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.
  25932. * @param animations defines the list of animations to start
  25933. * @param from defines the initial value
  25934. * @param to defines the final value
  25935. * @param loop defines if you want animation to loop (off by default)
  25936. * @param speedRatio defines the speed ratio to apply to all animations
  25937. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25938. * @returns the list of animatables created for all nodes
  25939. */
  25940. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25941. var children = target.getDescendants(directDescendantsOnly);
  25942. var result = [];
  25943. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25944. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25945. var child = children_1[_i];
  25946. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25947. }
  25948. return result;
  25949. };
  25950. /**
  25951. * Gets the animatable associated with a specific target
  25952. * @param target defines the target of the animatable
  25953. * @returns the required animatable if found
  25954. */
  25955. Scene.prototype.getAnimatableByTarget = function (target) {
  25956. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25957. if (this._activeAnimatables[index].target === target) {
  25958. return this._activeAnimatables[index];
  25959. }
  25960. }
  25961. return null;
  25962. };
  25963. /**
  25964. * Gets all animatables associated with a given target
  25965. * @param target defines the target to look animatables for
  25966. * @returns an array of Animatables
  25967. */
  25968. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25969. var result = [];
  25970. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25971. if (this._activeAnimatables[index].target === target) {
  25972. result.push(this._activeAnimatables[index]);
  25973. }
  25974. }
  25975. return result;
  25976. };
  25977. Object.defineProperty(Scene.prototype, "animatables", {
  25978. /**
  25979. * Gets all animatable attached to the scene
  25980. */
  25981. get: function () {
  25982. return this._activeAnimatables;
  25983. },
  25984. enumerable: true,
  25985. configurable: true
  25986. });
  25987. /**
  25988. * Will stop the animation of the given target
  25989. * @param target - the target
  25990. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25991. */
  25992. Scene.prototype.stopAnimation = function (target, animationName) {
  25993. var animatables = this.getAllAnimatablesByTarget(target);
  25994. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25995. var animatable = animatables_1[_i];
  25996. animatable.stop(animationName);
  25997. }
  25998. };
  25999. /**
  26000. * Stops and removes all animations that have been applied to the scene
  26001. */
  26002. Scene.prototype.stopAllAnimations = function () {
  26003. if (this._activeAnimatables) {
  26004. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26005. this._activeAnimatables[i].stop();
  26006. }
  26007. this._activeAnimatables = [];
  26008. }
  26009. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26010. var group = _a[_i];
  26011. group.stop();
  26012. }
  26013. };
  26014. Scene.prototype._animate = function () {
  26015. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26016. return;
  26017. }
  26018. // Getting time
  26019. var now = BABYLON.Tools.Now;
  26020. if (!this._animationTimeLast) {
  26021. if (this._pendingData.length > 0) {
  26022. return;
  26023. }
  26024. this._animationTimeLast = now;
  26025. }
  26026. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26027. this._animationTime += deltaTime;
  26028. this._animationTimeLast = now;
  26029. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26030. this._activeAnimatables[index]._animate(this._animationTime);
  26031. }
  26032. // Late animation bindings
  26033. this._processLateAnimationBindings();
  26034. };
  26035. /** @hidden */
  26036. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26037. var target = runtimeAnimation.target;
  26038. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26039. if (!target._lateAnimationHolders) {
  26040. target._lateAnimationHolders = {};
  26041. }
  26042. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26043. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26044. totalWeight: 0,
  26045. animations: [],
  26046. originalValue: originalValue
  26047. };
  26048. }
  26049. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26050. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26051. };
  26052. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26053. var normalizer = 1.0;
  26054. var finalPosition = BABYLON.Tmp.Vector3[0];
  26055. var finalScaling = BABYLON.Tmp.Vector3[1];
  26056. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26057. var startIndex = 0;
  26058. var originalAnimation = holder.animations[0];
  26059. var originalValue = holder.originalValue;
  26060. var scale = 1;
  26061. if (holder.totalWeight < 1.0) {
  26062. // We need to mix the original value in
  26063. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26064. scale = 1.0 - holder.totalWeight;
  26065. }
  26066. else {
  26067. startIndex = 1;
  26068. // We need to normalize the weights
  26069. normalizer = holder.totalWeight;
  26070. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26071. scale = originalAnimation.weight / normalizer;
  26072. if (scale == 1) {
  26073. return originalAnimation.currentValue;
  26074. }
  26075. }
  26076. finalScaling.scaleInPlace(scale);
  26077. finalPosition.scaleInPlace(scale);
  26078. finalQuaternion.scaleInPlace(scale);
  26079. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26080. var runtimeAnimation = holder.animations[animIndex];
  26081. var scale = runtimeAnimation.weight / normalizer;
  26082. var currentPosition = BABYLON.Tmp.Vector3[2];
  26083. var currentScaling = BABYLON.Tmp.Vector3[3];
  26084. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26085. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26086. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26087. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26088. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26089. }
  26090. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26091. return originalAnimation._workValue;
  26092. };
  26093. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26094. var originalAnimation = holder.animations[0];
  26095. var originalValue = holder.originalValue;
  26096. if (holder.animations.length === 1) {
  26097. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26098. }
  26099. var normalizer = 1.0;
  26100. var quaternions;
  26101. var weights;
  26102. if (holder.totalWeight < 1.0) {
  26103. var scale = 1.0 - holder.totalWeight;
  26104. quaternions = [];
  26105. weights = [];
  26106. quaternions.push(originalValue);
  26107. weights.push(scale);
  26108. }
  26109. else {
  26110. if (holder.animations.length === 2) { // Slerp as soon as we can
  26111. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26112. }
  26113. quaternions = [];
  26114. weights = [];
  26115. normalizer = holder.totalWeight;
  26116. }
  26117. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26118. var runtimeAnimation = holder.animations[animIndex];
  26119. quaternions.push(runtimeAnimation.currentValue);
  26120. weights.push(runtimeAnimation.weight / normalizer);
  26121. }
  26122. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26123. var cumulativeAmount = 0;
  26124. var cumulativeQuaternion = null;
  26125. for (var index = 0; index < quaternions.length;) {
  26126. if (!cumulativeQuaternion) {
  26127. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26128. cumulativeAmount = weights[index] + weights[index + 1];
  26129. index += 2;
  26130. continue;
  26131. }
  26132. cumulativeAmount += weights[index];
  26133. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26134. index++;
  26135. }
  26136. return cumulativeQuaternion;
  26137. };
  26138. Scene.prototype._processLateAnimationBindings = function () {
  26139. if (!this._registeredForLateAnimationBindings.length) {
  26140. return;
  26141. }
  26142. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26143. var target = this._registeredForLateAnimationBindings.data[index];
  26144. for (var path in target._lateAnimationHolders) {
  26145. var holder = target._lateAnimationHolders[path];
  26146. var originalAnimation = holder.animations[0];
  26147. var originalValue = holder.originalValue;
  26148. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26149. var finalValue = void 0;
  26150. if (matrixDecomposeMode) {
  26151. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26152. }
  26153. else {
  26154. var quaternionMode = originalValue.w !== undefined;
  26155. if (quaternionMode) {
  26156. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26157. }
  26158. else {
  26159. var startIndex = 0;
  26160. var normalizer = 1.0;
  26161. if (holder.totalWeight < 1.0) {
  26162. // We need to mix the original value in
  26163. if (originalValue.scale) {
  26164. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26165. }
  26166. else {
  26167. finalValue = originalValue * (1.0 - holder.totalWeight);
  26168. }
  26169. }
  26170. else {
  26171. // We need to normalize the weights
  26172. normalizer = holder.totalWeight;
  26173. var scale_1 = originalAnimation.weight / normalizer;
  26174. if (scale_1 !== 1) {
  26175. if (originalAnimation.currentValue.scale) {
  26176. finalValue = originalAnimation.currentValue.scale(scale_1);
  26177. }
  26178. else {
  26179. finalValue = originalAnimation.currentValue * scale_1;
  26180. }
  26181. }
  26182. else {
  26183. finalValue = originalAnimation.currentValue;
  26184. }
  26185. startIndex = 1;
  26186. }
  26187. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26188. var runtimeAnimation = holder.animations[animIndex];
  26189. var scale = runtimeAnimation.weight / normalizer;
  26190. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26191. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26192. }
  26193. else {
  26194. finalValue += runtimeAnimation.currentValue * scale;
  26195. }
  26196. }
  26197. }
  26198. }
  26199. target[path] = finalValue;
  26200. }
  26201. target._lateAnimationHolders = {};
  26202. }
  26203. this._registeredForLateAnimationBindings.reset();
  26204. };
  26205. // Matrix
  26206. /** @hidden */
  26207. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26208. this._useAlternateCameraConfiguration = active;
  26209. };
  26210. /**
  26211. * Gets the current view matrix
  26212. * @returns a Matrix
  26213. */
  26214. Scene.prototype.getViewMatrix = function () {
  26215. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26216. };
  26217. /**
  26218. * Gets the current projection matrix
  26219. * @returns a Matrix
  26220. */
  26221. Scene.prototype.getProjectionMatrix = function () {
  26222. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26223. };
  26224. /**
  26225. * Gets the current transform matrix
  26226. * @returns a Matrix made of View * Projection
  26227. */
  26228. Scene.prototype.getTransformMatrix = function () {
  26229. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26230. };
  26231. /**
  26232. * Sets the current transform matrix
  26233. * @param view defines the View matrix to use
  26234. * @param projection defines the Projection matrix to use
  26235. */
  26236. Scene.prototype.setTransformMatrix = function (view, projection) {
  26237. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26238. return;
  26239. }
  26240. this._viewUpdateFlag = view.updateFlag;
  26241. this._projectionUpdateFlag = projection.updateFlag;
  26242. this._viewMatrix = view;
  26243. this._projectionMatrix = projection;
  26244. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26245. // Update frustum
  26246. if (!this._frustumPlanes) {
  26247. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26248. }
  26249. else {
  26250. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26251. }
  26252. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26253. var otherCamera = this.activeCamera._alternateCamera;
  26254. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26255. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26256. }
  26257. if (this._sceneUbo.useUbo) {
  26258. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26259. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26260. this._sceneUbo.update();
  26261. }
  26262. };
  26263. /** @hidden */
  26264. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26265. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26266. return;
  26267. }
  26268. this._alternateViewUpdateFlag = view.updateFlag;
  26269. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26270. this._alternateViewMatrix = view;
  26271. this._alternateProjectionMatrix = projection;
  26272. if (!this._alternateTransformMatrix) {
  26273. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26274. }
  26275. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26276. if (!this._alternateSceneUbo) {
  26277. this._createAlternateUbo();
  26278. }
  26279. if (this._alternateSceneUbo.useUbo) {
  26280. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26281. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26282. this._alternateSceneUbo.update();
  26283. }
  26284. };
  26285. /**
  26286. * Gets the uniform buffer used to store scene data
  26287. * @returns a UniformBuffer
  26288. */
  26289. Scene.prototype.getSceneUniformBuffer = function () {
  26290. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26291. };
  26292. /**
  26293. * Gets an unique (relatively to the current scene) Id
  26294. * @returns an unique number for the scene
  26295. */
  26296. Scene.prototype.getUniqueId = function () {
  26297. var result = Scene._uniqueIdCounter;
  26298. Scene._uniqueIdCounter++;
  26299. return result;
  26300. };
  26301. /**
  26302. * Add a mesh to the list of scene's meshes
  26303. * @param newMesh defines the mesh to add
  26304. * @param recursive if all child meshes should also be added to the scene
  26305. */
  26306. Scene.prototype.addMesh = function (newMesh, recursive) {
  26307. var _this = this;
  26308. if (recursive === void 0) { recursive = false; }
  26309. this.meshes.push(newMesh);
  26310. //notify the collision coordinator
  26311. if (this.collisionCoordinator) {
  26312. this.collisionCoordinator.onMeshAdded(newMesh);
  26313. }
  26314. newMesh._resyncLightSources();
  26315. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26316. if (recursive) {
  26317. newMesh.getChildMeshes().forEach(function (m) {
  26318. _this.addMesh(m);
  26319. });
  26320. }
  26321. };
  26322. /**
  26323. * Remove a mesh for the list of scene's meshes
  26324. * @param toRemove defines the mesh to remove
  26325. * @param recursive if all child meshes should also be removed from the scene
  26326. * @returns the index where the mesh was in the mesh list
  26327. */
  26328. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26329. var _this = this;
  26330. if (recursive === void 0) { recursive = false; }
  26331. var index = this.meshes.indexOf(toRemove);
  26332. if (index !== -1) {
  26333. // Remove from the scene if mesh found
  26334. this.meshes.splice(index, 1);
  26335. }
  26336. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26337. if (recursive) {
  26338. toRemove.getChildMeshes().forEach(function (m) {
  26339. _this.removeMesh(m);
  26340. });
  26341. }
  26342. return index;
  26343. };
  26344. /**
  26345. * Add a transform node to the list of scene's transform nodes
  26346. * @param newTransformNode defines the transform node to add
  26347. */
  26348. Scene.prototype.addTransformNode = function (newTransformNode) {
  26349. this.transformNodes.push(newTransformNode);
  26350. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26351. };
  26352. /**
  26353. * Remove a transform node for the list of scene's transform nodes
  26354. * @param toRemove defines the transform node to remove
  26355. * @returns the index where the transform node was in the transform node list
  26356. */
  26357. Scene.prototype.removeTransformNode = function (toRemove) {
  26358. var index = this.transformNodes.indexOf(toRemove);
  26359. if (index !== -1) {
  26360. // Remove from the scene if found
  26361. this.transformNodes.splice(index, 1);
  26362. }
  26363. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26364. return index;
  26365. };
  26366. /**
  26367. * Remove a skeleton for the list of scene's skeletons
  26368. * @param toRemove defines the skeleton to remove
  26369. * @returns the index where the skeleton was in the skeleton list
  26370. */
  26371. Scene.prototype.removeSkeleton = function (toRemove) {
  26372. var index = this.skeletons.indexOf(toRemove);
  26373. if (index !== -1) {
  26374. // Remove from the scene if found
  26375. this.skeletons.splice(index, 1);
  26376. }
  26377. return index;
  26378. };
  26379. /**
  26380. * Remove a morph target for the list of scene's morph targets
  26381. * @param toRemove defines the morph target to remove
  26382. * @returns the index where the morph target was in the morph target list
  26383. */
  26384. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26385. var index = this.morphTargetManagers.indexOf(toRemove);
  26386. if (index !== -1) {
  26387. // Remove from the scene if found
  26388. this.morphTargetManagers.splice(index, 1);
  26389. }
  26390. return index;
  26391. };
  26392. /**
  26393. * Remove a light for the list of scene's lights
  26394. * @param toRemove defines the light to remove
  26395. * @returns the index where the light was in the light list
  26396. */
  26397. Scene.prototype.removeLight = function (toRemove) {
  26398. var index = this.lights.indexOf(toRemove);
  26399. if (index !== -1) {
  26400. // Remove from meshes
  26401. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26402. var mesh = _a[_i];
  26403. mesh._removeLightSource(toRemove);
  26404. }
  26405. // Remove from the scene if mesh found
  26406. this.lights.splice(index, 1);
  26407. this.sortLightsByPriority();
  26408. }
  26409. this.onLightRemovedObservable.notifyObservers(toRemove);
  26410. return index;
  26411. };
  26412. /**
  26413. * Remove a camera for the list of scene's cameras
  26414. * @param toRemove defines the camera to remove
  26415. * @returns the index where the camera was in the camera list
  26416. */
  26417. Scene.prototype.removeCamera = function (toRemove) {
  26418. var index = this.cameras.indexOf(toRemove);
  26419. if (index !== -1) {
  26420. // Remove from the scene if mesh found
  26421. this.cameras.splice(index, 1);
  26422. }
  26423. // Remove from activeCameras
  26424. var index2 = this.activeCameras.indexOf(toRemove);
  26425. if (index2 !== -1) {
  26426. // Remove from the scene if mesh found
  26427. this.activeCameras.splice(index2, 1);
  26428. }
  26429. // Reset the activeCamera
  26430. if (this.activeCamera === toRemove) {
  26431. if (this.cameras.length > 0) {
  26432. this.activeCamera = this.cameras[0];
  26433. }
  26434. else {
  26435. this.activeCamera = null;
  26436. }
  26437. }
  26438. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26439. return index;
  26440. };
  26441. /**
  26442. * Remove a particle system for the list of scene's particle systems
  26443. * @param toRemove defines the particle system to remove
  26444. * @returns the index where the particle system was in the particle system list
  26445. */
  26446. Scene.prototype.removeParticleSystem = function (toRemove) {
  26447. var index = this.particleSystems.indexOf(toRemove);
  26448. if (index !== -1) {
  26449. this.particleSystems.splice(index, 1);
  26450. }
  26451. return index;
  26452. };
  26453. /**
  26454. * Remove a animation for the list of scene's animations
  26455. * @param toRemove defines the animation to remove
  26456. * @returns the index where the animation was in the animation list
  26457. */
  26458. Scene.prototype.removeAnimation = function (toRemove) {
  26459. var index = this.animations.indexOf(toRemove);
  26460. if (index !== -1) {
  26461. this.animations.splice(index, 1);
  26462. }
  26463. return index;
  26464. };
  26465. /**
  26466. * Removes the given animation group from this scene.
  26467. * @param toRemove The animation group to remove
  26468. * @returns The index of the removed animation group
  26469. */
  26470. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26471. var index = this.animationGroups.indexOf(toRemove);
  26472. if (index !== -1) {
  26473. this.animationGroups.splice(index, 1);
  26474. }
  26475. return index;
  26476. };
  26477. /**
  26478. * Removes the given multi-material from this scene.
  26479. * @param toRemove The multi-material to remove
  26480. * @returns The index of the removed multi-material
  26481. */
  26482. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26483. var index = this.multiMaterials.indexOf(toRemove);
  26484. if (index !== -1) {
  26485. this.multiMaterials.splice(index, 1);
  26486. }
  26487. return index;
  26488. };
  26489. /**
  26490. * Removes the given material from this scene.
  26491. * @param toRemove The material to remove
  26492. * @returns The index of the removed material
  26493. */
  26494. Scene.prototype.removeMaterial = function (toRemove) {
  26495. var index = this.materials.indexOf(toRemove);
  26496. if (index !== -1) {
  26497. this.materials.splice(index, 1);
  26498. }
  26499. return index;
  26500. };
  26501. /**
  26502. * Removes the given lens flare system from this scene.
  26503. * @param toRemove The lens flare system to remove
  26504. * @returns The index of the removed lens flare system
  26505. */
  26506. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26507. var index = this.lensFlareSystems.indexOf(toRemove);
  26508. if (index !== -1) {
  26509. this.lensFlareSystems.splice(index, 1);
  26510. }
  26511. return index;
  26512. };
  26513. /**
  26514. * Removes the given action manager from this scene.
  26515. * @param toRemove The action manager to remove
  26516. * @returns The index of the removed action manager
  26517. */
  26518. Scene.prototype.removeActionManager = function (toRemove) {
  26519. var index = this._actionManagers.indexOf(toRemove);
  26520. if (index !== -1) {
  26521. this._actionManagers.splice(index, 1);
  26522. }
  26523. return index;
  26524. };
  26525. /**
  26526. * Removes the given effect layer from this scene.
  26527. * @param toRemove defines the effect layer to remove
  26528. * @returns the index of the removed effect layer
  26529. */
  26530. Scene.prototype.removeEffectLayer = function (toRemove) {
  26531. var index = this.effectLayers.indexOf(toRemove);
  26532. if (index !== -1) {
  26533. this.effectLayers.splice(index, 1);
  26534. }
  26535. return index;
  26536. };
  26537. /**
  26538. * Removes the given texture from this scene.
  26539. * @param toRemove The texture to remove
  26540. * @returns The index of the removed texture
  26541. */
  26542. Scene.prototype.removeTexture = function (toRemove) {
  26543. var index = this.textures.indexOf(toRemove);
  26544. if (index !== -1) {
  26545. this.textures.splice(index, 1);
  26546. }
  26547. return index;
  26548. };
  26549. /**
  26550. * Adds the given light to this scene
  26551. * @param newLight The light to add
  26552. */
  26553. Scene.prototype.addLight = function (newLight) {
  26554. this.lights.push(newLight);
  26555. this.sortLightsByPriority();
  26556. // Add light to all meshes (To support if the light is removed and then readded)
  26557. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26558. var mesh = _a[_i];
  26559. if (mesh._lightSources.indexOf(newLight) === -1) {
  26560. mesh._lightSources.push(newLight);
  26561. mesh._resyncLightSources();
  26562. }
  26563. }
  26564. this.onNewLightAddedObservable.notifyObservers(newLight);
  26565. };
  26566. /**
  26567. * Sorts the list list based on light priorities
  26568. */
  26569. Scene.prototype.sortLightsByPriority = function () {
  26570. if (this.requireLightSorting) {
  26571. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26572. }
  26573. };
  26574. /**
  26575. * Adds the given camera to this scene
  26576. * @param newCamera The camera to add
  26577. */
  26578. Scene.prototype.addCamera = function (newCamera) {
  26579. this.cameras.push(newCamera);
  26580. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26581. };
  26582. /**
  26583. * Adds the given skeleton to this scene
  26584. * @param newSkeleton The skeleton to add
  26585. */
  26586. Scene.prototype.addSkeleton = function (newSkeleton) {
  26587. this.skeletons.push(newSkeleton);
  26588. };
  26589. /**
  26590. * Adds the given particle system to this scene
  26591. * @param newParticleSystem The particle system to add
  26592. */
  26593. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26594. this.particleSystems.push(newParticleSystem);
  26595. };
  26596. /**
  26597. * Adds the given animation to this scene
  26598. * @param newAnimation The animation to add
  26599. */
  26600. Scene.prototype.addAnimation = function (newAnimation) {
  26601. this.animations.push(newAnimation);
  26602. };
  26603. /**
  26604. * Adds the given animation group to this scene.
  26605. * @param newAnimationGroup The animation group to add
  26606. */
  26607. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26608. this.animationGroups.push(newAnimationGroup);
  26609. };
  26610. /**
  26611. * Adds the given multi-material to this scene
  26612. * @param newMultiMaterial The multi-material to add
  26613. */
  26614. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26615. this.multiMaterials.push(newMultiMaterial);
  26616. };
  26617. /**
  26618. * Adds the given material to this scene
  26619. * @param newMaterial The material to add
  26620. */
  26621. Scene.prototype.addMaterial = function (newMaterial) {
  26622. this.materials.push(newMaterial);
  26623. };
  26624. /**
  26625. * Adds the given morph target to this scene
  26626. * @param newMorphTargetManager The morph target to add
  26627. */
  26628. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26629. this.morphTargetManagers.push(newMorphTargetManager);
  26630. };
  26631. /**
  26632. * Adds the given geometry to this scene
  26633. * @param newGeometry The geometry to add
  26634. */
  26635. Scene.prototype.addGeometry = function (newGeometry) {
  26636. this._geometries.push(newGeometry);
  26637. };
  26638. /**
  26639. * Adds the given lens flare system to this scene
  26640. * @param newLensFlareSystem The lens flare system to add
  26641. */
  26642. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26643. this.lensFlareSystems.push(newLensFlareSystem);
  26644. };
  26645. /**
  26646. * Adds the given effect layer to this scene
  26647. * @param newEffectLayer defines the effect layer to add
  26648. */
  26649. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26650. this.effectLayers.push(newEffectLayer);
  26651. };
  26652. /**
  26653. * Adds the given action manager to this scene
  26654. * @param newActionManager The action manager to add
  26655. */
  26656. Scene.prototype.addActionManager = function (newActionManager) {
  26657. this._actionManagers.push(newActionManager);
  26658. };
  26659. /**
  26660. * Adds the given texture to this scene.
  26661. * @param newTexture The texture to add
  26662. */
  26663. Scene.prototype.addTexture = function (newTexture) {
  26664. this.textures.push(newTexture);
  26665. };
  26666. /**
  26667. * Switch active camera
  26668. * @param newCamera defines the new active camera
  26669. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26670. */
  26671. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26672. if (attachControl === void 0) { attachControl = true; }
  26673. var canvas = this._engine.getRenderingCanvas();
  26674. if (!canvas) {
  26675. return;
  26676. }
  26677. if (this.activeCamera) {
  26678. this.activeCamera.detachControl(canvas);
  26679. }
  26680. this.activeCamera = newCamera;
  26681. if (attachControl) {
  26682. newCamera.attachControl(canvas);
  26683. }
  26684. };
  26685. /**
  26686. * sets the active camera of the scene using its ID
  26687. * @param id defines the camera's ID
  26688. * @return the new active camera or null if none found.
  26689. */
  26690. Scene.prototype.setActiveCameraByID = function (id) {
  26691. var camera = this.getCameraByID(id);
  26692. if (camera) {
  26693. this.activeCamera = camera;
  26694. return camera;
  26695. }
  26696. return null;
  26697. };
  26698. /**
  26699. * sets the active camera of the scene using its name
  26700. * @param name defines the camera's name
  26701. * @returns the new active camera or null if none found.
  26702. */
  26703. Scene.prototype.setActiveCameraByName = function (name) {
  26704. var camera = this.getCameraByName(name);
  26705. if (camera) {
  26706. this.activeCamera = camera;
  26707. return camera;
  26708. }
  26709. return null;
  26710. };
  26711. /**
  26712. * get an animation group using its name
  26713. * @param name defines the material's name
  26714. * @return the animation group or null if none found.
  26715. */
  26716. Scene.prototype.getAnimationGroupByName = function (name) {
  26717. for (var index = 0; index < this.animationGroups.length; index++) {
  26718. if (this.animationGroups[index].name === name) {
  26719. return this.animationGroups[index];
  26720. }
  26721. }
  26722. return null;
  26723. };
  26724. /**
  26725. * get a material using its id
  26726. * @param id defines the material's ID
  26727. * @return the material or null if none found.
  26728. */
  26729. Scene.prototype.getMaterialByID = function (id) {
  26730. for (var index = 0; index < this.materials.length; index++) {
  26731. if (this.materials[index].id === id) {
  26732. return this.materials[index];
  26733. }
  26734. }
  26735. return null;
  26736. };
  26737. /**
  26738. * Gets a material using its name
  26739. * @param name defines the material's name
  26740. * @return the material or null if none found.
  26741. */
  26742. Scene.prototype.getMaterialByName = function (name) {
  26743. for (var index = 0; index < this.materials.length; index++) {
  26744. if (this.materials[index].name === name) {
  26745. return this.materials[index];
  26746. }
  26747. }
  26748. return null;
  26749. };
  26750. /**
  26751. * Gets a lens flare system using its name
  26752. * @param name defines the name to look for
  26753. * @returns the lens flare system or null if not found
  26754. */
  26755. Scene.prototype.getLensFlareSystemByName = function (name) {
  26756. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26757. if (this.lensFlareSystems[index].name === name) {
  26758. return this.lensFlareSystems[index];
  26759. }
  26760. }
  26761. return null;
  26762. };
  26763. /**
  26764. * Gets a lens flare system using its id
  26765. * @param id defines the id to look for
  26766. * @returns the lens flare system or null if not found
  26767. */
  26768. Scene.prototype.getLensFlareSystemByID = function (id) {
  26769. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26770. if (this.lensFlareSystems[index].id === id) {
  26771. return this.lensFlareSystems[index];
  26772. }
  26773. }
  26774. return null;
  26775. };
  26776. /**
  26777. * Gets a camera using its id
  26778. * @param id defines the id to look for
  26779. * @returns the camera or null if not found
  26780. */
  26781. Scene.prototype.getCameraByID = function (id) {
  26782. for (var index = 0; index < this.cameras.length; index++) {
  26783. if (this.cameras[index].id === id) {
  26784. return this.cameras[index];
  26785. }
  26786. }
  26787. return null;
  26788. };
  26789. /**
  26790. * Gets a camera using its unique id
  26791. * @param uniqueId defines the unique id to look for
  26792. * @returns the camera or null if not found
  26793. */
  26794. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26795. for (var index = 0; index < this.cameras.length; index++) {
  26796. if (this.cameras[index].uniqueId === uniqueId) {
  26797. return this.cameras[index];
  26798. }
  26799. }
  26800. return null;
  26801. };
  26802. /**
  26803. * Gets a camera using its name
  26804. * @param name defines the camera's name
  26805. * @return the camera or null if none found.
  26806. */
  26807. Scene.prototype.getCameraByName = function (name) {
  26808. for (var index = 0; index < this.cameras.length; index++) {
  26809. if (this.cameras[index].name === name) {
  26810. return this.cameras[index];
  26811. }
  26812. }
  26813. return null;
  26814. };
  26815. /**
  26816. * Gets a bone using its id
  26817. * @param id defines the bone's id
  26818. * @return the bone or null if not found
  26819. */
  26820. Scene.prototype.getBoneByID = function (id) {
  26821. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26822. var skeleton = this.skeletons[skeletonIndex];
  26823. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26824. if (skeleton.bones[boneIndex].id === id) {
  26825. return skeleton.bones[boneIndex];
  26826. }
  26827. }
  26828. }
  26829. return null;
  26830. };
  26831. /**
  26832. * Gets a bone using its id
  26833. * @param name defines the bone's name
  26834. * @return the bone or null if not found
  26835. */
  26836. Scene.prototype.getBoneByName = function (name) {
  26837. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26838. var skeleton = this.skeletons[skeletonIndex];
  26839. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26840. if (skeleton.bones[boneIndex].name === name) {
  26841. return skeleton.bones[boneIndex];
  26842. }
  26843. }
  26844. }
  26845. return null;
  26846. };
  26847. /**
  26848. * Gets a light node using its name
  26849. * @param name defines the the light's name
  26850. * @return the light or null if none found.
  26851. */
  26852. Scene.prototype.getLightByName = function (name) {
  26853. for (var index = 0; index < this.lights.length; index++) {
  26854. if (this.lights[index].name === name) {
  26855. return this.lights[index];
  26856. }
  26857. }
  26858. return null;
  26859. };
  26860. /**
  26861. * Gets a light node using its id
  26862. * @param id defines the light's id
  26863. * @return the light or null if none found.
  26864. */
  26865. Scene.prototype.getLightByID = function (id) {
  26866. for (var index = 0; index < this.lights.length; index++) {
  26867. if (this.lights[index].id === id) {
  26868. return this.lights[index];
  26869. }
  26870. }
  26871. return null;
  26872. };
  26873. /**
  26874. * Gets a light node using its scene-generated unique ID
  26875. * @param uniqueId defines the light's unique id
  26876. * @return the light or null if none found.
  26877. */
  26878. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26879. for (var index = 0; index < this.lights.length; index++) {
  26880. if (this.lights[index].uniqueId === uniqueId) {
  26881. return this.lights[index];
  26882. }
  26883. }
  26884. return null;
  26885. };
  26886. /**
  26887. * Gets a particle system by id
  26888. * @param id defines the particle system id
  26889. * @return the corresponding system or null if none found
  26890. */
  26891. Scene.prototype.getParticleSystemByID = function (id) {
  26892. for (var index = 0; index < this.particleSystems.length; index++) {
  26893. if (this.particleSystems[index].id === id) {
  26894. return this.particleSystems[index];
  26895. }
  26896. }
  26897. return null;
  26898. };
  26899. /**
  26900. * Gets a geometry using its ID
  26901. * @param id defines the geometry's id
  26902. * @return the geometry or null if none found.
  26903. */
  26904. Scene.prototype.getGeometryByID = function (id) {
  26905. for (var index = 0; index < this._geometries.length; index++) {
  26906. if (this._geometries[index].id === id) {
  26907. return this._geometries[index];
  26908. }
  26909. }
  26910. return null;
  26911. };
  26912. /**
  26913. * Add a new geometry to this scene
  26914. * @param geometry defines the geometry to be added to the scene.
  26915. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26916. * @return a boolean defining if the geometry was added or not
  26917. */
  26918. Scene.prototype.pushGeometry = function (geometry, force) {
  26919. if (!force && this.getGeometryByID(geometry.id)) {
  26920. return false;
  26921. }
  26922. this._geometries.push(geometry);
  26923. //notify the collision coordinator
  26924. if (this.collisionCoordinator) {
  26925. this.collisionCoordinator.onGeometryAdded(geometry);
  26926. }
  26927. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26928. return true;
  26929. };
  26930. /**
  26931. * Removes an existing geometry
  26932. * @param geometry defines the geometry to be removed from the scene
  26933. * @return a boolean defining if the geometry was removed or not
  26934. */
  26935. Scene.prototype.removeGeometry = function (geometry) {
  26936. var index = this._geometries.indexOf(geometry);
  26937. if (index > -1) {
  26938. this._geometries.splice(index, 1);
  26939. //notify the collision coordinator
  26940. if (this.collisionCoordinator) {
  26941. this.collisionCoordinator.onGeometryDeleted(geometry);
  26942. }
  26943. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26944. return true;
  26945. }
  26946. return false;
  26947. };
  26948. /**
  26949. * Gets the list of geometries attached to the scene
  26950. * @returns an array of Geometry
  26951. */
  26952. Scene.prototype.getGeometries = function () {
  26953. return this._geometries;
  26954. };
  26955. /**
  26956. * Gets the first added mesh found of a given ID
  26957. * @param id defines the id to search for
  26958. * @return the mesh found or null if not found at all
  26959. */
  26960. Scene.prototype.getMeshByID = function (id) {
  26961. for (var index = 0; index < this.meshes.length; index++) {
  26962. if (this.meshes[index].id === id) {
  26963. return this.meshes[index];
  26964. }
  26965. }
  26966. return null;
  26967. };
  26968. /**
  26969. * Gets a list of meshes using their id
  26970. * @param id defines the id to search for
  26971. * @returns a list of meshes
  26972. */
  26973. Scene.prototype.getMeshesByID = function (id) {
  26974. return this.meshes.filter(function (m) {
  26975. return m.id === id;
  26976. });
  26977. };
  26978. /**
  26979. * Gets the first added transform node found of a given ID
  26980. * @param id defines the id to search for
  26981. * @return the found transform node or null if not found at all.
  26982. */
  26983. Scene.prototype.getTransformNodeByID = function (id) {
  26984. for (var index = 0; index < this.transformNodes.length; index++) {
  26985. if (this.transformNodes[index].id === id) {
  26986. return this.transformNodes[index];
  26987. }
  26988. }
  26989. return null;
  26990. };
  26991. /**
  26992. * Gets a list of transform nodes using their id
  26993. * @param id defines the id to search for
  26994. * @returns a list of transform nodes
  26995. */
  26996. Scene.prototype.getTransformNodesByID = function (id) {
  26997. return this.transformNodes.filter(function (m) {
  26998. return m.id === id;
  26999. });
  27000. };
  27001. /**
  27002. * Gets a mesh with its auto-generated unique id
  27003. * @param uniqueId defines the unique id to search for
  27004. * @return the found mesh or null if not found at all.
  27005. */
  27006. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27007. for (var index = 0; index < this.meshes.length; index++) {
  27008. if (this.meshes[index].uniqueId === uniqueId) {
  27009. return this.meshes[index];
  27010. }
  27011. }
  27012. return null;
  27013. };
  27014. /**
  27015. * Gets a the last added mesh using a given id
  27016. * @param id defines the id to search for
  27017. * @return the found mesh or null if not found at all.
  27018. */
  27019. Scene.prototype.getLastMeshByID = function (id) {
  27020. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27021. if (this.meshes[index].id === id) {
  27022. return this.meshes[index];
  27023. }
  27024. }
  27025. return null;
  27026. };
  27027. /**
  27028. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27029. * @param id defines the id to search for
  27030. * @return the found node or null if not found at all
  27031. */
  27032. Scene.prototype.getLastEntryByID = function (id) {
  27033. var index;
  27034. for (index = this.meshes.length - 1; index >= 0; index--) {
  27035. if (this.meshes[index].id === id) {
  27036. return this.meshes[index];
  27037. }
  27038. }
  27039. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27040. if (this.transformNodes[index].id === id) {
  27041. return this.transformNodes[index];
  27042. }
  27043. }
  27044. for (index = this.cameras.length - 1; index >= 0; index--) {
  27045. if (this.cameras[index].id === id) {
  27046. return this.cameras[index];
  27047. }
  27048. }
  27049. for (index = this.lights.length - 1; index >= 0; index--) {
  27050. if (this.lights[index].id === id) {
  27051. return this.lights[index];
  27052. }
  27053. }
  27054. return null;
  27055. };
  27056. /**
  27057. * Gets a node (Mesh, Camera, Light) using a given id
  27058. * @param id defines the id to search for
  27059. * @return the found node or null if not found at all
  27060. */
  27061. Scene.prototype.getNodeByID = function (id) {
  27062. var mesh = this.getMeshByID(id);
  27063. if (mesh) {
  27064. return mesh;
  27065. }
  27066. var light = this.getLightByID(id);
  27067. if (light) {
  27068. return light;
  27069. }
  27070. var camera = this.getCameraByID(id);
  27071. if (camera) {
  27072. return camera;
  27073. }
  27074. var bone = this.getBoneByID(id);
  27075. return bone;
  27076. };
  27077. /**
  27078. * Gets a node (Mesh, Camera, Light) using a given name
  27079. * @param name defines the name to search for
  27080. * @return the found node or null if not found at all.
  27081. */
  27082. Scene.prototype.getNodeByName = function (name) {
  27083. var mesh = this.getMeshByName(name);
  27084. if (mesh) {
  27085. return mesh;
  27086. }
  27087. var light = this.getLightByName(name);
  27088. if (light) {
  27089. return light;
  27090. }
  27091. var camera = this.getCameraByName(name);
  27092. if (camera) {
  27093. return camera;
  27094. }
  27095. var bone = this.getBoneByName(name);
  27096. return bone;
  27097. };
  27098. /**
  27099. * Gets a mesh using a given name
  27100. * @param name defines the name to search for
  27101. * @return the found mesh or null if not found at all.
  27102. */
  27103. Scene.prototype.getMeshByName = function (name) {
  27104. for (var index = 0; index < this.meshes.length; index++) {
  27105. if (this.meshes[index].name === name) {
  27106. return this.meshes[index];
  27107. }
  27108. }
  27109. return null;
  27110. };
  27111. /**
  27112. * Gets a transform node using a given name
  27113. * @param name defines the name to search for
  27114. * @return the found transform node or null if not found at all.
  27115. */
  27116. Scene.prototype.getTransformNodeByName = function (name) {
  27117. for (var index = 0; index < this.transformNodes.length; index++) {
  27118. if (this.transformNodes[index].name === name) {
  27119. return this.transformNodes[index];
  27120. }
  27121. }
  27122. return null;
  27123. };
  27124. /**
  27125. * Gets a sound using a given name
  27126. * @param name defines the name to search for
  27127. * @return the found sound or null if not found at all.
  27128. */
  27129. Scene.prototype.getSoundByName = function (name) {
  27130. var index;
  27131. if (BABYLON.AudioEngine) {
  27132. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27133. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27134. return this.mainSoundTrack.soundCollection[index];
  27135. }
  27136. }
  27137. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27138. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27139. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27140. return this.soundTracks[sdIndex].soundCollection[index];
  27141. }
  27142. }
  27143. }
  27144. }
  27145. return null;
  27146. };
  27147. /**
  27148. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27149. * @param id defines the id to search for
  27150. * @return the found skeleton or null if not found at all.
  27151. */
  27152. Scene.prototype.getLastSkeletonByID = function (id) {
  27153. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27154. if (this.skeletons[index].id === id) {
  27155. return this.skeletons[index];
  27156. }
  27157. }
  27158. return null;
  27159. };
  27160. /**
  27161. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27162. * @param id defines the id to search for
  27163. * @return the found skeleton or null if not found at all.
  27164. */
  27165. Scene.prototype.getSkeletonById = function (id) {
  27166. for (var index = 0; index < this.skeletons.length; index++) {
  27167. if (this.skeletons[index].id === id) {
  27168. return this.skeletons[index];
  27169. }
  27170. }
  27171. return null;
  27172. };
  27173. /**
  27174. * Gets a skeleton using a given name
  27175. * @param name defines the name to search for
  27176. * @return the found skeleton or null if not found at all.
  27177. */
  27178. Scene.prototype.getSkeletonByName = function (name) {
  27179. for (var index = 0; index < this.skeletons.length; index++) {
  27180. if (this.skeletons[index].name === name) {
  27181. return this.skeletons[index];
  27182. }
  27183. }
  27184. return null;
  27185. };
  27186. /**
  27187. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27188. * @param id defines the id to search for
  27189. * @return the found morph target manager or null if not found at all.
  27190. */
  27191. Scene.prototype.getMorphTargetManagerById = function (id) {
  27192. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27193. if (this.morphTargetManagers[index].uniqueId === id) {
  27194. return this.morphTargetManagers[index];
  27195. }
  27196. }
  27197. return null;
  27198. };
  27199. /**
  27200. * Gets a boolean indicating if the given mesh is active
  27201. * @param mesh defines the mesh to look for
  27202. * @returns true if the mesh is in the active list
  27203. */
  27204. Scene.prototype.isActiveMesh = function (mesh) {
  27205. return (this._activeMeshes.indexOf(mesh) !== -1);
  27206. };
  27207. /**
  27208. * Return a the first highlight layer of the scene with a given name.
  27209. * @param name The name of the highlight layer to look for.
  27210. * @return The highlight layer if found otherwise null.
  27211. */
  27212. Scene.prototype.getHighlightLayerByName = function (name) {
  27213. for (var index = 0; index < this.effectLayers.length; index++) {
  27214. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27215. return this.effectLayers[index];
  27216. }
  27217. }
  27218. return null;
  27219. };
  27220. /**
  27221. * Return a the first highlight layer of the scene with a given name.
  27222. * @param name The name of the highlight layer to look for.
  27223. * @return The highlight layer if found otherwise null.
  27224. */
  27225. Scene.prototype.getGlowLayerByName = function (name) {
  27226. for (var index = 0; index < this.effectLayers.length; index++) {
  27227. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27228. return this.effectLayers[index];
  27229. }
  27230. }
  27231. return null;
  27232. };
  27233. Object.defineProperty(Scene.prototype, "uid", {
  27234. /**
  27235. * Return a unique id as a string which can serve as an identifier for the scene
  27236. */
  27237. get: function () {
  27238. if (!this._uid) {
  27239. this._uid = BABYLON.Tools.RandomId();
  27240. }
  27241. return this._uid;
  27242. },
  27243. enumerable: true,
  27244. configurable: true
  27245. });
  27246. /**
  27247. * Add an externaly attached data from its key.
  27248. * This method call will fail and return false, if such key already exists.
  27249. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27250. * @param key the unique key that identifies the data
  27251. * @param data the data object to associate to the key for this Engine instance
  27252. * @return true if no such key were already present and the data was added successfully, false otherwise
  27253. */
  27254. Scene.prototype.addExternalData = function (key, data) {
  27255. if (!this._externalData) {
  27256. this._externalData = new BABYLON.StringDictionary();
  27257. }
  27258. return this._externalData.add(key, data);
  27259. };
  27260. /**
  27261. * Get an externaly attached data from its key
  27262. * @param key the unique key that identifies the data
  27263. * @return the associated data, if present (can be null), or undefined if not present
  27264. */
  27265. Scene.prototype.getExternalData = function (key) {
  27266. if (!this._externalData) {
  27267. return null;
  27268. }
  27269. return this._externalData.get(key);
  27270. };
  27271. /**
  27272. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27273. * @param key the unique key that identifies the data
  27274. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27275. * @return the associated data, can be null if the factory returned null.
  27276. */
  27277. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27278. if (!this._externalData) {
  27279. this._externalData = new BABYLON.StringDictionary();
  27280. }
  27281. return this._externalData.getOrAddWithFactory(key, factory);
  27282. };
  27283. /**
  27284. * Remove an externaly attached data from the Engine instance
  27285. * @param key the unique key that identifies the data
  27286. * @return true if the data was successfully removed, false if it doesn't exist
  27287. */
  27288. Scene.prototype.removeExternalData = function (key) {
  27289. return this._externalData.remove(key);
  27290. };
  27291. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27292. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27293. if (mesh.showSubMeshesBoundingBox) {
  27294. var boundingInfo = subMesh.getBoundingInfo();
  27295. if (boundingInfo !== null && boundingInfo !== undefined) {
  27296. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27297. }
  27298. }
  27299. var material = subMesh.getMaterial();
  27300. if (material !== null && material !== undefined) {
  27301. // Render targets
  27302. if (material.getRenderTargetTextures !== undefined) {
  27303. if (this._processedMaterials.indexOf(material) === -1) {
  27304. this._processedMaterials.push(material);
  27305. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27306. }
  27307. }
  27308. // Dispatch
  27309. this._activeIndices.addCount(subMesh.indexCount, false);
  27310. this._renderingManager.dispatch(subMesh, mesh, material);
  27311. }
  27312. }
  27313. };
  27314. /**
  27315. * Clear the processed materials smart array preventing retention point in material dispose.
  27316. */
  27317. Scene.prototype.freeProcessedMaterials = function () {
  27318. this._processedMaterials.dispose();
  27319. };
  27320. /**
  27321. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27322. */
  27323. Scene.prototype.freeActiveMeshes = function () {
  27324. this._activeMeshes.dispose();
  27325. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27326. this.activeCamera._activeMeshes.dispose();
  27327. }
  27328. if (this.activeCameras) {
  27329. for (var i = 0; i < this.activeCameras.length; i++) {
  27330. var activeCamera = this.activeCameras[i];
  27331. if (activeCamera && activeCamera._activeMeshes) {
  27332. activeCamera._activeMeshes.dispose();
  27333. }
  27334. }
  27335. }
  27336. };
  27337. /**
  27338. * Clear the info related to rendering groups preventing retention points during dispose.
  27339. */
  27340. Scene.prototype.freeRenderingGroups = function () {
  27341. if (this._renderingManager) {
  27342. this._renderingManager.freeRenderingGroups();
  27343. }
  27344. if (this.textures) {
  27345. for (var i = 0; i < this.textures.length; i++) {
  27346. var texture = this.textures[i];
  27347. if (texture && texture.renderList) {
  27348. texture.freeRenderingGroups();
  27349. }
  27350. }
  27351. }
  27352. };
  27353. /** @hidden */
  27354. Scene.prototype._isInIntermediateRendering = function () {
  27355. return this._intermediateRendering;
  27356. };
  27357. /**
  27358. * Defines the current active mesh candidate provider
  27359. * @param provider defines the provider to use
  27360. */
  27361. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27362. this._activeMeshCandidateProvider = provider;
  27363. };
  27364. /**
  27365. * Gets the current active mesh candidate provider
  27366. * @returns the current active mesh candidate provider
  27367. */
  27368. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27369. return this._activeMeshCandidateProvider;
  27370. };
  27371. /**
  27372. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27373. * @returns the current scene
  27374. */
  27375. Scene.prototype.freezeActiveMeshes = function () {
  27376. if (!this.activeCamera) {
  27377. return this;
  27378. }
  27379. if (!this._frustumPlanes) {
  27380. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27381. }
  27382. this._evaluateActiveMeshes();
  27383. this._activeMeshesFrozen = true;
  27384. return this;
  27385. };
  27386. /**
  27387. * Use this function to restart evaluating active meshes on every frame
  27388. * @returns the current scene
  27389. */
  27390. Scene.prototype.unfreezeActiveMeshes = function () {
  27391. this._activeMeshesFrozen = false;
  27392. return this;
  27393. };
  27394. Scene.prototype._evaluateActiveMeshes = function () {
  27395. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27396. return;
  27397. }
  27398. if (!this.activeCamera) {
  27399. return;
  27400. }
  27401. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27402. this.activeCamera._activeMeshes.reset();
  27403. this._activeMeshes.reset();
  27404. this._renderingManager.reset();
  27405. this._processedMaterials.reset();
  27406. this._activeParticleSystems.reset();
  27407. this._activeSkeletons.reset();
  27408. this._softwareSkinnedMeshes.reset();
  27409. if (this._boundingBoxRenderer) {
  27410. this._boundingBoxRenderer.reset();
  27411. }
  27412. // Meshes
  27413. var meshes;
  27414. var len;
  27415. var checkIsEnabled = true;
  27416. // Determine mesh candidates
  27417. if (this._activeMeshCandidateProvider !== undefined) {
  27418. // Use _activeMeshCandidateProvider
  27419. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27420. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27421. if (meshes !== undefined) {
  27422. len = meshes.length;
  27423. }
  27424. else {
  27425. len = 0;
  27426. }
  27427. }
  27428. else if (this._selectionOctree !== undefined) {
  27429. // Octree
  27430. var selection = this._selectionOctree.select(this._frustumPlanes);
  27431. meshes = selection.data;
  27432. len = selection.length;
  27433. }
  27434. else {
  27435. // Full scene traversal
  27436. len = this.meshes.length;
  27437. meshes = this.meshes;
  27438. }
  27439. // Check each mesh
  27440. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27441. mesh = meshes[meshIndex];
  27442. if (mesh.isBlocked) {
  27443. continue;
  27444. }
  27445. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27446. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27447. continue;
  27448. }
  27449. mesh.computeWorldMatrix();
  27450. // Intersections
  27451. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27452. this._meshesForIntersections.pushNoDuplicate(mesh);
  27453. }
  27454. // Switch to current LOD
  27455. meshLOD = mesh.getLOD(this.activeCamera);
  27456. if (meshLOD === undefined || meshLOD === null) {
  27457. continue;
  27458. }
  27459. mesh._preActivate();
  27460. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27461. this._activeMeshes.push(mesh);
  27462. this.activeCamera._activeMeshes.push(mesh);
  27463. mesh._activate(this._renderId);
  27464. if (meshLOD !== mesh) {
  27465. meshLOD._activate(this._renderId);
  27466. }
  27467. this._activeMesh(mesh, meshLOD);
  27468. }
  27469. }
  27470. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27471. // Particle systems
  27472. if (this.particlesEnabled) {
  27473. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27474. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27475. var particleSystem = this.particleSystems[particleIndex];
  27476. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27477. continue;
  27478. }
  27479. var emitter = particleSystem.emitter;
  27480. if (!emitter.position || emitter.isEnabled()) {
  27481. this._activeParticleSystems.push(particleSystem);
  27482. particleSystem.animate();
  27483. this._renderingManager.dispatchParticles(particleSystem);
  27484. }
  27485. }
  27486. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27487. }
  27488. };
  27489. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27490. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27491. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27492. mesh.skeleton.prepare();
  27493. }
  27494. if (!mesh.computeBonesUsingShaders) {
  27495. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27496. }
  27497. }
  27498. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27499. var boundingInfo = sourceMesh.getBoundingInfo();
  27500. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27501. }
  27502. if (mesh !== undefined && mesh !== null
  27503. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27504. // Submeshes Octrees
  27505. var len;
  27506. var subMeshes;
  27507. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27508. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27509. len = intersections.length;
  27510. subMeshes = intersections.data;
  27511. }
  27512. else {
  27513. subMeshes = mesh.subMeshes;
  27514. len = subMeshes.length;
  27515. }
  27516. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27517. subMesh = subMeshes[subIndex];
  27518. this._evaluateSubMesh(subMesh, mesh);
  27519. }
  27520. }
  27521. };
  27522. /**
  27523. * Update the transform matrix to update from the current active camera
  27524. * @param force defines a boolean used to force the update even if cache is up to date
  27525. */
  27526. Scene.prototype.updateTransformMatrix = function (force) {
  27527. if (!this.activeCamera) {
  27528. return;
  27529. }
  27530. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27531. };
  27532. /**
  27533. * 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)
  27534. * @param alternateCamera defines the camera to use
  27535. */
  27536. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27537. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27538. };
  27539. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27540. if (camera && camera._skipRendering) {
  27541. return;
  27542. }
  27543. var engine = this._engine;
  27544. this.activeCamera = camera;
  27545. if (!this.activeCamera)
  27546. throw new Error("Active camera not set");
  27547. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27548. // Viewport
  27549. engine.setViewport(this.activeCamera.viewport);
  27550. // Camera
  27551. this.resetCachedMaterial();
  27552. this._renderId++;
  27553. this.updateTransformMatrix();
  27554. if (camera._alternateCamera) {
  27555. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27556. this._alternateRendering = true;
  27557. }
  27558. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27559. // Meshes
  27560. this._evaluateActiveMeshes();
  27561. // Software skinning
  27562. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27563. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27564. mesh.applySkeleton(mesh.skeleton);
  27565. }
  27566. // Render targets
  27567. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27568. var needsRestoreFrameBuffer = false;
  27569. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27570. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27571. }
  27572. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27573. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27574. }
  27575. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27576. this._intermediateRendering = true;
  27577. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27578. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27579. var renderTarget = this._renderTargets.data[renderIndex];
  27580. if (renderTarget._shouldRender()) {
  27581. this._renderId++;
  27582. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27583. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27584. }
  27585. }
  27586. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27587. this._intermediateRendering = false;
  27588. this._renderId++;
  27589. needsRestoreFrameBuffer = true; // Restore back buffer
  27590. }
  27591. // Render EffecttLayer Texture
  27592. var stencilState = this._engine.getStencilBuffer();
  27593. var renderEffects = false;
  27594. var needStencil = false;
  27595. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27596. this._intermediateRendering = true;
  27597. for (var i = 0; i < this.effectLayers.length; i++) {
  27598. var effectLayer = this.effectLayers[i];
  27599. if (effectLayer.shouldRender() &&
  27600. (!effectLayer.camera ||
  27601. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27602. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27603. renderEffects = true;
  27604. needStencil = needStencil || effectLayer.needStencil();
  27605. var renderTarget = effectLayer._mainTexture;
  27606. if (renderTarget._shouldRender()) {
  27607. this._renderId++;
  27608. renderTarget.render(false, false);
  27609. needsRestoreFrameBuffer = true;
  27610. }
  27611. }
  27612. }
  27613. this._intermediateRendering = false;
  27614. this._renderId++;
  27615. }
  27616. if (needsRestoreFrameBuffer) {
  27617. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27618. }
  27619. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27620. // Prepare Frame
  27621. this.postProcessManager._prepareFrame();
  27622. // Backgrounds
  27623. var layerIndex;
  27624. var layer;
  27625. if (this.layers.length) {
  27626. engine.setDepthBuffer(false);
  27627. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27628. layer = this.layers[layerIndex];
  27629. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27630. layer.render();
  27631. }
  27632. }
  27633. engine.setDepthBuffer(true);
  27634. }
  27635. // Activate effect Layer stencil
  27636. if (needStencil) {
  27637. this._engine.setStencilBuffer(true);
  27638. }
  27639. // Render
  27640. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27641. this._renderingManager.render(null, null, true, true);
  27642. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27643. // Restore effect Layer stencil
  27644. if (needStencil) {
  27645. this._engine.setStencilBuffer(stencilState);
  27646. }
  27647. // Bounding boxes
  27648. if (this._boundingBoxRenderer) {
  27649. this._boundingBoxRenderer.render();
  27650. }
  27651. // Lens flares
  27652. if (this.lensFlaresEnabled) {
  27653. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27654. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27655. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27656. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27657. lensFlareSystem.render();
  27658. }
  27659. }
  27660. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27661. }
  27662. // Effect Layer
  27663. if (renderEffects) {
  27664. engine.setDepthBuffer(false);
  27665. for (var i = 0; i < this.effectLayers.length; i++) {
  27666. if (this.effectLayers[i].shouldRender()) {
  27667. this.effectLayers[i].render();
  27668. }
  27669. }
  27670. engine.setDepthBuffer(true);
  27671. }
  27672. // Foregrounds
  27673. if (this.layers.length) {
  27674. engine.setDepthBuffer(false);
  27675. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27676. layer = this.layers[layerIndex];
  27677. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27678. layer.render();
  27679. }
  27680. }
  27681. engine.setDepthBuffer(true);
  27682. }
  27683. // Finalize frame
  27684. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27685. // Reset some special arrays
  27686. this._renderTargets.reset();
  27687. this._alternateRendering = false;
  27688. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27689. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27690. };
  27691. Scene.prototype._processSubCameras = function (camera) {
  27692. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27693. this._renderForCamera(camera);
  27694. return;
  27695. }
  27696. // rig cameras
  27697. for (var index = 0; index < camera._rigCameras.length; index++) {
  27698. this._renderForCamera(camera._rigCameras[index], camera);
  27699. }
  27700. this.activeCamera = camera;
  27701. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27702. };
  27703. Scene.prototype._checkIntersections = function () {
  27704. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27705. var sourceMesh = this._meshesForIntersections.data[index];
  27706. if (!sourceMesh.actionManager) {
  27707. continue;
  27708. }
  27709. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27710. var action = sourceMesh.actionManager.actions[actionIndex];
  27711. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27712. var parameters = action.getTriggerParameter();
  27713. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27714. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27715. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27716. if (areIntersecting && currentIntersectionInProgress === -1) {
  27717. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27718. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27719. sourceMesh._intersectionsInProgress.push(otherMesh);
  27720. }
  27721. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27722. sourceMesh._intersectionsInProgress.push(otherMesh);
  27723. }
  27724. }
  27725. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27726. //They intersected, and now they don't.
  27727. //is this trigger an exit trigger? execute an event.
  27728. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27729. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27730. }
  27731. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27732. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27733. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27734. return otherMesh === parameterMesh;
  27735. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27736. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27737. }
  27738. }
  27739. }
  27740. }
  27741. }
  27742. };
  27743. /**
  27744. * Render the scene
  27745. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27746. */
  27747. Scene.prototype.render = function (updateCameras) {
  27748. if (updateCameras === void 0) { updateCameras = true; }
  27749. if (this.isDisposed) {
  27750. return;
  27751. }
  27752. this._activeParticles.fetchNewFrame();
  27753. this._totalVertices.fetchNewFrame();
  27754. this._activeIndices.fetchNewFrame();
  27755. this._activeBones.fetchNewFrame();
  27756. this._meshesForIntersections.reset();
  27757. this.resetCachedMaterial();
  27758. this.onBeforeAnimationsObservable.notifyObservers(this);
  27759. // Actions
  27760. if (this.actionManager) {
  27761. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27762. }
  27763. //Simplification Queue
  27764. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27765. this.simplificationQueue.executeNext();
  27766. }
  27767. if (this._engine.isDeterministicLockStep()) {
  27768. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27769. var defaultFPS = (60.0 / 1000.0);
  27770. var defaultFrameTime = 1000 / 60; // frame time in MS
  27771. if (this._physicsEngine) {
  27772. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27773. }
  27774. var stepsTaken = 0;
  27775. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27776. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27777. internalSteps = Math.min(internalSteps, maxSubSteps);
  27778. do {
  27779. this.onBeforeStepObservable.notifyObservers(this);
  27780. // Animations
  27781. this._animationRatio = defaultFrameTime * defaultFPS;
  27782. this._animate();
  27783. this.onAfterAnimationsObservable.notifyObservers(this);
  27784. // Physics
  27785. if (this._physicsEngine) {
  27786. this.onBeforePhysicsObservable.notifyObservers(this);
  27787. this._physicsEngine._step(defaultFrameTime / 1000);
  27788. this.onAfterPhysicsObservable.notifyObservers(this);
  27789. }
  27790. this.onAfterStepObservable.notifyObservers(this);
  27791. this._currentStepId++;
  27792. stepsTaken++;
  27793. deltaTime -= defaultFrameTime;
  27794. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27795. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27796. }
  27797. else {
  27798. // Animations
  27799. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27800. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27801. this._animate();
  27802. this.onAfterAnimationsObservable.notifyObservers(this);
  27803. // Physics
  27804. if (this._physicsEngine) {
  27805. this.onBeforePhysicsObservable.notifyObservers(this);
  27806. this._physicsEngine._step(deltaTime / 1000.0);
  27807. this.onAfterPhysicsObservable.notifyObservers(this);
  27808. }
  27809. }
  27810. // update gamepad manager
  27811. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27812. this._gamepadManager._checkGamepadsStatus();
  27813. }
  27814. // Update Cameras
  27815. if (updateCameras) {
  27816. if (this.activeCameras.length > 0) {
  27817. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27818. var camera = this.activeCameras[cameraIndex];
  27819. camera.update();
  27820. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27821. // rig cameras
  27822. for (var index = 0; index < camera._rigCameras.length; index++) {
  27823. camera._rigCameras[index].update();
  27824. }
  27825. }
  27826. }
  27827. }
  27828. else if (this.activeCamera) {
  27829. this.activeCamera.update();
  27830. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27831. // rig cameras
  27832. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27833. this.activeCamera._rigCameras[index].update();
  27834. }
  27835. }
  27836. }
  27837. }
  27838. // Before render
  27839. this.onBeforeRenderObservable.notifyObservers(this);
  27840. // Customs render targets
  27841. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27842. var engine = this.getEngine();
  27843. var currentActiveCamera = this.activeCamera;
  27844. if (this.renderTargetsEnabled) {
  27845. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27846. this._intermediateRendering = true;
  27847. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27848. var renderTarget = this.customRenderTargets[customIndex];
  27849. if (renderTarget._shouldRender()) {
  27850. this._renderId++;
  27851. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27852. if (!this.activeCamera)
  27853. throw new Error("Active camera not set");
  27854. // Viewport
  27855. engine.setViewport(this.activeCamera.viewport);
  27856. // Camera
  27857. this.updateTransformMatrix();
  27858. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27859. }
  27860. }
  27861. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27862. this._intermediateRendering = false;
  27863. this._renderId++;
  27864. }
  27865. // Restore back buffer
  27866. if (this.customRenderTargets.length > 0) {
  27867. engine.restoreDefaultFramebuffer();
  27868. }
  27869. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27870. this.activeCamera = currentActiveCamera;
  27871. // Procedural textures
  27872. if (this.proceduralTexturesEnabled) {
  27873. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27874. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27875. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27876. if (proceduralTexture._shouldRender()) {
  27877. proceduralTexture.render();
  27878. }
  27879. }
  27880. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27881. }
  27882. // Clear
  27883. if (this.autoClearDepthAndStencil || this.autoClear) {
  27884. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27885. }
  27886. // Shadows
  27887. if (this.shadowsEnabled) {
  27888. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27889. var light = this.lights[lightIndex];
  27890. var shadowGenerator = light.getShadowGenerator();
  27891. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27892. var shadowMap = (shadowGenerator.getShadowMap());
  27893. if (this.textures.indexOf(shadowMap) !== -1) {
  27894. this._renderTargets.push(shadowMap);
  27895. }
  27896. }
  27897. }
  27898. }
  27899. // Depth renderer
  27900. for (var key in this._depthRenderer) {
  27901. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27902. }
  27903. // Geometry renderer
  27904. if (this._geometryBufferRenderer) {
  27905. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27906. }
  27907. // RenderPipeline
  27908. if (this._postProcessRenderPipelineManager) {
  27909. this._postProcessRenderPipelineManager.update();
  27910. }
  27911. // Multi-cameras?
  27912. if (this.activeCameras.length > 0) {
  27913. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27914. if (cameraIndex > 0) {
  27915. this._engine.clear(null, false, true, true);
  27916. }
  27917. this._processSubCameras(this.activeCameras[cameraIndex]);
  27918. }
  27919. }
  27920. else {
  27921. if (!this.activeCamera) {
  27922. throw new Error("No camera defined");
  27923. }
  27924. this._processSubCameras(this.activeCamera);
  27925. }
  27926. // Intersection checks
  27927. this._checkIntersections();
  27928. // Update the audio listener attached to the camera
  27929. if (BABYLON.AudioEngine) {
  27930. this._updateAudioParameters();
  27931. }
  27932. // After render
  27933. if (this.afterRender) {
  27934. this.afterRender();
  27935. }
  27936. this.onAfterRenderObservable.notifyObservers(this);
  27937. // Cleaning
  27938. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27939. var data = this._toBeDisposed.data[index];
  27940. if (data) {
  27941. data.dispose();
  27942. }
  27943. this._toBeDisposed[index] = null;
  27944. }
  27945. this._toBeDisposed.reset();
  27946. if (this.dumpNextRenderTargets) {
  27947. this.dumpNextRenderTargets = false;
  27948. }
  27949. this._activeBones.addCount(0, true);
  27950. this._activeIndices.addCount(0, true);
  27951. this._activeParticles.addCount(0, true);
  27952. };
  27953. Scene.prototype._updateAudioParameters = function () {
  27954. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27955. return;
  27956. }
  27957. var listeningCamera;
  27958. var audioEngine = BABYLON.Engine.audioEngine;
  27959. if (this.activeCameras.length > 0) {
  27960. listeningCamera = this.activeCameras[0];
  27961. }
  27962. else {
  27963. listeningCamera = this.activeCamera;
  27964. }
  27965. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27966. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27967. // for VR cameras
  27968. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27969. listeningCamera = listeningCamera.rigCameras[0];
  27970. }
  27971. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27972. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27973. cameraDirection.normalize();
  27974. // To avoid some errors on GearVR
  27975. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27976. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27977. }
  27978. var i;
  27979. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27980. var sound = this.mainSoundTrack.soundCollection[i];
  27981. if (sound.useCustomAttenuation) {
  27982. sound.updateDistanceFromListener();
  27983. }
  27984. }
  27985. for (i = 0; i < this.soundTracks.length; i++) {
  27986. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27987. sound = this.soundTracks[i].soundCollection[j];
  27988. if (sound.useCustomAttenuation) {
  27989. sound.updateDistanceFromListener();
  27990. }
  27991. }
  27992. }
  27993. }
  27994. };
  27995. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27996. // Audio
  27997. /**
  27998. * Gets or sets if audio support is enabled
  27999. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28000. */
  28001. get: function () {
  28002. return this._audioEnabled;
  28003. },
  28004. set: function (value) {
  28005. this._audioEnabled = value;
  28006. if (BABYLON.AudioEngine) {
  28007. if (this._audioEnabled) {
  28008. this._enableAudio();
  28009. }
  28010. else {
  28011. this._disableAudio();
  28012. }
  28013. }
  28014. },
  28015. enumerable: true,
  28016. configurable: true
  28017. });
  28018. Scene.prototype._disableAudio = function () {
  28019. var i;
  28020. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28021. this.mainSoundTrack.soundCollection[i].pause();
  28022. }
  28023. for (i = 0; i < this.soundTracks.length; i++) {
  28024. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28025. this.soundTracks[i].soundCollection[j].pause();
  28026. }
  28027. }
  28028. };
  28029. Scene.prototype._enableAudio = function () {
  28030. var i;
  28031. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28032. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28033. this.mainSoundTrack.soundCollection[i].play();
  28034. }
  28035. }
  28036. for (i = 0; i < this.soundTracks.length; i++) {
  28037. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28038. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28039. this.soundTracks[i].soundCollection[j].play();
  28040. }
  28041. }
  28042. }
  28043. };
  28044. Object.defineProperty(Scene.prototype, "headphone", {
  28045. /**
  28046. * Gets or sets if audio will be output to headphones
  28047. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28048. */
  28049. get: function () {
  28050. return this._headphone;
  28051. },
  28052. set: function (value) {
  28053. this._headphone = value;
  28054. if (BABYLON.AudioEngine) {
  28055. if (this._headphone) {
  28056. this._switchAudioModeForHeadphones();
  28057. }
  28058. else {
  28059. this._switchAudioModeForNormalSpeakers();
  28060. }
  28061. }
  28062. },
  28063. enumerable: true,
  28064. configurable: true
  28065. });
  28066. Scene.prototype._switchAudioModeForHeadphones = function () {
  28067. this.mainSoundTrack.switchPanningModelToHRTF();
  28068. for (var i = 0; i < this.soundTracks.length; i++) {
  28069. this.soundTracks[i].switchPanningModelToHRTF();
  28070. }
  28071. };
  28072. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28073. this.mainSoundTrack.switchPanningModelToEqualPower();
  28074. for (var i = 0; i < this.soundTracks.length; i++) {
  28075. this.soundTracks[i].switchPanningModelToEqualPower();
  28076. }
  28077. };
  28078. /**
  28079. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28080. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28081. * @returns the created depth renderer
  28082. */
  28083. Scene.prototype.enableDepthRenderer = function (camera) {
  28084. camera = camera || this.activeCamera;
  28085. if (!camera) {
  28086. throw "No camera available to enable depth renderer";
  28087. }
  28088. if (!this._depthRenderer[camera.id]) {
  28089. var textureType = 0;
  28090. if (this._engine.getCaps().textureHalfFloatRender) {
  28091. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28092. }
  28093. else if (this._engine.getCaps().textureFloatRender) {
  28094. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28095. }
  28096. else {
  28097. throw "Depth renderer does not support int texture type";
  28098. }
  28099. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28100. }
  28101. return this._depthRenderer[camera.id];
  28102. };
  28103. /**
  28104. * Disables a depth renderer for a given camera
  28105. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28106. */
  28107. Scene.prototype.disableDepthRenderer = function (camera) {
  28108. camera = camera || this.activeCamera;
  28109. if (!camera || !this._depthRenderer[camera.id]) {
  28110. return;
  28111. }
  28112. this._depthRenderer[camera.id].dispose();
  28113. delete this._depthRenderer[camera.id];
  28114. };
  28115. /**
  28116. * Enables a GeometryBufferRender and associates it with the scene
  28117. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28118. * @returns the GeometryBufferRenderer
  28119. */
  28120. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28121. if (ratio === void 0) { ratio = 1; }
  28122. if (this._geometryBufferRenderer) {
  28123. return this._geometryBufferRenderer;
  28124. }
  28125. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28126. if (!this._geometryBufferRenderer.isSupported) {
  28127. this._geometryBufferRenderer = null;
  28128. }
  28129. return this._geometryBufferRenderer;
  28130. };
  28131. /**
  28132. * Disables the GeometryBufferRender associated with the scene
  28133. */
  28134. Scene.prototype.disableGeometryBufferRenderer = function () {
  28135. if (!this._geometryBufferRenderer) {
  28136. return;
  28137. }
  28138. this._geometryBufferRenderer.dispose();
  28139. this._geometryBufferRenderer = null;
  28140. };
  28141. /**
  28142. * Freeze all materials
  28143. * A frozen material will not be updatable but should be faster to render
  28144. */
  28145. Scene.prototype.freezeMaterials = function () {
  28146. for (var i = 0; i < this.materials.length; i++) {
  28147. this.materials[i].freeze();
  28148. }
  28149. };
  28150. /**
  28151. * Unfreeze all materials
  28152. * A frozen material will not be updatable but should be faster to render
  28153. */
  28154. Scene.prototype.unfreezeMaterials = function () {
  28155. for (var i = 0; i < this.materials.length; i++) {
  28156. this.materials[i].unfreeze();
  28157. }
  28158. };
  28159. /**
  28160. * Releases all held ressources
  28161. */
  28162. Scene.prototype.dispose = function () {
  28163. this.beforeRender = null;
  28164. this.afterRender = null;
  28165. this.skeletons = [];
  28166. this.morphTargetManagers = [];
  28167. this.importedMeshesFiles = new Array();
  28168. this.stopAllAnimations();
  28169. this.resetCachedMaterial();
  28170. for (var key in this._depthRenderer) {
  28171. this._depthRenderer[key].dispose();
  28172. }
  28173. if (this._gamepadManager) {
  28174. this._gamepadManager.dispose();
  28175. this._gamepadManager = null;
  28176. }
  28177. // Smart arrays
  28178. if (this.activeCamera) {
  28179. this.activeCamera._activeMeshes.dispose();
  28180. this.activeCamera = null;
  28181. }
  28182. this._activeMeshes.dispose();
  28183. this._renderingManager.dispose();
  28184. this._processedMaterials.dispose();
  28185. this._activeParticleSystems.dispose();
  28186. this._activeSkeletons.dispose();
  28187. this._softwareSkinnedMeshes.dispose();
  28188. this._renderTargets.dispose();
  28189. this._registeredForLateAnimationBindings.dispose();
  28190. if (this._boundingBoxRenderer) {
  28191. this._boundingBoxRenderer.dispose();
  28192. }
  28193. this._meshesForIntersections.dispose();
  28194. this._toBeDisposed.dispose();
  28195. // Abort active requests
  28196. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28197. var request = _a[_i];
  28198. request.abort();
  28199. }
  28200. // Debug layer
  28201. if (this._debugLayer) {
  28202. this._debugLayer.hide();
  28203. }
  28204. // Events
  28205. this.onDisposeObservable.notifyObservers(this);
  28206. this.onDisposeObservable.clear();
  28207. this.onBeforeRenderObservable.clear();
  28208. this.onAfterRenderObservable.clear();
  28209. this.onBeforeRenderTargetsRenderObservable.clear();
  28210. this.onAfterRenderTargetsRenderObservable.clear();
  28211. this.onAfterStepObservable.clear();
  28212. this.onBeforeStepObservable.clear();
  28213. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28214. this.onAfterActiveMeshesEvaluationObservable.clear();
  28215. this.onBeforeParticlesRenderingObservable.clear();
  28216. this.onAfterParticlesRenderingObservable.clear();
  28217. this.onBeforeSpritesRenderingObservable.clear();
  28218. this.onAfterSpritesRenderingObservable.clear();
  28219. this.onBeforeDrawPhaseObservable.clear();
  28220. this.onAfterDrawPhaseObservable.clear();
  28221. this.onBeforePhysicsObservable.clear();
  28222. this.onAfterPhysicsObservable.clear();
  28223. this.onBeforeAnimationsObservable.clear();
  28224. this.onAfterAnimationsObservable.clear();
  28225. this.onDataLoadedObservable.clear();
  28226. this.detachControl();
  28227. // Release sounds & sounds tracks
  28228. if (BABYLON.AudioEngine) {
  28229. this.disposeSounds();
  28230. }
  28231. // VR Helper
  28232. if (this.VRHelper) {
  28233. this.VRHelper.dispose();
  28234. }
  28235. // Detach cameras
  28236. var canvas = this._engine.getRenderingCanvas();
  28237. if (canvas) {
  28238. var index;
  28239. for (index = 0; index < this.cameras.length; index++) {
  28240. this.cameras[index].detachControl(canvas);
  28241. }
  28242. }
  28243. // Release animation groups
  28244. while (this.animationGroups.length) {
  28245. this.animationGroups[0].dispose();
  28246. }
  28247. // Release lights
  28248. while (this.lights.length) {
  28249. this.lights[0].dispose();
  28250. }
  28251. // Release meshes
  28252. while (this.meshes.length) {
  28253. this.meshes[0].dispose(true);
  28254. }
  28255. while (this.transformNodes.length) {
  28256. this.removeTransformNode(this.transformNodes[0]);
  28257. }
  28258. // Release cameras
  28259. while (this.cameras.length) {
  28260. this.cameras[0].dispose();
  28261. }
  28262. // Release materials
  28263. if (this.defaultMaterial) {
  28264. this.defaultMaterial.dispose();
  28265. }
  28266. while (this.multiMaterials.length) {
  28267. this.multiMaterials[0].dispose();
  28268. }
  28269. while (this.materials.length) {
  28270. this.materials[0].dispose();
  28271. }
  28272. // Release particles
  28273. while (this.particleSystems.length) {
  28274. this.particleSystems[0].dispose();
  28275. }
  28276. // Release sprites
  28277. while (this.spriteManagers.length) {
  28278. this.spriteManagers[0].dispose();
  28279. }
  28280. // Release postProcesses
  28281. while (this.postProcesses.length) {
  28282. this.postProcesses[0].dispose();
  28283. }
  28284. // Release layers
  28285. while (this.layers.length) {
  28286. this.layers[0].dispose();
  28287. }
  28288. while (this.effectLayers.length) {
  28289. this.effectLayers[0].dispose();
  28290. }
  28291. // Release textures
  28292. while (this.textures.length) {
  28293. this.textures[0].dispose();
  28294. }
  28295. // Release UBO
  28296. this._sceneUbo.dispose();
  28297. if (this._alternateSceneUbo) {
  28298. this._alternateSceneUbo.dispose();
  28299. }
  28300. // Post-processes
  28301. this.postProcessManager.dispose();
  28302. if (this._postProcessRenderPipelineManager) {
  28303. this._postProcessRenderPipelineManager.dispose();
  28304. }
  28305. // Physics
  28306. if (this._physicsEngine) {
  28307. this.disablePhysicsEngine();
  28308. }
  28309. // Remove from engine
  28310. index = this._engine.scenes.indexOf(this);
  28311. if (index > -1) {
  28312. this._engine.scenes.splice(index, 1);
  28313. }
  28314. this._engine.wipeCaches(true);
  28315. this._isDisposed = true;
  28316. };
  28317. Object.defineProperty(Scene.prototype, "isDisposed", {
  28318. /**
  28319. * Gets if the scene is already disposed
  28320. */
  28321. get: function () {
  28322. return this._isDisposed;
  28323. },
  28324. enumerable: true,
  28325. configurable: true
  28326. });
  28327. /**
  28328. * Releases sounds & soundtracks
  28329. */
  28330. Scene.prototype.disposeSounds = function () {
  28331. if (!this._mainSoundTrack) {
  28332. return;
  28333. }
  28334. this.mainSoundTrack.dispose();
  28335. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28336. this.soundTracks[scIndex].dispose();
  28337. }
  28338. };
  28339. /**
  28340. * Call this function to reduce memory footprint of the scene.
  28341. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28342. */
  28343. Scene.prototype.clearCachedVertexData = function () {
  28344. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28345. var mesh = this.meshes[meshIndex];
  28346. var geometry = mesh.geometry;
  28347. if (geometry) {
  28348. geometry._indices = [];
  28349. for (var vbName in geometry._vertexBuffers) {
  28350. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28351. continue;
  28352. }
  28353. geometry._vertexBuffers[vbName]._buffer._data = null;
  28354. }
  28355. }
  28356. }
  28357. };
  28358. /**
  28359. * This function will remove the local cached buffer data from texture.
  28360. * It will save memory but will prevent the texture from being rebuilt
  28361. */
  28362. Scene.prototype.cleanCachedTextureBuffer = function () {
  28363. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28364. var baseTexture = _a[_i];
  28365. var buffer = baseTexture._buffer;
  28366. if (buffer) {
  28367. baseTexture._buffer = null;
  28368. }
  28369. }
  28370. };
  28371. // Octrees
  28372. /**
  28373. * Get the world extend vectors with an optional filter
  28374. *
  28375. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28376. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28377. */
  28378. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28379. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28380. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28381. filterPredicate = filterPredicate || (function () { return true; });
  28382. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28383. mesh.computeWorldMatrix(true);
  28384. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28385. return;
  28386. }
  28387. var boundingInfo = mesh.getBoundingInfo();
  28388. var minBox = boundingInfo.boundingBox.minimumWorld;
  28389. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28390. BABYLON.Tools.CheckExtends(minBox, min, max);
  28391. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28392. });
  28393. return {
  28394. min: min,
  28395. max: max
  28396. };
  28397. };
  28398. /**
  28399. * Creates or updates the octree used to boost selection (picking)
  28400. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28401. * @param maxCapacity defines the maximum capacity per leaf
  28402. * @param maxDepth defines the maximum depth of the octree
  28403. * @returns an octree of AbstractMesh
  28404. */
  28405. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28406. if (maxCapacity === void 0) { maxCapacity = 64; }
  28407. if (maxDepth === void 0) { maxDepth = 2; }
  28408. if (!this._selectionOctree) {
  28409. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28410. }
  28411. var worldExtends = this.getWorldExtends();
  28412. // Update octree
  28413. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28414. return this._selectionOctree;
  28415. };
  28416. // Picking
  28417. /**
  28418. * Creates a ray that can be used to pick in the scene
  28419. * @param x defines the x coordinate of the origin (on-screen)
  28420. * @param y defines the y coordinate of the origin (on-screen)
  28421. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28422. * @param camera defines the camera to use for the picking
  28423. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28424. * @returns a Ray
  28425. */
  28426. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28427. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28428. var result = BABYLON.Ray.Zero();
  28429. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28430. return result;
  28431. };
  28432. /**
  28433. * Creates a ray that can be used to pick in the scene
  28434. * @param x defines the x coordinate of the origin (on-screen)
  28435. * @param y defines the y coordinate of the origin (on-screen)
  28436. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28437. * @param result defines the ray where to store the picking ray
  28438. * @param camera defines the camera to use for the picking
  28439. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28440. * @returns the current scene
  28441. */
  28442. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28443. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28444. var engine = this._engine;
  28445. if (!camera) {
  28446. if (!this.activeCamera)
  28447. throw new Error("Active camera not set");
  28448. camera = this.activeCamera;
  28449. }
  28450. var cameraViewport = camera.viewport;
  28451. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28452. // Moving coordinates to local viewport world
  28453. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28454. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28455. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28456. return this;
  28457. };
  28458. /**
  28459. * Creates a ray that can be used to pick in the scene
  28460. * @param x defines the x coordinate of the origin (on-screen)
  28461. * @param y defines the y coordinate of the origin (on-screen)
  28462. * @param camera defines the camera to use for the picking
  28463. * @returns a Ray
  28464. */
  28465. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28466. var result = BABYLON.Ray.Zero();
  28467. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28468. return result;
  28469. };
  28470. /**
  28471. * Creates a ray that can be used to pick in the scene
  28472. * @param x defines the x coordinate of the origin (on-screen)
  28473. * @param y defines the y coordinate of the origin (on-screen)
  28474. * @param result defines the ray where to store the picking ray
  28475. * @param camera defines the camera to use for the picking
  28476. * @returns the current scene
  28477. */
  28478. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28479. if (!BABYLON.PickingInfo) {
  28480. return this;
  28481. }
  28482. var engine = this._engine;
  28483. if (!camera) {
  28484. if (!this.activeCamera)
  28485. throw new Error("Active camera not set");
  28486. camera = this.activeCamera;
  28487. }
  28488. var cameraViewport = camera.viewport;
  28489. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28490. var identity = BABYLON.Matrix.Identity();
  28491. // Moving coordinates to local viewport world
  28492. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28493. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28494. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28495. return this;
  28496. };
  28497. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28498. if (!BABYLON.PickingInfo) {
  28499. return null;
  28500. }
  28501. var pickingInfo = null;
  28502. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28503. var mesh = this.meshes[meshIndex];
  28504. if (predicate) {
  28505. if (!predicate(mesh)) {
  28506. continue;
  28507. }
  28508. }
  28509. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28510. continue;
  28511. }
  28512. var world = mesh.getWorldMatrix();
  28513. var ray = rayFunction(world);
  28514. var result = mesh.intersects(ray, fastCheck);
  28515. if (!result || !result.hit)
  28516. continue;
  28517. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28518. continue;
  28519. pickingInfo = result;
  28520. if (fastCheck) {
  28521. break;
  28522. }
  28523. }
  28524. return pickingInfo || new BABYLON.PickingInfo();
  28525. };
  28526. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28527. if (!BABYLON.PickingInfo) {
  28528. return null;
  28529. }
  28530. var pickingInfos = new Array();
  28531. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28532. var mesh = this.meshes[meshIndex];
  28533. if (predicate) {
  28534. if (!predicate(mesh)) {
  28535. continue;
  28536. }
  28537. }
  28538. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28539. continue;
  28540. }
  28541. var world = mesh.getWorldMatrix();
  28542. var ray = rayFunction(world);
  28543. var result = mesh.intersects(ray, false);
  28544. if (!result || !result.hit)
  28545. continue;
  28546. pickingInfos.push(result);
  28547. }
  28548. return pickingInfos;
  28549. };
  28550. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28551. if (!BABYLON.PickingInfo) {
  28552. return null;
  28553. }
  28554. var pickingInfo = null;
  28555. if (!camera) {
  28556. if (!this.activeCamera) {
  28557. return null;
  28558. }
  28559. camera = this.activeCamera;
  28560. }
  28561. if (this.spriteManagers.length > 0) {
  28562. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28563. var spriteManager = this.spriteManagers[spriteIndex];
  28564. if (!spriteManager.isPickable) {
  28565. continue;
  28566. }
  28567. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28568. if (!result || !result.hit)
  28569. continue;
  28570. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28571. continue;
  28572. pickingInfo = result;
  28573. if (fastCheck) {
  28574. break;
  28575. }
  28576. }
  28577. }
  28578. return pickingInfo || new BABYLON.PickingInfo();
  28579. };
  28580. /** Launch a ray to try to pick a mesh in the scene
  28581. * @param x position on screen
  28582. * @param y position on screen
  28583. * @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
  28584. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28585. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28586. * @returns a PickingInfo
  28587. */
  28588. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28589. var _this = this;
  28590. if (!BABYLON.PickingInfo) {
  28591. return null;
  28592. }
  28593. return this._internalPick(function (world) {
  28594. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28595. return _this._tempPickingRay;
  28596. }, predicate, fastCheck);
  28597. };
  28598. /** Launch a ray to try to pick a sprite in the scene
  28599. * @param x position on screen
  28600. * @param y position on screen
  28601. * @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
  28602. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28603. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28604. * @returns a PickingInfo
  28605. */
  28606. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28607. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28608. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28609. };
  28610. /** Use the given ray to pick a mesh in the scene
  28611. * @param ray The ray to use to pick meshes
  28612. * @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
  28613. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28614. * @returns a PickingInfo
  28615. */
  28616. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28617. var _this = this;
  28618. var result = this._internalPick(function (world) {
  28619. if (!_this._pickWithRayInverseMatrix) {
  28620. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28621. }
  28622. world.invertToRef(_this._pickWithRayInverseMatrix);
  28623. if (!_this._cachedRayForTransform) {
  28624. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28625. }
  28626. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28627. return _this._cachedRayForTransform;
  28628. }, predicate, fastCheck);
  28629. if (result) {
  28630. result.ray = ray;
  28631. }
  28632. return result;
  28633. };
  28634. /**
  28635. * Launch a ray to try to pick a mesh in the scene
  28636. * @param x X position on screen
  28637. * @param y Y position on screen
  28638. * @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
  28639. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28640. * @returns an array of PickingInfo
  28641. */
  28642. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28643. var _this = this;
  28644. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28645. };
  28646. /**
  28647. * Launch a ray to try to pick a mesh in the scene
  28648. * @param ray Ray to use
  28649. * @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
  28650. * @returns an array of PickingInfo
  28651. */
  28652. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28653. var _this = this;
  28654. return this._internalMultiPick(function (world) {
  28655. if (!_this._pickWithRayInverseMatrix) {
  28656. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28657. }
  28658. world.invertToRef(_this._pickWithRayInverseMatrix);
  28659. if (!_this._cachedRayForTransform) {
  28660. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28661. }
  28662. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28663. return _this._cachedRayForTransform;
  28664. }, predicate);
  28665. };
  28666. /**
  28667. * Force the value of meshUnderPointer
  28668. * @param mesh defines the mesh to use
  28669. */
  28670. Scene.prototype.setPointerOverMesh = function (mesh) {
  28671. if (this._pointerOverMesh === mesh) {
  28672. return;
  28673. }
  28674. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28675. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28676. }
  28677. this._pointerOverMesh = mesh;
  28678. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28679. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28680. }
  28681. };
  28682. /**
  28683. * Gets the mesh under the pointer
  28684. * @returns a Mesh or null if no mesh is under the pointer
  28685. */
  28686. Scene.prototype.getPointerOverMesh = function () {
  28687. return this._pointerOverMesh;
  28688. };
  28689. /**
  28690. * Force the sprite under the pointer
  28691. * @param sprite defines the sprite to use
  28692. */
  28693. Scene.prototype.setPointerOverSprite = function (sprite) {
  28694. if (this._pointerOverSprite === sprite) {
  28695. return;
  28696. }
  28697. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28698. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28699. }
  28700. this._pointerOverSprite = sprite;
  28701. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28702. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28703. }
  28704. };
  28705. /**
  28706. * Gets the sprite under the pointer
  28707. * @returns a Sprite or null if no sprite is under the pointer
  28708. */
  28709. Scene.prototype.getPointerOverSprite = function () {
  28710. return this._pointerOverSprite;
  28711. };
  28712. // Physics
  28713. /**
  28714. * Gets the current physics engine
  28715. * @returns a PhysicsEngine or null if none attached
  28716. */
  28717. Scene.prototype.getPhysicsEngine = function () {
  28718. return this._physicsEngine;
  28719. };
  28720. /**
  28721. * Enables physics to the current scene
  28722. * @param gravity defines the scene's gravity for the physics engine
  28723. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28724. * @return a boolean indicating if the physics engine was initialized
  28725. */
  28726. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28727. if (gravity === void 0) { gravity = null; }
  28728. if (this._physicsEngine) {
  28729. return true;
  28730. }
  28731. try {
  28732. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28733. return true;
  28734. }
  28735. catch (e) {
  28736. BABYLON.Tools.Error(e.message);
  28737. return false;
  28738. }
  28739. };
  28740. /**
  28741. * Disables and disposes the physics engine associated with the scene
  28742. */
  28743. Scene.prototype.disablePhysicsEngine = function () {
  28744. if (!this._physicsEngine) {
  28745. return;
  28746. }
  28747. this._physicsEngine.dispose();
  28748. this._physicsEngine = null;
  28749. };
  28750. /**
  28751. * Gets a boolean indicating if there is an active physics engine
  28752. * @returns a boolean indicating if there is an active physics engine
  28753. */
  28754. Scene.prototype.isPhysicsEnabled = function () {
  28755. return this._physicsEngine !== undefined;
  28756. };
  28757. /**
  28758. * Deletes a physics compound impostor
  28759. * @param compound defines the compound to delete
  28760. */
  28761. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28762. var mesh = compound.parts[0].mesh;
  28763. if (mesh.physicsImpostor) {
  28764. mesh.physicsImpostor.dispose( /*true*/);
  28765. mesh.physicsImpostor = null;
  28766. }
  28767. };
  28768. // Misc.
  28769. /** @hidden */
  28770. Scene.prototype._rebuildGeometries = function () {
  28771. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28772. var geometry = _a[_i];
  28773. geometry._rebuild();
  28774. }
  28775. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28776. var mesh = _c[_b];
  28777. mesh._rebuild();
  28778. }
  28779. if (this.postProcessManager) {
  28780. this.postProcessManager._rebuild();
  28781. }
  28782. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28783. var layer = _e[_d];
  28784. layer._rebuild();
  28785. }
  28786. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28787. var effectLayer = _g[_f];
  28788. effectLayer._rebuild();
  28789. }
  28790. if (this._boundingBoxRenderer) {
  28791. this._boundingBoxRenderer._rebuild();
  28792. }
  28793. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28794. var system = _j[_h];
  28795. system.rebuild();
  28796. }
  28797. if (this._postProcessRenderPipelineManager) {
  28798. this._postProcessRenderPipelineManager._rebuild();
  28799. }
  28800. };
  28801. /** @hidden */
  28802. Scene.prototype._rebuildTextures = function () {
  28803. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28804. var texture = _a[_i];
  28805. texture._rebuild();
  28806. }
  28807. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28808. };
  28809. /**
  28810. * Creates a default light for the scene.
  28811. * @param replace Whether to replace the existing lights in the scene.
  28812. */
  28813. Scene.prototype.createDefaultLight = function (replace) {
  28814. if (replace === void 0) { replace = false; }
  28815. // Dispose existing light in replace mode.
  28816. if (replace) {
  28817. if (this.lights) {
  28818. for (var i = 0; i < this.lights.length; i++) {
  28819. this.lights[i].dispose();
  28820. }
  28821. }
  28822. }
  28823. // Light
  28824. if (this.lights.length === 0) {
  28825. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28826. }
  28827. };
  28828. /**
  28829. * Creates a default camera for the scene.
  28830. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28831. * @param replace Whether to replace the existing active camera in the scene.
  28832. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28833. */
  28834. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28835. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28836. if (replace === void 0) { replace = false; }
  28837. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28838. // Dispose existing camera in replace mode.
  28839. if (replace) {
  28840. if (this.activeCamera) {
  28841. this.activeCamera.dispose();
  28842. this.activeCamera = null;
  28843. }
  28844. }
  28845. // Camera
  28846. if (!this.activeCamera) {
  28847. var worldExtends = this.getWorldExtends();
  28848. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28849. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28850. var camera;
  28851. var radius = worldSize.length() * 1.5;
  28852. // empty scene scenario!
  28853. if (!isFinite(radius)) {
  28854. radius = 1;
  28855. worldCenter.copyFromFloats(0, 0, 0);
  28856. }
  28857. if (createArcRotateCamera) {
  28858. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28859. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28860. arcRotateCamera.wheelPrecision = 100 / radius;
  28861. camera = arcRotateCamera;
  28862. }
  28863. else {
  28864. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28865. freeCamera.setTarget(worldCenter);
  28866. camera = freeCamera;
  28867. }
  28868. camera.minZ = radius * 0.01;
  28869. camera.maxZ = radius * 1000;
  28870. camera.speed = radius * 0.2;
  28871. this.activeCamera = camera;
  28872. var canvas = this.getEngine().getRenderingCanvas();
  28873. if (attachCameraControls && canvas) {
  28874. camera.attachControl(canvas);
  28875. }
  28876. }
  28877. };
  28878. /**
  28879. * Creates a default camera and a default light
  28880. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28881. * @param replace defines if the camera and/or light will replace the existing ones
  28882. * @param attachCameraControls defines if attachControl will be called on the new camera
  28883. */
  28884. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28885. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28886. if (replace === void 0) { replace = false; }
  28887. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28888. this.createDefaultLight(replace);
  28889. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28890. };
  28891. /**
  28892. * Creates a new sky box
  28893. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28894. * @param environmentTexture defines the texture to use as environment texture
  28895. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28896. * @param scale defines the overall scale of the skybox
  28897. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28898. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28899. * @returns a new mesh holding the sky box
  28900. */
  28901. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28902. if (pbr === void 0) { pbr = false; }
  28903. if (scale === void 0) { scale = 1000; }
  28904. if (blur === void 0) { blur = 0; }
  28905. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28906. if (!environmentTexture) {
  28907. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28908. return null;
  28909. }
  28910. if (setGlobalEnvTexture) {
  28911. if (environmentTexture) {
  28912. this.environmentTexture = environmentTexture;
  28913. }
  28914. }
  28915. // Skybox
  28916. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28917. if (pbr) {
  28918. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28919. hdrSkyboxMaterial.backFaceCulling = false;
  28920. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28921. if (hdrSkyboxMaterial.reflectionTexture) {
  28922. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28923. }
  28924. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28925. hdrSkyboxMaterial.disableLighting = true;
  28926. hdrSkyboxMaterial.twoSidedLighting = true;
  28927. hdrSkybox.infiniteDistance = true;
  28928. hdrSkybox.material = hdrSkyboxMaterial;
  28929. }
  28930. else {
  28931. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28932. skyboxMaterial.backFaceCulling = false;
  28933. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28934. if (skyboxMaterial.reflectionTexture) {
  28935. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28936. }
  28937. skyboxMaterial.disableLighting = true;
  28938. hdrSkybox.infiniteDistance = true;
  28939. hdrSkybox.material = skyboxMaterial;
  28940. }
  28941. return hdrSkybox;
  28942. };
  28943. /**
  28944. * Creates a new environment
  28945. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28946. * @param options defines the options you can use to configure the environment
  28947. * @returns the new EnvironmentHelper
  28948. */
  28949. Scene.prototype.createDefaultEnvironment = function (options) {
  28950. if (BABYLON.EnvironmentHelper) {
  28951. return new BABYLON.EnvironmentHelper(options, this);
  28952. }
  28953. return null;
  28954. };
  28955. /**
  28956. * Creates a new VREXperienceHelper
  28957. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28958. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28959. * @returns a new VREXperienceHelper
  28960. */
  28961. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28962. if (webVROptions === void 0) { webVROptions = {}; }
  28963. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28964. };
  28965. // Tags
  28966. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28967. if (tagsQuery === undefined) {
  28968. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28969. return list;
  28970. }
  28971. var listByTags = [];
  28972. forEach = forEach || (function (item) { return; });
  28973. for (var i in list) {
  28974. var item = list[i];
  28975. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28976. listByTags.push(item);
  28977. forEach(item);
  28978. }
  28979. }
  28980. return listByTags;
  28981. };
  28982. /**
  28983. * Get a list of meshes by tags
  28984. * @param tagsQuery defines the tags query to use
  28985. * @param forEach defines a predicate used to filter results
  28986. * @returns an array of Mesh
  28987. */
  28988. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28989. return this._getByTags(this.meshes, tagsQuery, forEach);
  28990. };
  28991. /**
  28992. * Get a list of cameras by tags
  28993. * @param tagsQuery defines the tags query to use
  28994. * @param forEach defines a predicate used to filter results
  28995. * @returns an array of Camera
  28996. */
  28997. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28998. return this._getByTags(this.cameras, tagsQuery, forEach);
  28999. };
  29000. /**
  29001. * Get a list of lights by tags
  29002. * @param tagsQuery defines the tags query to use
  29003. * @param forEach defines a predicate used to filter results
  29004. * @returns an array of Light
  29005. */
  29006. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29007. return this._getByTags(this.lights, tagsQuery, forEach);
  29008. };
  29009. /**
  29010. * Get a list of materials by tags
  29011. * @param tagsQuery defines the tags query to use
  29012. * @param forEach defines a predicate used to filter results
  29013. * @returns an array of Material
  29014. */
  29015. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29016. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29017. };
  29018. /**
  29019. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29020. * This allowed control for front to back rendering or reversly depending of the special needs.
  29021. *
  29022. * @param renderingGroupId The rendering group id corresponding to its index
  29023. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29024. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29025. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29026. */
  29027. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29028. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29029. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29030. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29031. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29032. };
  29033. /**
  29034. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29035. *
  29036. * @param renderingGroupId The rendering group id corresponding to its index
  29037. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29038. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29039. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29040. */
  29041. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29042. if (depth === void 0) { depth = true; }
  29043. if (stencil === void 0) { stencil = true; }
  29044. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29045. };
  29046. /**
  29047. * Will flag all materials as dirty to trigger new shader compilation
  29048. * @param flag defines the flag used to specify which material part must be marked as dirty
  29049. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29050. */
  29051. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29052. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29053. var material = _a[_i];
  29054. if (predicate && !predicate(material)) {
  29055. continue;
  29056. }
  29057. material.markAsDirty(flag);
  29058. }
  29059. };
  29060. /** @hidden */
  29061. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29062. var _this = this;
  29063. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29064. this._activeRequests.push(request);
  29065. request.onCompleteObservable.add(function (request) {
  29066. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29067. });
  29068. return request;
  29069. };
  29070. /** @hidden */
  29071. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29072. var _this = this;
  29073. return new Promise(function (resolve, reject) {
  29074. _this._loadFile(url, function (data) {
  29075. resolve(data);
  29076. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29077. reject(exception);
  29078. });
  29079. });
  29080. };
  29081. // Statics
  29082. Scene._FOGMODE_NONE = 0;
  29083. Scene._FOGMODE_EXP = 1;
  29084. Scene._FOGMODE_EXP2 = 2;
  29085. Scene._FOGMODE_LINEAR = 3;
  29086. Scene._uniqueIdCounter = 0;
  29087. /**
  29088. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29089. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29090. */
  29091. Scene.MinDeltaTime = 1.0;
  29092. /**
  29093. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29094. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29095. */
  29096. Scene.MaxDeltaTime = 1000.0;
  29097. /** The distance in pixel that you have to move to prevent some events */
  29098. Scene.DragMovementThreshold = 10; // in pixels
  29099. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29100. Scene.LongPressDelay = 500; // in milliseconds
  29101. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29102. Scene.DoubleClickDelay = 300; // in milliseconds
  29103. /** If you need to check double click without raising a single click at first click, enable this flag */
  29104. Scene.ExclusiveDoubleClickMode = false;
  29105. return Scene;
  29106. }());
  29107. BABYLON.Scene = Scene;
  29108. })(BABYLON || (BABYLON = {}));
  29109. //# sourceMappingURL=babylon.scene.js.map
  29110. var BABYLON;
  29111. (function (BABYLON) {
  29112. /**
  29113. * Set of assets to keep when moving a scene into an asset container.
  29114. */
  29115. var KeepAssets = /** @class */ (function () {
  29116. function KeepAssets() {
  29117. /**
  29118. * Cameras to keep.
  29119. */
  29120. this.cameras = new Array();
  29121. /**
  29122. * Lights to keep.
  29123. */
  29124. this.lights = new Array();
  29125. /**
  29126. * Meshes to keep.
  29127. */
  29128. this.meshes = new Array();
  29129. /**
  29130. * Skeletons to keep.
  29131. */
  29132. this.skeletons = new Array();
  29133. /**
  29134. * ParticleSystems to keep.
  29135. */
  29136. this.particleSystems = new Array();
  29137. /**
  29138. * Animations to keep.
  29139. */
  29140. this.animations = new Array();
  29141. /**
  29142. * AnimationGroups to keep.
  29143. */
  29144. this.animationGroups = new Array();
  29145. /**
  29146. * MultiMaterials to keep.
  29147. */
  29148. this.multiMaterials = new Array();
  29149. /**
  29150. * Materials to keep.
  29151. */
  29152. this.materials = new Array();
  29153. /**
  29154. * MorphTargetManagers to keep.
  29155. */
  29156. this.morphTargetManagers = new Array();
  29157. /**
  29158. * Geometries to keep.
  29159. */
  29160. this.geometries = new Array();
  29161. /**
  29162. * TransformNodes to keep.
  29163. */
  29164. this.transformNodes = new Array();
  29165. /**
  29166. * LensFlareSystems to keep.
  29167. */
  29168. this.lensFlareSystems = new Array();
  29169. /**
  29170. * ShadowGenerators to keep.
  29171. */
  29172. this.shadowGenerators = new Array();
  29173. /**
  29174. * ActionManagers to keep.
  29175. */
  29176. this.actionManagers = new Array();
  29177. /**
  29178. * Sounds to keep.
  29179. */
  29180. this.sounds = new Array();
  29181. /**
  29182. * Textures to keep.
  29183. */
  29184. this.textures = new Array();
  29185. /**
  29186. * Effect layers to keep.
  29187. */
  29188. this.effectLayers = new Array();
  29189. }
  29190. return KeepAssets;
  29191. }());
  29192. BABYLON.KeepAssets = KeepAssets;
  29193. /**
  29194. * Container with a set of assets that can be added or removed from a scene.
  29195. */
  29196. var AssetContainer = /** @class */ (function () {
  29197. /**
  29198. * Instantiates an AssetContainer.
  29199. * @param scene The scene the AssetContainer belongs to.
  29200. */
  29201. function AssetContainer(scene) {
  29202. // Objects
  29203. /**
  29204. * Cameras populated in the container.
  29205. */
  29206. this.cameras = new Array();
  29207. /**
  29208. * Lights populated in the container.
  29209. */
  29210. this.lights = new Array();
  29211. /**
  29212. * Meshes populated in the container.
  29213. */
  29214. this.meshes = new Array();
  29215. /**
  29216. * Skeletons populated in the container.
  29217. */
  29218. this.skeletons = new Array();
  29219. /**
  29220. * ParticleSystems populated in the container.
  29221. */
  29222. this.particleSystems = new Array();
  29223. /**
  29224. * Animations populated in the container.
  29225. */
  29226. this.animations = new Array();
  29227. /**
  29228. * AnimationGroups populated in the container.
  29229. */
  29230. this.animationGroups = new Array();
  29231. /**
  29232. * MultiMaterials populated in the container.
  29233. */
  29234. this.multiMaterials = new Array();
  29235. /**
  29236. * Materials populated in the container.
  29237. */
  29238. this.materials = new Array();
  29239. /**
  29240. * MorphTargetManagers populated in the container.
  29241. */
  29242. this.morphTargetManagers = new Array();
  29243. /**
  29244. * Geometries populated in the container.
  29245. */
  29246. this.geometries = new Array();
  29247. /**
  29248. * TransformNodes populated in the container.
  29249. */
  29250. this.transformNodes = new Array();
  29251. /**
  29252. * LensFlareSystems populated in the container.
  29253. */
  29254. this.lensFlareSystems = new Array();
  29255. /**
  29256. * ShadowGenerators populated in the container.
  29257. */
  29258. this.shadowGenerators = new Array();
  29259. /**
  29260. * ActionManagers populated in the container.
  29261. */
  29262. this.actionManagers = new Array();
  29263. /**
  29264. * Sounds populated in the container.
  29265. */
  29266. this.sounds = new Array();
  29267. /**
  29268. * Textures populated in the container.
  29269. */
  29270. this.textures = new Array();
  29271. /**
  29272. * Effect layers populated in the container.
  29273. */
  29274. this.effectLayers = new Array();
  29275. this.scene = scene;
  29276. }
  29277. /**
  29278. * Adds all the assets from the container to the scene.
  29279. */
  29280. AssetContainer.prototype.addAllToScene = function () {
  29281. var _this = this;
  29282. this.cameras.forEach(function (o) {
  29283. _this.scene.addCamera(o);
  29284. });
  29285. this.lights.forEach(function (o) {
  29286. _this.scene.addLight(o);
  29287. });
  29288. this.meshes.forEach(function (o) {
  29289. _this.scene.addMesh(o);
  29290. });
  29291. this.skeletons.forEach(function (o) {
  29292. _this.scene.addSkeleton(o);
  29293. });
  29294. this.particleSystems.forEach(function (o) {
  29295. _this.scene.addParticleSystem(o);
  29296. });
  29297. this.animations.forEach(function (o) {
  29298. _this.scene.addAnimation(o);
  29299. });
  29300. this.animationGroups.forEach(function (o) {
  29301. _this.scene.addAnimationGroup(o);
  29302. });
  29303. this.multiMaterials.forEach(function (o) {
  29304. _this.scene.addMultiMaterial(o);
  29305. });
  29306. this.materials.forEach(function (o) {
  29307. _this.scene.addMaterial(o);
  29308. });
  29309. this.morphTargetManagers.forEach(function (o) {
  29310. _this.scene.addMorphTargetManager(o);
  29311. });
  29312. this.geometries.forEach(function (o) {
  29313. _this.scene.addGeometry(o);
  29314. });
  29315. this.transformNodes.forEach(function (o) {
  29316. _this.scene.addTransformNode(o);
  29317. });
  29318. this.lensFlareSystems.forEach(function (o) {
  29319. _this.scene.addLensFlareSystem(o);
  29320. });
  29321. this.actionManagers.forEach(function (o) {
  29322. _this.scene.addActionManager(o);
  29323. });
  29324. this.sounds.forEach(function (o) {
  29325. o.play();
  29326. o.autoplay = true;
  29327. _this.scene.mainSoundTrack.AddSound(o);
  29328. });
  29329. this.textures.forEach(function (o) {
  29330. _this.scene.addTexture(o);
  29331. });
  29332. this.effectLayers.forEach(function (o) {
  29333. _this.scene.addEffectLayer(o);
  29334. });
  29335. };
  29336. /**
  29337. * Removes all the assets in the container from the scene
  29338. */
  29339. AssetContainer.prototype.removeAllFromScene = function () {
  29340. var _this = this;
  29341. this.cameras.forEach(function (o) {
  29342. _this.scene.removeCamera(o);
  29343. });
  29344. this.lights.forEach(function (o) {
  29345. _this.scene.removeLight(o);
  29346. });
  29347. this.meshes.forEach(function (o) {
  29348. _this.scene.removeMesh(o);
  29349. });
  29350. this.skeletons.forEach(function (o) {
  29351. _this.scene.removeSkeleton(o);
  29352. });
  29353. this.particleSystems.forEach(function (o) {
  29354. _this.scene.removeParticleSystem(o);
  29355. });
  29356. this.animations.forEach(function (o) {
  29357. _this.scene.removeAnimation(o);
  29358. });
  29359. this.animationGroups.forEach(function (o) {
  29360. _this.scene.removeAnimationGroup(o);
  29361. });
  29362. this.multiMaterials.forEach(function (o) {
  29363. _this.scene.removeMultiMaterial(o);
  29364. });
  29365. this.materials.forEach(function (o) {
  29366. _this.scene.removeMaterial(o);
  29367. });
  29368. this.morphTargetManagers.forEach(function (o) {
  29369. _this.scene.removeMorphTargetManager(o);
  29370. });
  29371. this.geometries.forEach(function (o) {
  29372. _this.scene.removeGeometry(o);
  29373. });
  29374. this.transformNodes.forEach(function (o) {
  29375. _this.scene.removeTransformNode(o);
  29376. });
  29377. this.lensFlareSystems.forEach(function (o) {
  29378. _this.scene.removeLensFlareSystem(o);
  29379. });
  29380. this.actionManagers.forEach(function (o) {
  29381. _this.scene.removeActionManager(o);
  29382. });
  29383. this.sounds.forEach(function (o) {
  29384. o.stop();
  29385. o.autoplay = false;
  29386. _this.scene.mainSoundTrack.RemoveSound(o);
  29387. });
  29388. this.textures.forEach(function (o) {
  29389. _this.scene.removeTexture(o);
  29390. });
  29391. this.effectLayers.forEach(function (o) {
  29392. _this.scene.removeEffectLayer(o);
  29393. });
  29394. };
  29395. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29396. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29397. var asset = sourceAssets_1[_i];
  29398. var move = true;
  29399. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29400. var keepAsset = keepAssets_1[_a];
  29401. if (asset === keepAsset) {
  29402. move = false;
  29403. break;
  29404. }
  29405. }
  29406. if (move) {
  29407. targetAssets.push(asset);
  29408. }
  29409. }
  29410. };
  29411. /**
  29412. * Removes all the assets contained in the scene and adds them to the container.
  29413. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29414. */
  29415. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29416. if (keepAssets === undefined) {
  29417. keepAssets = new KeepAssets();
  29418. }
  29419. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29420. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29421. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29422. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29423. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29424. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29425. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29426. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29427. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29428. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29429. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29430. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29431. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29432. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29433. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29434. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29435. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29436. this.removeAllFromScene();
  29437. };
  29438. /**
  29439. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29440. * @returns the root mesh
  29441. */
  29442. AssetContainer.prototype.createRootMesh = function () {
  29443. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29444. this.meshes.forEach(function (m) {
  29445. if (!m.parent) {
  29446. rootMesh.addChild(m);
  29447. }
  29448. });
  29449. this.meshes.unshift(rootMesh);
  29450. return rootMesh;
  29451. };
  29452. return AssetContainer;
  29453. }());
  29454. BABYLON.AssetContainer = AssetContainer;
  29455. })(BABYLON || (BABYLON = {}));
  29456. //# sourceMappingURL=babylon.assetContainer.js.map
  29457. var BABYLON;
  29458. (function (BABYLON) {
  29459. var Buffer = /** @class */ (function () {
  29460. /**
  29461. * Constructor
  29462. * @param engine the engine
  29463. * @param data the data to use for this buffer
  29464. * @param updatable whether the data is updatable
  29465. * @param stride the stride (optional)
  29466. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29467. * @param instanced whether the buffer is instanced (optional)
  29468. * @param useBytes set to true if the stride in in bytes (optional)
  29469. */
  29470. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29471. if (stride === void 0) { stride = 0; }
  29472. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29473. if (instanced === void 0) { instanced = false; }
  29474. if (useBytes === void 0) { useBytes = false; }
  29475. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29476. this._engine = engine.getScene().getEngine();
  29477. }
  29478. else {
  29479. this._engine = engine;
  29480. }
  29481. this._updatable = updatable;
  29482. this._instanced = instanced;
  29483. this._data = data;
  29484. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29485. if (!postponeInternalCreation) { // by default
  29486. this.create();
  29487. }
  29488. }
  29489. /**
  29490. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29491. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29492. * @param offset defines offset in the buffer (0 by default)
  29493. * @param size defines the size in floats of attributes (position is 3 for instance)
  29494. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29495. * @param instanced defines if the vertex buffer contains indexed data
  29496. * @param useBytes defines if the offset and stride are in bytes
  29497. * @returns the new vertex buffer
  29498. */
  29499. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29500. if (useBytes === void 0) { useBytes = false; }
  29501. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29502. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29503. // a lot of these parameters are ignored as they are overriden by the buffer
  29504. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29505. };
  29506. // Properties
  29507. Buffer.prototype.isUpdatable = function () {
  29508. return this._updatable;
  29509. };
  29510. Buffer.prototype.getData = function () {
  29511. return this._data;
  29512. };
  29513. Buffer.prototype.getBuffer = function () {
  29514. return this._buffer;
  29515. };
  29516. /**
  29517. * Gets the stride in float32 units (i.e. byte stride / 4).
  29518. * May not be an integer if the byte stride is not divisible by 4.
  29519. * DEPRECATED. Use byteStride instead.
  29520. * @returns the stride in float32 units
  29521. */
  29522. Buffer.prototype.getStrideSize = function () {
  29523. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29524. };
  29525. // Methods
  29526. Buffer.prototype.create = function (data) {
  29527. if (data === void 0) { data = null; }
  29528. if (!data && this._buffer) {
  29529. return; // nothing to do
  29530. }
  29531. data = data || this._data;
  29532. if (!data) {
  29533. return;
  29534. }
  29535. if (!this._buffer) { // create buffer
  29536. if (this._updatable) {
  29537. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29538. this._data = data;
  29539. }
  29540. else {
  29541. this._buffer = this._engine.createVertexBuffer(data);
  29542. }
  29543. }
  29544. else if (this._updatable) { // update buffer
  29545. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29546. this._data = data;
  29547. }
  29548. };
  29549. Buffer.prototype._rebuild = function () {
  29550. this._buffer = null;
  29551. this.create(this._data);
  29552. };
  29553. Buffer.prototype.update = function (data) {
  29554. this.create(data);
  29555. };
  29556. /**
  29557. * Updates the data directly.
  29558. * @param data the new data
  29559. * @param offset the new offset
  29560. * @param vertexCount the vertex count (optional)
  29561. * @param useBytes set to true if the offset is in bytes
  29562. */
  29563. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29564. if (useBytes === void 0) { useBytes = false; }
  29565. if (!this._buffer) {
  29566. return;
  29567. }
  29568. if (this._updatable) { // update buffer
  29569. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29570. this._data = null;
  29571. }
  29572. };
  29573. Buffer.prototype.dispose = function () {
  29574. if (!this._buffer) {
  29575. return;
  29576. }
  29577. if (this._engine._releaseBuffer(this._buffer)) {
  29578. this._buffer = null;
  29579. }
  29580. };
  29581. return Buffer;
  29582. }());
  29583. BABYLON.Buffer = Buffer;
  29584. })(BABYLON || (BABYLON = {}));
  29585. //# sourceMappingURL=babylon.buffer.js.map
  29586. var BABYLON;
  29587. (function (BABYLON) {
  29588. var VertexBuffer = /** @class */ (function () {
  29589. /**
  29590. * Constructor
  29591. * @param engine the engine
  29592. * @param data the data to use for this vertex buffer
  29593. * @param kind the vertex buffer kind
  29594. * @param updatable whether the data is updatable
  29595. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29596. * @param stride the stride (optional)
  29597. * @param instanced whether the buffer is instanced (optional)
  29598. * @param offset the offset of the data (optional)
  29599. * @param size the number of components (optional)
  29600. * @param type the type of the component (optional)
  29601. * @param normalized whether the data contains normalized data (optional)
  29602. * @param useBytes set to true if stride and offset are in bytes (optional)
  29603. */
  29604. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29605. if (normalized === void 0) { normalized = false; }
  29606. if (useBytes === void 0) { useBytes = false; }
  29607. if (data instanceof BABYLON.Buffer) {
  29608. this._buffer = data;
  29609. this._ownsBuffer = false;
  29610. }
  29611. else {
  29612. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29613. this._ownsBuffer = true;
  29614. }
  29615. this._kind = kind;
  29616. if (type == undefined) {
  29617. var data_1 = this.getData();
  29618. this.type = VertexBuffer.FLOAT;
  29619. if (data_1 instanceof Int8Array)
  29620. this.type = VertexBuffer.BYTE;
  29621. else if (data_1 instanceof Uint8Array)
  29622. this.type = VertexBuffer.UNSIGNED_BYTE;
  29623. else if (data_1 instanceof Int16Array)
  29624. this.type = VertexBuffer.SHORT;
  29625. else if (data_1 instanceof Uint16Array)
  29626. this.type = VertexBuffer.UNSIGNED_SHORT;
  29627. else if (data_1 instanceof Int32Array)
  29628. this.type = VertexBuffer.INT;
  29629. else if (data_1 instanceof Uint32Array)
  29630. this.type = VertexBuffer.UNSIGNED_INT;
  29631. }
  29632. else {
  29633. this.type = type;
  29634. }
  29635. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29636. if (useBytes) {
  29637. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29638. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29639. this.byteOffset = offset || 0;
  29640. }
  29641. else {
  29642. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29643. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29644. this.byteOffset = (offset || 0) * typeByteLength;
  29645. }
  29646. this.normalized = normalized;
  29647. this._instanced = instanced !== undefined ? instanced : false;
  29648. this._instanceDivisor = instanced ? 1 : 0;
  29649. }
  29650. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29651. /**
  29652. * Gets or sets the instance divisor when in instanced mode
  29653. */
  29654. get: function () {
  29655. return this._instanceDivisor;
  29656. },
  29657. set: function (value) {
  29658. this._instanceDivisor = value;
  29659. if (value == 0) {
  29660. this._instanced = false;
  29661. }
  29662. else {
  29663. this._instanced = true;
  29664. }
  29665. },
  29666. enumerable: true,
  29667. configurable: true
  29668. });
  29669. VertexBuffer.prototype._rebuild = function () {
  29670. if (!this._buffer) {
  29671. return;
  29672. }
  29673. this._buffer._rebuild();
  29674. };
  29675. /**
  29676. * Returns the kind of the VertexBuffer (string).
  29677. */
  29678. VertexBuffer.prototype.getKind = function () {
  29679. return this._kind;
  29680. };
  29681. // Properties
  29682. /**
  29683. * Boolean : is the VertexBuffer updatable ?
  29684. */
  29685. VertexBuffer.prototype.isUpdatable = function () {
  29686. return this._buffer.isUpdatable();
  29687. };
  29688. /**
  29689. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29690. */
  29691. VertexBuffer.prototype.getData = function () {
  29692. return this._buffer.getData();
  29693. };
  29694. /**
  29695. * Returns the WebGLBuffer associated to the VertexBuffer.
  29696. */
  29697. VertexBuffer.prototype.getBuffer = function () {
  29698. return this._buffer.getBuffer();
  29699. };
  29700. /**
  29701. * Returns the stride as a multiple of the type byte length.
  29702. * DEPRECATED. Use byteStride instead.
  29703. */
  29704. VertexBuffer.prototype.getStrideSize = function () {
  29705. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29706. };
  29707. /**
  29708. * Returns the offset as a multiple of the type byte length.
  29709. * DEPRECATED. Use byteOffset instead.
  29710. */
  29711. VertexBuffer.prototype.getOffset = function () {
  29712. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29713. };
  29714. /**
  29715. * Returns the number of components per vertex attribute (integer).
  29716. */
  29717. VertexBuffer.prototype.getSize = function () {
  29718. return this._size;
  29719. };
  29720. /**
  29721. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29722. */
  29723. VertexBuffer.prototype.getIsInstanced = function () {
  29724. return this._instanced;
  29725. };
  29726. /**
  29727. * Returns the instancing divisor, zero for non-instanced (integer).
  29728. */
  29729. VertexBuffer.prototype.getInstanceDivisor = function () {
  29730. return this._instanceDivisor;
  29731. };
  29732. // Methods
  29733. /**
  29734. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29735. * Returns the created WebGLBuffer.
  29736. */
  29737. VertexBuffer.prototype.create = function (data) {
  29738. return this._buffer.create(data);
  29739. };
  29740. /**
  29741. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29742. * This function will create a new buffer if the current one is not updatable
  29743. * Returns the updated WebGLBuffer.
  29744. */
  29745. VertexBuffer.prototype.update = function (data) {
  29746. return this._buffer.update(data);
  29747. };
  29748. /**
  29749. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29750. * Returns the directly updated WebGLBuffer.
  29751. * @param data the new data
  29752. * @param offset the new offset
  29753. * @param useBytes set to true if the offset is in bytes
  29754. */
  29755. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29756. if (useBytes === void 0) { useBytes = false; }
  29757. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29758. };
  29759. /**
  29760. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29761. */
  29762. VertexBuffer.prototype.dispose = function () {
  29763. if (this._ownsBuffer) {
  29764. this._buffer.dispose();
  29765. }
  29766. };
  29767. /**
  29768. * Enumerates each value of this vertex buffer as numbers.
  29769. * @param count the number of values to enumerate
  29770. * @param callback the callback function called for each value
  29771. */
  29772. VertexBuffer.prototype.forEach = function (count, callback) {
  29773. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29774. };
  29775. Object.defineProperty(VertexBuffer, "PositionKind", {
  29776. get: function () {
  29777. return VertexBuffer._PositionKind;
  29778. },
  29779. enumerable: true,
  29780. configurable: true
  29781. });
  29782. Object.defineProperty(VertexBuffer, "NormalKind", {
  29783. get: function () {
  29784. return VertexBuffer._NormalKind;
  29785. },
  29786. enumerable: true,
  29787. configurable: true
  29788. });
  29789. Object.defineProperty(VertexBuffer, "TangentKind", {
  29790. get: function () {
  29791. return VertexBuffer._TangentKind;
  29792. },
  29793. enumerable: true,
  29794. configurable: true
  29795. });
  29796. Object.defineProperty(VertexBuffer, "UVKind", {
  29797. get: function () {
  29798. return VertexBuffer._UVKind;
  29799. },
  29800. enumerable: true,
  29801. configurable: true
  29802. });
  29803. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29804. get: function () {
  29805. return VertexBuffer._UV2Kind;
  29806. },
  29807. enumerable: true,
  29808. configurable: true
  29809. });
  29810. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29811. get: function () {
  29812. return VertexBuffer._UV3Kind;
  29813. },
  29814. enumerable: true,
  29815. configurable: true
  29816. });
  29817. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29818. get: function () {
  29819. return VertexBuffer._UV4Kind;
  29820. },
  29821. enumerable: true,
  29822. configurable: true
  29823. });
  29824. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29825. get: function () {
  29826. return VertexBuffer._UV5Kind;
  29827. },
  29828. enumerable: true,
  29829. configurable: true
  29830. });
  29831. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29832. get: function () {
  29833. return VertexBuffer._UV6Kind;
  29834. },
  29835. enumerable: true,
  29836. configurable: true
  29837. });
  29838. Object.defineProperty(VertexBuffer, "ColorKind", {
  29839. get: function () {
  29840. return VertexBuffer._ColorKind;
  29841. },
  29842. enumerable: true,
  29843. configurable: true
  29844. });
  29845. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29846. get: function () {
  29847. return VertexBuffer._MatricesIndicesKind;
  29848. },
  29849. enumerable: true,
  29850. configurable: true
  29851. });
  29852. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29853. get: function () {
  29854. return VertexBuffer._MatricesWeightsKind;
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29860. get: function () {
  29861. return VertexBuffer._MatricesIndicesExtraKind;
  29862. },
  29863. enumerable: true,
  29864. configurable: true
  29865. });
  29866. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29867. get: function () {
  29868. return VertexBuffer._MatricesWeightsExtraKind;
  29869. },
  29870. enumerable: true,
  29871. configurable: true
  29872. });
  29873. /**
  29874. * Deduces the stride given a kind.
  29875. * @param kind The kind string to deduce
  29876. * @returns The deduced stride
  29877. */
  29878. VertexBuffer.DeduceStride = function (kind) {
  29879. switch (kind) {
  29880. case VertexBuffer.UVKind:
  29881. case VertexBuffer.UV2Kind:
  29882. case VertexBuffer.UV3Kind:
  29883. case VertexBuffer.UV4Kind:
  29884. case VertexBuffer.UV5Kind:
  29885. case VertexBuffer.UV6Kind:
  29886. return 2;
  29887. case VertexBuffer.NormalKind:
  29888. case VertexBuffer.PositionKind:
  29889. return 3;
  29890. case VertexBuffer.ColorKind:
  29891. case VertexBuffer.MatricesIndicesKind:
  29892. case VertexBuffer.MatricesIndicesExtraKind:
  29893. case VertexBuffer.MatricesWeightsKind:
  29894. case VertexBuffer.MatricesWeightsExtraKind:
  29895. case VertexBuffer.TangentKind:
  29896. return 4;
  29897. default:
  29898. throw new Error("Invalid kind '" + kind + "'");
  29899. }
  29900. };
  29901. /**
  29902. * Gets the byte length of the given type.
  29903. * @param type the type
  29904. * @returns the number of bytes
  29905. */
  29906. VertexBuffer.GetTypeByteLength = function (type) {
  29907. switch (type) {
  29908. case VertexBuffer.BYTE:
  29909. case VertexBuffer.UNSIGNED_BYTE:
  29910. return 1;
  29911. case VertexBuffer.SHORT:
  29912. case VertexBuffer.UNSIGNED_SHORT:
  29913. return 2;
  29914. case VertexBuffer.INT:
  29915. case VertexBuffer.FLOAT:
  29916. return 4;
  29917. default:
  29918. throw new Error("Invalid type '" + type + "'");
  29919. }
  29920. };
  29921. /**
  29922. * Enumerates each value of the given parameters as numbers.
  29923. * @param data the data to enumerate
  29924. * @param byteOffset the byte offset of the data
  29925. * @param byteStride the byte stride of the data
  29926. * @param componentCount the number of components per element
  29927. * @param componentType the type of the component
  29928. * @param count the total number of components
  29929. * @param normalized whether the data is normalized
  29930. * @param callback the callback function called for each value
  29931. */
  29932. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29933. if (data instanceof Array) {
  29934. var offset = byteOffset / 4;
  29935. var stride = byteStride / 4;
  29936. for (var index = 0; index < count; index += componentCount) {
  29937. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29938. callback(data[offset + componentIndex], index + componentIndex);
  29939. }
  29940. offset += stride;
  29941. }
  29942. }
  29943. else {
  29944. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29945. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29946. for (var index = 0; index < count; index += componentCount) {
  29947. var componentByteOffset = byteOffset;
  29948. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29949. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29950. callback(value, index + componentIndex);
  29951. componentByteOffset += componentByteLength;
  29952. }
  29953. byteOffset += byteStride;
  29954. }
  29955. }
  29956. };
  29957. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29958. switch (type) {
  29959. case VertexBuffer.BYTE: {
  29960. var value = dataView.getInt8(byteOffset);
  29961. if (normalized) {
  29962. value = Math.max(value / 127, -1);
  29963. }
  29964. return value;
  29965. }
  29966. case VertexBuffer.UNSIGNED_BYTE: {
  29967. var value = dataView.getUint8(byteOffset);
  29968. if (normalized) {
  29969. value = value / 255;
  29970. }
  29971. return value;
  29972. }
  29973. case VertexBuffer.SHORT: {
  29974. var value = dataView.getInt16(byteOffset, true);
  29975. if (normalized) {
  29976. value = Math.max(value / 16383, -1);
  29977. }
  29978. return value;
  29979. }
  29980. case VertexBuffer.UNSIGNED_SHORT: {
  29981. var value = dataView.getUint16(byteOffset, true);
  29982. if (normalized) {
  29983. value = value / 65535;
  29984. }
  29985. return value;
  29986. }
  29987. case VertexBuffer.FLOAT: {
  29988. return dataView.getFloat32(byteOffset, true);
  29989. }
  29990. default: {
  29991. throw new Error("Invalid component type " + type);
  29992. }
  29993. }
  29994. };
  29995. /**
  29996. * The byte type.
  29997. */
  29998. VertexBuffer.BYTE = 5120;
  29999. /**
  30000. * The unsigned byte type.
  30001. */
  30002. VertexBuffer.UNSIGNED_BYTE = 5121;
  30003. /**
  30004. * The short type.
  30005. */
  30006. VertexBuffer.SHORT = 5122;
  30007. /**
  30008. * The unsigned short type.
  30009. */
  30010. VertexBuffer.UNSIGNED_SHORT = 5123;
  30011. /**
  30012. * The integer type.
  30013. */
  30014. VertexBuffer.INT = 5124;
  30015. /**
  30016. * The unsigned integer type.
  30017. */
  30018. VertexBuffer.UNSIGNED_INT = 5125;
  30019. /**
  30020. * The float type.
  30021. */
  30022. VertexBuffer.FLOAT = 5126;
  30023. // Enums
  30024. VertexBuffer._PositionKind = "position";
  30025. VertexBuffer._NormalKind = "normal";
  30026. VertexBuffer._TangentKind = "tangent";
  30027. VertexBuffer._UVKind = "uv";
  30028. VertexBuffer._UV2Kind = "uv2";
  30029. VertexBuffer._UV3Kind = "uv3";
  30030. VertexBuffer._UV4Kind = "uv4";
  30031. VertexBuffer._UV5Kind = "uv5";
  30032. VertexBuffer._UV6Kind = "uv6";
  30033. VertexBuffer._ColorKind = "color";
  30034. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30035. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30036. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30037. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30038. return VertexBuffer;
  30039. }());
  30040. BABYLON.VertexBuffer = VertexBuffer;
  30041. })(BABYLON || (BABYLON = {}));
  30042. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30043. var BABYLON;
  30044. (function (BABYLON) {
  30045. /**
  30046. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30047. */
  30048. var DummyInternalTextureTracker = /** @class */ (function () {
  30049. function DummyInternalTextureTracker() {
  30050. /**
  30051. * Gets or set the previous tracker in the list
  30052. */
  30053. this.previous = null;
  30054. /**
  30055. * Gets or set the next tracker in the list
  30056. */
  30057. this.next = null;
  30058. }
  30059. return DummyInternalTextureTracker;
  30060. }());
  30061. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30062. })(BABYLON || (BABYLON = {}));
  30063. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30064. var BABYLON;
  30065. (function (BABYLON) {
  30066. /**
  30067. * Class used to store data associated with WebGL texture data for the engine
  30068. * This class should not be used directly
  30069. */
  30070. var InternalTexture = /** @class */ (function () {
  30071. /**
  30072. * Creates a new InternalTexture
  30073. * @param engine defines the engine to use
  30074. * @param dataSource defines the type of data that will be used
  30075. */
  30076. function InternalTexture(engine, dataSource) {
  30077. /**
  30078. * Observable called when the texture is loaded
  30079. */
  30080. this.onLoadedObservable = new BABYLON.Observable();
  30081. /**
  30082. * Gets or set the previous tracker in the list
  30083. */
  30084. this.previous = null;
  30085. /**
  30086. * Gets or set the next tracker in the list
  30087. */
  30088. this.next = null;
  30089. // Private
  30090. /** @hidden */
  30091. this._initialSlot = -1;
  30092. /** @hidden */
  30093. this._designatedSlot = -1;
  30094. /** @hidden */
  30095. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30096. /** @hidden */
  30097. this._comparisonFunction = 0;
  30098. /** @hidden */
  30099. this._references = 1;
  30100. this._engine = engine;
  30101. this._dataSource = dataSource;
  30102. this._webGLTexture = engine._createTexture();
  30103. }
  30104. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30105. /**
  30106. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30107. */
  30108. get: function () {
  30109. return this._dataSource;
  30110. },
  30111. enumerable: true,
  30112. configurable: true
  30113. });
  30114. /**
  30115. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30116. */
  30117. InternalTexture.prototype.incrementReferences = function () {
  30118. this._references++;
  30119. };
  30120. /**
  30121. * Change the size of the texture (not the size of the content)
  30122. * @param width defines the new width
  30123. * @param height defines the new height
  30124. * @param depth defines the new depth (1 by default)
  30125. */
  30126. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30127. if (depth === void 0) { depth = 1; }
  30128. this.width = width;
  30129. this.height = height;
  30130. this.depth = depth;
  30131. this.baseWidth = width;
  30132. this.baseHeight = height;
  30133. this.baseDepth = depth;
  30134. this._size = width * height * depth;
  30135. };
  30136. /** @hidden */
  30137. InternalTexture.prototype._rebuild = function () {
  30138. var _this = this;
  30139. var proxy;
  30140. this.isReady = false;
  30141. this._cachedCoordinatesMode = null;
  30142. this._cachedWrapU = null;
  30143. this._cachedWrapV = null;
  30144. this._cachedAnisotropicFilteringLevel = null;
  30145. switch (this._dataSource) {
  30146. case InternalTexture.DATASOURCE_TEMP:
  30147. return;
  30148. case InternalTexture.DATASOURCE_URL:
  30149. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30150. _this.isReady = true;
  30151. }, null, this._buffer, undefined, this.format);
  30152. proxy._swapAndDie(this);
  30153. return;
  30154. case InternalTexture.DATASOURCE_RAW:
  30155. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30156. proxy._swapAndDie(this);
  30157. this.isReady = true;
  30158. return;
  30159. case InternalTexture.DATASOURCE_RAW3D:
  30160. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30161. proxy._swapAndDie(this);
  30162. this.isReady = true;
  30163. return;
  30164. case InternalTexture.DATASOURCE_DYNAMIC:
  30165. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30166. proxy._swapAndDie(this);
  30167. // The engine will make sure to update content so no need to flag it as isReady = true
  30168. return;
  30169. case InternalTexture.DATASOURCE_RENDERTARGET:
  30170. var options = new BABYLON.RenderTargetCreationOptions();
  30171. options.generateDepthBuffer = this._generateDepthBuffer;
  30172. options.generateMipMaps = this.generateMipMaps;
  30173. options.generateStencilBuffer = this._generateStencilBuffer;
  30174. options.samplingMode = this.samplingMode;
  30175. options.type = this.type;
  30176. if (this.isCube) {
  30177. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30178. }
  30179. else {
  30180. var size = {
  30181. width: this.width,
  30182. height: this.height
  30183. };
  30184. proxy = this._engine.createRenderTargetTexture(size, options);
  30185. }
  30186. proxy._swapAndDie(this);
  30187. this.isReady = true;
  30188. return;
  30189. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30190. var depthTextureOptions = {
  30191. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30192. comparisonFunction: this._comparisonFunction,
  30193. generateStencil: this._generateStencilBuffer,
  30194. isCube: this.isCube
  30195. };
  30196. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30197. proxy._swapAndDie(this);
  30198. this.isReady = true;
  30199. return;
  30200. case InternalTexture.DATASOURCE_CUBE:
  30201. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30202. _this.isReady = true;
  30203. }, null, this.format, this._extension);
  30204. proxy._swapAndDie(this);
  30205. return;
  30206. case InternalTexture.DATASOURCE_CUBERAW:
  30207. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30208. proxy._swapAndDie(this);
  30209. this.isReady = true;
  30210. return;
  30211. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30212. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30213. if (proxy) {
  30214. proxy._swapAndDie(_this);
  30215. }
  30216. _this.isReady = true;
  30217. }, null, this.format, this._extension);
  30218. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30219. return;
  30220. }
  30221. };
  30222. InternalTexture.prototype._swapAndDie = function (target) {
  30223. target._webGLTexture = this._webGLTexture;
  30224. if (this._framebuffer) {
  30225. target._framebuffer = this._framebuffer;
  30226. }
  30227. if (this._depthStencilBuffer) {
  30228. target._depthStencilBuffer = this._depthStencilBuffer;
  30229. }
  30230. if (this._lodTextureHigh) {
  30231. if (target._lodTextureHigh) {
  30232. target._lodTextureHigh.dispose();
  30233. }
  30234. target._lodTextureHigh = this._lodTextureHigh;
  30235. }
  30236. if (this._lodTextureMid) {
  30237. if (target._lodTextureMid) {
  30238. target._lodTextureMid.dispose();
  30239. }
  30240. target._lodTextureMid = this._lodTextureMid;
  30241. }
  30242. if (this._lodTextureLow) {
  30243. if (target._lodTextureLow) {
  30244. target._lodTextureLow.dispose();
  30245. }
  30246. target._lodTextureLow = this._lodTextureLow;
  30247. }
  30248. var cache = this._engine.getLoadedTexturesCache();
  30249. var index = cache.indexOf(this);
  30250. if (index !== -1) {
  30251. cache.splice(index, 1);
  30252. }
  30253. };
  30254. /**
  30255. * Dispose the current allocated resources
  30256. */
  30257. InternalTexture.prototype.dispose = function () {
  30258. if (!this._webGLTexture) {
  30259. return;
  30260. }
  30261. this._references--;
  30262. if (this._references === 0) {
  30263. this._engine._releaseTexture(this);
  30264. this._webGLTexture = null;
  30265. this.previous = null;
  30266. this.next = null;
  30267. }
  30268. };
  30269. /**
  30270. * The source of the texture data is unknown
  30271. */
  30272. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30273. /**
  30274. * Texture data comes from an URL
  30275. */
  30276. InternalTexture.DATASOURCE_URL = 1;
  30277. /**
  30278. * Texture data is only used for temporary storage
  30279. */
  30280. InternalTexture.DATASOURCE_TEMP = 2;
  30281. /**
  30282. * Texture data comes from raw data (ArrayBuffer)
  30283. */
  30284. InternalTexture.DATASOURCE_RAW = 3;
  30285. /**
  30286. * Texture content is dynamic (video or dynamic texture)
  30287. */
  30288. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30289. /**
  30290. * Texture content is generated by rendering to it
  30291. */
  30292. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30293. /**
  30294. * Texture content is part of a multi render target process
  30295. */
  30296. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30297. /**
  30298. * Texture data comes from a cube data file
  30299. */
  30300. InternalTexture.DATASOURCE_CUBE = 7;
  30301. /**
  30302. * Texture data comes from a raw cube data
  30303. */
  30304. InternalTexture.DATASOURCE_CUBERAW = 8;
  30305. /**
  30306. * Texture data come from a prefiltered cube data file
  30307. */
  30308. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30309. /**
  30310. * Texture content is raw 3D data
  30311. */
  30312. InternalTexture.DATASOURCE_RAW3D = 10;
  30313. /**
  30314. * Texture content is a depth texture
  30315. */
  30316. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30317. return InternalTexture;
  30318. }());
  30319. BABYLON.InternalTexture = InternalTexture;
  30320. })(BABYLON || (BABYLON = {}));
  30321. //# sourceMappingURL=babylon.internalTexture.js.map
  30322. var BABYLON;
  30323. (function (BABYLON) {
  30324. var BaseTexture = /** @class */ (function () {
  30325. function BaseTexture(scene) {
  30326. this._hasAlpha = false;
  30327. this.getAlphaFromRGB = false;
  30328. this.level = 1;
  30329. this.coordinatesIndex = 0;
  30330. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30331. /**
  30332. * | Value | Type | Description |
  30333. * | ----- | ------------------ | ----------- |
  30334. * | 0 | CLAMP_ADDRESSMODE | |
  30335. * | 1 | WRAP_ADDRESSMODE | |
  30336. * | 2 | MIRROR_ADDRESSMODE | |
  30337. */
  30338. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30339. /**
  30340. * | Value | Type | Description |
  30341. * | ----- | ------------------ | ----------- |
  30342. * | 0 | CLAMP_ADDRESSMODE | |
  30343. * | 1 | WRAP_ADDRESSMODE | |
  30344. * | 2 | MIRROR_ADDRESSMODE | |
  30345. */
  30346. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30347. /**
  30348. * | Value | Type | Description |
  30349. * | ----- | ------------------ | ----------- |
  30350. * | 0 | CLAMP_ADDRESSMODE | |
  30351. * | 1 | WRAP_ADDRESSMODE | |
  30352. * | 2 | MIRROR_ADDRESSMODE | |
  30353. */
  30354. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30355. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30356. this.isCube = false;
  30357. this.is3D = false;
  30358. this.gammaSpace = true;
  30359. this.invertZ = false;
  30360. this.lodLevelInAlpha = false;
  30361. this.lodGenerationOffset = 0.0;
  30362. this.lodGenerationScale = 0.8;
  30363. this.isRenderTarget = false;
  30364. this.animations = new Array();
  30365. /**
  30366. * An event triggered when the texture is disposed.
  30367. */
  30368. this.onDisposeObservable = new BABYLON.Observable();
  30369. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30370. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30371. if (this._scene) {
  30372. this._scene.textures.push(this);
  30373. }
  30374. this._uid = null;
  30375. }
  30376. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30377. get: function () {
  30378. return this._hasAlpha;
  30379. },
  30380. set: function (value) {
  30381. if (this._hasAlpha === value) {
  30382. return;
  30383. }
  30384. this._hasAlpha = value;
  30385. if (this._scene) {
  30386. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30387. }
  30388. },
  30389. enumerable: true,
  30390. configurable: true
  30391. });
  30392. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30393. get: function () {
  30394. return this._coordinatesMode;
  30395. },
  30396. /**
  30397. * How a texture is mapped.
  30398. *
  30399. * | Value | Type | Description |
  30400. * | ----- | ----------------------------------- | ----------- |
  30401. * | 0 | EXPLICIT_MODE | |
  30402. * | 1 | SPHERICAL_MODE | |
  30403. * | 2 | PLANAR_MODE | |
  30404. * | 3 | CUBIC_MODE | |
  30405. * | 4 | PROJECTION_MODE | |
  30406. * | 5 | SKYBOX_MODE | |
  30407. * | 6 | INVCUBIC_MODE | |
  30408. * | 7 | EQUIRECTANGULAR_MODE | |
  30409. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30410. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30411. */
  30412. set: function (value) {
  30413. if (this._coordinatesMode === value) {
  30414. return;
  30415. }
  30416. this._coordinatesMode = value;
  30417. if (this._scene) {
  30418. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30419. }
  30420. },
  30421. enumerable: true,
  30422. configurable: true
  30423. });
  30424. Object.defineProperty(BaseTexture.prototype, "uid", {
  30425. get: function () {
  30426. if (!this._uid) {
  30427. this._uid = BABYLON.Tools.RandomId();
  30428. }
  30429. return this._uid;
  30430. },
  30431. enumerable: true,
  30432. configurable: true
  30433. });
  30434. BaseTexture.prototype.toString = function () {
  30435. return this.name;
  30436. };
  30437. BaseTexture.prototype.getClassName = function () {
  30438. return "BaseTexture";
  30439. };
  30440. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30441. set: function (callback) {
  30442. if (this._onDisposeObserver) {
  30443. this.onDisposeObservable.remove(this._onDisposeObserver);
  30444. }
  30445. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30451. get: function () {
  30452. return true;
  30453. },
  30454. enumerable: true,
  30455. configurable: true
  30456. });
  30457. BaseTexture.prototype.getScene = function () {
  30458. return this._scene;
  30459. };
  30460. BaseTexture.prototype.getTextureMatrix = function () {
  30461. return BABYLON.Matrix.IdentityReadOnly;
  30462. };
  30463. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30464. return BABYLON.Matrix.IdentityReadOnly;
  30465. };
  30466. BaseTexture.prototype.getInternalTexture = function () {
  30467. return this._texture;
  30468. };
  30469. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30470. return !this.isBlocking || this.isReady();
  30471. };
  30472. BaseTexture.prototype.isReady = function () {
  30473. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30474. this.delayLoad();
  30475. return false;
  30476. }
  30477. if (this._texture) {
  30478. return this._texture.isReady;
  30479. }
  30480. return false;
  30481. };
  30482. BaseTexture.prototype.getSize = function () {
  30483. if (this._texture && this._texture.width) {
  30484. return new BABYLON.Size(this._texture.width, this._texture.height);
  30485. }
  30486. if (this._texture && this._texture._size) {
  30487. return new BABYLON.Size(this._texture._size, this._texture._size);
  30488. }
  30489. return BABYLON.Size.Zero();
  30490. };
  30491. BaseTexture.prototype.getBaseSize = function () {
  30492. if (!this.isReady() || !this._texture)
  30493. return BABYLON.Size.Zero();
  30494. if (this._texture._size) {
  30495. return new BABYLON.Size(this._texture._size, this._texture._size);
  30496. }
  30497. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30498. };
  30499. BaseTexture.prototype.scale = function (ratio) {
  30500. };
  30501. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30502. get: function () {
  30503. return false;
  30504. },
  30505. enumerable: true,
  30506. configurable: true
  30507. });
  30508. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30509. if (!this._scene) {
  30510. return null;
  30511. }
  30512. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30513. for (var index = 0; index < texturesCache.length; index++) {
  30514. var texturesCacheEntry = texturesCache[index];
  30515. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30516. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30517. texturesCacheEntry.incrementReferences();
  30518. return texturesCacheEntry;
  30519. }
  30520. }
  30521. }
  30522. return null;
  30523. };
  30524. BaseTexture.prototype._rebuild = function () {
  30525. };
  30526. BaseTexture.prototype.delayLoad = function () {
  30527. };
  30528. BaseTexture.prototype.clone = function () {
  30529. return null;
  30530. };
  30531. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30532. get: function () {
  30533. if (!this._texture) {
  30534. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30535. }
  30536. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30537. },
  30538. enumerable: true,
  30539. configurable: true
  30540. });
  30541. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30542. get: function () {
  30543. if (!this._texture) {
  30544. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30545. }
  30546. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30547. },
  30548. enumerable: true,
  30549. configurable: true
  30550. });
  30551. BaseTexture.prototype.readPixels = function (faceIndex) {
  30552. if (faceIndex === void 0) { faceIndex = 0; }
  30553. if (!this._texture) {
  30554. return null;
  30555. }
  30556. var size = this.getSize();
  30557. var scene = this.getScene();
  30558. if (!scene) {
  30559. return null;
  30560. }
  30561. var engine = scene.getEngine();
  30562. if (this._texture.isCube) {
  30563. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30564. }
  30565. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30566. };
  30567. BaseTexture.prototype.releaseInternalTexture = function () {
  30568. if (this._texture) {
  30569. this._texture.dispose();
  30570. this._texture = null;
  30571. }
  30572. };
  30573. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30574. get: function () {
  30575. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30576. return null;
  30577. }
  30578. if (!this._texture._sphericalPolynomial) {
  30579. this._texture._sphericalPolynomial =
  30580. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30581. }
  30582. return this._texture._sphericalPolynomial;
  30583. },
  30584. set: function (value) {
  30585. if (this._texture) {
  30586. this._texture._sphericalPolynomial = value;
  30587. }
  30588. },
  30589. enumerable: true,
  30590. configurable: true
  30591. });
  30592. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30593. get: function () {
  30594. if (this._texture) {
  30595. return this._texture._lodTextureHigh;
  30596. }
  30597. return null;
  30598. },
  30599. enumerable: true,
  30600. configurable: true
  30601. });
  30602. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30603. get: function () {
  30604. if (this._texture) {
  30605. return this._texture._lodTextureMid;
  30606. }
  30607. return null;
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30613. get: function () {
  30614. if (this._texture) {
  30615. return this._texture._lodTextureLow;
  30616. }
  30617. return null;
  30618. },
  30619. enumerable: true,
  30620. configurable: true
  30621. });
  30622. BaseTexture.prototype.dispose = function () {
  30623. if (!this._scene) {
  30624. return;
  30625. }
  30626. // Animations
  30627. this._scene.stopAnimation(this);
  30628. // Remove from scene
  30629. this._scene._removePendingData(this);
  30630. var index = this._scene.textures.indexOf(this);
  30631. if (index >= 0) {
  30632. this._scene.textures.splice(index, 1);
  30633. }
  30634. if (this._texture === undefined) {
  30635. return;
  30636. }
  30637. // Release
  30638. this.releaseInternalTexture();
  30639. // Callback
  30640. this.onDisposeObservable.notifyObservers(this);
  30641. this.onDisposeObservable.clear();
  30642. };
  30643. BaseTexture.prototype.serialize = function () {
  30644. if (!this.name) {
  30645. return null;
  30646. }
  30647. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30648. // Animations
  30649. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30650. return serializationObject;
  30651. };
  30652. BaseTexture.WhenAllReady = function (textures, callback) {
  30653. var numRemaining = textures.length;
  30654. if (numRemaining === 0) {
  30655. callback();
  30656. return;
  30657. }
  30658. var _loop_1 = function () {
  30659. texture = textures[i];
  30660. if (texture.isReady()) {
  30661. if (--numRemaining === 0) {
  30662. callback();
  30663. }
  30664. }
  30665. else {
  30666. onLoadObservable = texture.onLoadObservable;
  30667. var onLoadCallback_1 = function () {
  30668. onLoadObservable.removeCallback(onLoadCallback_1);
  30669. if (--numRemaining === 0) {
  30670. callback();
  30671. }
  30672. };
  30673. onLoadObservable.add(onLoadCallback_1);
  30674. }
  30675. };
  30676. var texture, onLoadObservable;
  30677. for (var i = 0; i < textures.length; i++) {
  30678. _loop_1();
  30679. }
  30680. };
  30681. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30682. __decorate([
  30683. BABYLON.serialize()
  30684. ], BaseTexture.prototype, "name", void 0);
  30685. __decorate([
  30686. BABYLON.serialize("hasAlpha")
  30687. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30688. __decorate([
  30689. BABYLON.serialize()
  30690. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30691. __decorate([
  30692. BABYLON.serialize()
  30693. ], BaseTexture.prototype, "level", void 0);
  30694. __decorate([
  30695. BABYLON.serialize()
  30696. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30697. __decorate([
  30698. BABYLON.serialize("coordinatesMode")
  30699. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30700. __decorate([
  30701. BABYLON.serialize()
  30702. ], BaseTexture.prototype, "wrapU", void 0);
  30703. __decorate([
  30704. BABYLON.serialize()
  30705. ], BaseTexture.prototype, "wrapV", void 0);
  30706. __decorate([
  30707. BABYLON.serialize()
  30708. ], BaseTexture.prototype, "wrapR", void 0);
  30709. __decorate([
  30710. BABYLON.serialize()
  30711. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30712. __decorate([
  30713. BABYLON.serialize()
  30714. ], BaseTexture.prototype, "isCube", void 0);
  30715. __decorate([
  30716. BABYLON.serialize()
  30717. ], BaseTexture.prototype, "is3D", void 0);
  30718. __decorate([
  30719. BABYLON.serialize()
  30720. ], BaseTexture.prototype, "gammaSpace", void 0);
  30721. __decorate([
  30722. BABYLON.serialize()
  30723. ], BaseTexture.prototype, "invertZ", void 0);
  30724. __decorate([
  30725. BABYLON.serialize()
  30726. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30727. __decorate([
  30728. BABYLON.serialize()
  30729. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30730. __decorate([
  30731. BABYLON.serialize()
  30732. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30733. __decorate([
  30734. BABYLON.serialize()
  30735. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30736. return BaseTexture;
  30737. }());
  30738. BABYLON.BaseTexture = BaseTexture;
  30739. })(BABYLON || (BABYLON = {}));
  30740. //# sourceMappingURL=babylon.baseTexture.js.map
  30741. var BABYLON;
  30742. (function (BABYLON) {
  30743. var Texture = /** @class */ (function (_super) {
  30744. __extends(Texture, _super);
  30745. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30746. if (noMipmap === void 0) { noMipmap = false; }
  30747. if (invertY === void 0) { invertY = true; }
  30748. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30749. if (onLoad === void 0) { onLoad = null; }
  30750. if (onError === void 0) { onError = null; }
  30751. if (buffer === void 0) { buffer = null; }
  30752. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30753. var _this = _super.call(this, scene) || this;
  30754. _this.uOffset = 0;
  30755. _this.vOffset = 0;
  30756. _this.uScale = 1.0;
  30757. _this.vScale = 1.0;
  30758. _this.uAng = 0;
  30759. _this.vAng = 0;
  30760. _this.wAng = 0;
  30761. /**
  30762. * Defines the center of rotation (U)
  30763. */
  30764. _this.uRotationCenter = 0.5;
  30765. /**
  30766. * Defines the center of rotation (V)
  30767. */
  30768. _this.vRotationCenter = 0.5;
  30769. /**
  30770. * Defines the center of rotation (W)
  30771. */
  30772. _this.wRotationCenter = 0.5;
  30773. _this._isBlocking = true;
  30774. _this.name = url || "";
  30775. _this.url = url;
  30776. _this._noMipmap = noMipmap;
  30777. _this._invertY = invertY;
  30778. _this._samplingMode = samplingMode;
  30779. _this._buffer = buffer;
  30780. _this._deleteBuffer = deleteBuffer;
  30781. if (format) {
  30782. _this._format = format;
  30783. }
  30784. scene = _this.getScene();
  30785. if (!scene) {
  30786. return _this;
  30787. }
  30788. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30789. var load = function () {
  30790. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30791. _this.onLoadObservable.notifyObservers(_this);
  30792. }
  30793. if (onLoad) {
  30794. onLoad();
  30795. }
  30796. if (!_this.isBlocking && scene) {
  30797. scene.resetCachedMaterial();
  30798. }
  30799. };
  30800. if (!_this.url) {
  30801. _this._delayedOnLoad = load;
  30802. _this._delayedOnError = onError;
  30803. return _this;
  30804. }
  30805. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30806. if (!_this._texture) {
  30807. if (!scene.useDelayedTextureLoading) {
  30808. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30809. if (deleteBuffer) {
  30810. delete _this._buffer;
  30811. }
  30812. }
  30813. else {
  30814. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30815. _this._delayedOnLoad = load;
  30816. _this._delayedOnError = onError;
  30817. }
  30818. }
  30819. else {
  30820. if (_this._texture.isReady) {
  30821. BABYLON.Tools.SetImmediate(function () { return load(); });
  30822. }
  30823. else {
  30824. _this._texture.onLoadedObservable.add(load);
  30825. }
  30826. }
  30827. return _this;
  30828. }
  30829. Object.defineProperty(Texture.prototype, "noMipmap", {
  30830. get: function () {
  30831. return this._noMipmap;
  30832. },
  30833. enumerable: true,
  30834. configurable: true
  30835. });
  30836. Object.defineProperty(Texture.prototype, "isBlocking", {
  30837. get: function () {
  30838. return this._isBlocking;
  30839. },
  30840. set: function (value) {
  30841. this._isBlocking = value;
  30842. },
  30843. enumerable: true,
  30844. configurable: true
  30845. });
  30846. Object.defineProperty(Texture.prototype, "samplingMode", {
  30847. get: function () {
  30848. return this._samplingMode;
  30849. },
  30850. enumerable: true,
  30851. configurable: true
  30852. });
  30853. /**
  30854. * Update the url (and optional buffer) of this texture if url was null during construction.
  30855. * @param url the url of the texture
  30856. * @param buffer the buffer of the texture (defaults to null)
  30857. */
  30858. Texture.prototype.updateURL = function (url, buffer) {
  30859. if (buffer === void 0) { buffer = null; }
  30860. if (this.url) {
  30861. throw new Error("URL is already set");
  30862. }
  30863. this.url = url;
  30864. this._buffer = buffer;
  30865. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30866. this.delayLoad();
  30867. };
  30868. Texture.prototype.delayLoad = function () {
  30869. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30870. return;
  30871. }
  30872. var scene = this.getScene();
  30873. if (!scene) {
  30874. return;
  30875. }
  30876. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30877. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30878. if (!this._texture) {
  30879. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30880. if (this._deleteBuffer) {
  30881. delete this._buffer;
  30882. }
  30883. }
  30884. else {
  30885. if (this._delayedOnLoad) {
  30886. if (this._texture.isReady) {
  30887. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30888. }
  30889. else {
  30890. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30891. }
  30892. }
  30893. }
  30894. this._delayedOnLoad = null;
  30895. this._delayedOnError = null;
  30896. };
  30897. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30898. if (!this._texture) {
  30899. return;
  30900. }
  30901. var scene = this.getScene();
  30902. if (!scene) {
  30903. return;
  30904. }
  30905. this._samplingMode = samplingMode;
  30906. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30907. };
  30908. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30909. x *= this.uScale;
  30910. y *= this.vScale;
  30911. x -= this.uRotationCenter * this.uScale;
  30912. y -= this.vRotationCenter * this.vScale;
  30913. z -= this.wRotationCenter;
  30914. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30915. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30916. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30917. t.z += this.wRotationCenter;
  30918. };
  30919. Texture.prototype.getTextureMatrix = function () {
  30920. var _this = this;
  30921. if (this.uOffset === this._cachedUOffset &&
  30922. this.vOffset === this._cachedVOffset &&
  30923. this.uScale === this._cachedUScale &&
  30924. this.vScale === this._cachedVScale &&
  30925. this.uAng === this._cachedUAng &&
  30926. this.vAng === this._cachedVAng &&
  30927. this.wAng === this._cachedWAng) {
  30928. return this._cachedTextureMatrix;
  30929. }
  30930. this._cachedUOffset = this.uOffset;
  30931. this._cachedVOffset = this.vOffset;
  30932. this._cachedUScale = this.uScale;
  30933. this._cachedVScale = this.vScale;
  30934. this._cachedUAng = this.uAng;
  30935. this._cachedVAng = this.vAng;
  30936. this._cachedWAng = this.wAng;
  30937. if (!this._cachedTextureMatrix) {
  30938. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30939. this._rowGenerationMatrix = new BABYLON.Matrix();
  30940. this._t0 = BABYLON.Vector3.Zero();
  30941. this._t1 = BABYLON.Vector3.Zero();
  30942. this._t2 = BABYLON.Vector3.Zero();
  30943. }
  30944. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30945. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30946. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30947. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30948. this._t1.subtractInPlace(this._t0);
  30949. this._t2.subtractInPlace(this._t0);
  30950. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30951. this._cachedTextureMatrix.m[0] = this._t1.x;
  30952. this._cachedTextureMatrix.m[1] = this._t1.y;
  30953. this._cachedTextureMatrix.m[2] = this._t1.z;
  30954. this._cachedTextureMatrix.m[4] = this._t2.x;
  30955. this._cachedTextureMatrix.m[5] = this._t2.y;
  30956. this._cachedTextureMatrix.m[6] = this._t2.z;
  30957. this._cachedTextureMatrix.m[8] = this._t0.x;
  30958. this._cachedTextureMatrix.m[9] = this._t0.y;
  30959. this._cachedTextureMatrix.m[10] = this._t0.z;
  30960. var scene = this.getScene();
  30961. if (!scene) {
  30962. return this._cachedTextureMatrix;
  30963. }
  30964. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30965. return mat.hasTexture(_this);
  30966. });
  30967. return this._cachedTextureMatrix;
  30968. };
  30969. Texture.prototype.getReflectionTextureMatrix = function () {
  30970. var _this = this;
  30971. var scene = this.getScene();
  30972. if (!scene) {
  30973. return this._cachedTextureMatrix;
  30974. }
  30975. if (this.uOffset === this._cachedUOffset &&
  30976. this.vOffset === this._cachedVOffset &&
  30977. this.uScale === this._cachedUScale &&
  30978. this.vScale === this._cachedVScale &&
  30979. this.coordinatesMode === this._cachedCoordinatesMode) {
  30980. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30981. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30982. return this._cachedTextureMatrix;
  30983. }
  30984. }
  30985. else {
  30986. return this._cachedTextureMatrix;
  30987. }
  30988. }
  30989. if (!this._cachedTextureMatrix) {
  30990. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30991. }
  30992. if (!this._projectionModeMatrix) {
  30993. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30994. }
  30995. this._cachedUOffset = this.uOffset;
  30996. this._cachedVOffset = this.vOffset;
  30997. this._cachedUScale = this.uScale;
  30998. this._cachedVScale = this.vScale;
  30999. this._cachedCoordinatesMode = this.coordinatesMode;
  31000. switch (this.coordinatesMode) {
  31001. case Texture.PLANAR_MODE:
  31002. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31003. this._cachedTextureMatrix[0] = this.uScale;
  31004. this._cachedTextureMatrix[5] = this.vScale;
  31005. this._cachedTextureMatrix[12] = this.uOffset;
  31006. this._cachedTextureMatrix[13] = this.vOffset;
  31007. break;
  31008. case Texture.PROJECTION_MODE:
  31009. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31010. this._projectionModeMatrix.m[0] = 0.5;
  31011. this._projectionModeMatrix.m[5] = -0.5;
  31012. this._projectionModeMatrix.m[10] = 0.0;
  31013. this._projectionModeMatrix.m[12] = 0.5;
  31014. this._projectionModeMatrix.m[13] = 0.5;
  31015. this._projectionModeMatrix.m[14] = 1.0;
  31016. this._projectionModeMatrix.m[15] = 1.0;
  31017. var projectionMatrix = scene.getProjectionMatrix();
  31018. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31019. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31020. break;
  31021. default:
  31022. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31023. break;
  31024. }
  31025. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31026. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31027. });
  31028. return this._cachedTextureMatrix;
  31029. };
  31030. Texture.prototype.clone = function () {
  31031. var _this = this;
  31032. return BABYLON.SerializationHelper.Clone(function () {
  31033. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31034. }, this);
  31035. };
  31036. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31037. get: function () {
  31038. if (!this._onLoadObservable) {
  31039. this._onLoadObservable = new BABYLON.Observable();
  31040. }
  31041. return this._onLoadObservable;
  31042. },
  31043. enumerable: true,
  31044. configurable: true
  31045. });
  31046. Texture.prototype.serialize = function () {
  31047. var serializationObject = _super.prototype.serialize.call(this);
  31048. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31049. serializationObject.base64String = this._buffer;
  31050. serializationObject.name = serializationObject.name.replace("data:", "");
  31051. }
  31052. serializationObject.invertY = this._invertY;
  31053. serializationObject.samplingMode = this.samplingMode;
  31054. return serializationObject;
  31055. };
  31056. Texture.prototype.getClassName = function () {
  31057. return "Texture";
  31058. };
  31059. Texture.prototype.dispose = function () {
  31060. _super.prototype.dispose.call(this);
  31061. if (this.onLoadObservable) {
  31062. this.onLoadObservable.clear();
  31063. this._onLoadObservable = null;
  31064. }
  31065. this._delayedOnLoad = null;
  31066. this._delayedOnError = null;
  31067. };
  31068. // Statics
  31069. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31070. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31071. if (onLoad === void 0) { onLoad = null; }
  31072. if (onError === void 0) { onError = null; }
  31073. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31074. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31075. };
  31076. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31077. if (parsedTexture.customType) {
  31078. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31079. // Update Sampling Mode
  31080. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31081. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31082. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31083. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31084. }
  31085. }
  31086. return parsedCustomTexture;
  31087. }
  31088. if (parsedTexture.isCube) {
  31089. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31090. }
  31091. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31092. return null;
  31093. }
  31094. var texture = BABYLON.SerializationHelper.Parse(function () {
  31095. var generateMipMaps = true;
  31096. if (parsedTexture.noMipmap) {
  31097. generateMipMaps = false;
  31098. }
  31099. if (parsedTexture.mirrorPlane) {
  31100. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31101. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31102. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31103. return mirrorTexture;
  31104. }
  31105. else if (parsedTexture.isRenderTarget) {
  31106. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31107. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31108. return renderTargetTexture;
  31109. }
  31110. else {
  31111. var texture;
  31112. if (parsedTexture.base64String) {
  31113. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31114. }
  31115. else {
  31116. var url = rootUrl + parsedTexture.name;
  31117. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31118. url = parsedTexture.url;
  31119. }
  31120. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31121. }
  31122. return texture;
  31123. }
  31124. }, parsedTexture, scene);
  31125. // Update Sampling Mode
  31126. if (parsedTexture.samplingMode) {
  31127. var sampling = parsedTexture.samplingMode;
  31128. if (texture._samplingMode !== sampling) {
  31129. texture.updateSamplingMode(sampling);
  31130. }
  31131. }
  31132. // Animations
  31133. if (parsedTexture.animations) {
  31134. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31135. var parsedAnimation = parsedTexture.animations[animationIndex];
  31136. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31137. }
  31138. }
  31139. return texture;
  31140. };
  31141. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31142. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31143. if (noMipmap === void 0) { noMipmap = false; }
  31144. if (invertY === void 0) { invertY = true; }
  31145. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31146. if (onLoad === void 0) { onLoad = null; }
  31147. if (onError === void 0) { onError = null; }
  31148. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31149. if (name.substr(0, 5) !== "data:") {
  31150. name = "data:" + name;
  31151. }
  31152. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31153. };
  31154. // Constants
  31155. Texture.NEAREST_SAMPLINGMODE = 1;
  31156. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31157. Texture.BILINEAR_SAMPLINGMODE = 2;
  31158. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31159. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31160. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31161. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31162. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31163. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31164. Texture.NEAREST_LINEAR = 7;
  31165. Texture.NEAREST_NEAREST = 8;
  31166. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31167. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31168. Texture.LINEAR_LINEAR = 11;
  31169. Texture.LINEAR_NEAREST = 12;
  31170. Texture.EXPLICIT_MODE = 0;
  31171. Texture.SPHERICAL_MODE = 1;
  31172. Texture.PLANAR_MODE = 2;
  31173. Texture.CUBIC_MODE = 3;
  31174. Texture.PROJECTION_MODE = 4;
  31175. Texture.SKYBOX_MODE = 5;
  31176. Texture.INVCUBIC_MODE = 6;
  31177. Texture.EQUIRECTANGULAR_MODE = 7;
  31178. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31179. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31180. Texture.CLAMP_ADDRESSMODE = 0;
  31181. Texture.WRAP_ADDRESSMODE = 1;
  31182. Texture.MIRROR_ADDRESSMODE = 2;
  31183. /**
  31184. * 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
  31185. */
  31186. Texture.UseSerializedUrlIfAny = false;
  31187. __decorate([
  31188. BABYLON.serialize()
  31189. ], Texture.prototype, "url", void 0);
  31190. __decorate([
  31191. BABYLON.serialize()
  31192. ], Texture.prototype, "uOffset", void 0);
  31193. __decorate([
  31194. BABYLON.serialize()
  31195. ], Texture.prototype, "vOffset", void 0);
  31196. __decorate([
  31197. BABYLON.serialize()
  31198. ], Texture.prototype, "uScale", void 0);
  31199. __decorate([
  31200. BABYLON.serialize()
  31201. ], Texture.prototype, "vScale", void 0);
  31202. __decorate([
  31203. BABYLON.serialize()
  31204. ], Texture.prototype, "uAng", void 0);
  31205. __decorate([
  31206. BABYLON.serialize()
  31207. ], Texture.prototype, "vAng", void 0);
  31208. __decorate([
  31209. BABYLON.serialize()
  31210. ], Texture.prototype, "wAng", void 0);
  31211. __decorate([
  31212. BABYLON.serialize()
  31213. ], Texture.prototype, "uRotationCenter", void 0);
  31214. __decorate([
  31215. BABYLON.serialize()
  31216. ], Texture.prototype, "vRotationCenter", void 0);
  31217. __decorate([
  31218. BABYLON.serialize()
  31219. ], Texture.prototype, "wRotationCenter", void 0);
  31220. __decorate([
  31221. BABYLON.serialize()
  31222. ], Texture.prototype, "isBlocking", null);
  31223. return Texture;
  31224. }(BABYLON.BaseTexture));
  31225. BABYLON.Texture = Texture;
  31226. })(BABYLON || (BABYLON = {}));
  31227. //# sourceMappingURL=babylon.texture.js.map
  31228. var BABYLON;
  31229. (function (BABYLON) {
  31230. /**
  31231. * @hidden
  31232. **/
  31233. var _InstancesBatch = /** @class */ (function () {
  31234. function _InstancesBatch() {
  31235. this.mustReturn = false;
  31236. this.visibleInstances = new Array();
  31237. this.renderSelf = new Array();
  31238. }
  31239. return _InstancesBatch;
  31240. }());
  31241. BABYLON._InstancesBatch = _InstancesBatch;
  31242. var Mesh = /** @class */ (function (_super) {
  31243. __extends(Mesh, _super);
  31244. /**
  31245. * @constructor
  31246. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31247. * @param {Scene} scene The scene to add this mesh to.
  31248. * @param {Node} parent The parent of this mesh, if it has one
  31249. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31250. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31251. * When false, achieved by calling a clone(), also passing False.
  31252. * This will make creation of children, recursive.
  31253. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31254. */
  31255. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31256. if (scene === void 0) { scene = null; }
  31257. if (parent === void 0) { parent = null; }
  31258. if (source === void 0) { source = null; }
  31259. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31260. var _this = _super.call(this, name, scene) || this;
  31261. // Events
  31262. /**
  31263. * An event triggered before rendering the mesh
  31264. */
  31265. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31266. /**
  31267. * An event triggered after rendering the mesh
  31268. */
  31269. _this.onAfterRenderObservable = new BABYLON.Observable();
  31270. /**
  31271. * An event triggered before drawing the mesh
  31272. */
  31273. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31274. // Members
  31275. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31276. _this.instances = new Array();
  31277. _this._LODLevels = new Array();
  31278. _this._visibleInstances = {};
  31279. _this._renderIdForInstances = new Array();
  31280. _this._batchCache = new _InstancesBatch();
  31281. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31282. // Use by builder only to know what orientation were the mesh build in.
  31283. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31284. _this.overrideMaterialSideOrientation = null;
  31285. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31286. // Will be used to save a source mesh reference, If any
  31287. _this._source = null;
  31288. scene = _this.getScene();
  31289. if (source) {
  31290. // Geometry
  31291. if (source._geometry) {
  31292. source._geometry.applyToMesh(_this);
  31293. }
  31294. // Deep copy
  31295. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31296. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31297. // Source mesh
  31298. _this._source = source;
  31299. // Metadata
  31300. if (source.metadata && source.metadata.clone) {
  31301. _this.metadata = source.metadata.clone();
  31302. }
  31303. else {
  31304. _this.metadata = source.metadata;
  31305. }
  31306. // Tags
  31307. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31308. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31309. }
  31310. // Parent
  31311. _this.parent = source.parent;
  31312. // Pivot
  31313. _this.setPivotMatrix(source.getPivotMatrix());
  31314. _this.id = name + "." + source.id;
  31315. // Material
  31316. _this.material = source.material;
  31317. var index;
  31318. if (!doNotCloneChildren) {
  31319. // Children
  31320. var directDescendants = source.getDescendants(true);
  31321. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31322. var child = directDescendants[index_1];
  31323. if (child.clone) {
  31324. child.clone(name + "." + child.name, _this);
  31325. }
  31326. }
  31327. }
  31328. // Physics clone
  31329. var physicsEngine = _this.getScene().getPhysicsEngine();
  31330. if (clonePhysicsImpostor && physicsEngine) {
  31331. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31332. if (impostor) {
  31333. _this.physicsImpostor = impostor.clone(_this);
  31334. }
  31335. }
  31336. // Particles
  31337. for (index = 0; index < scene.particleSystems.length; index++) {
  31338. var system = scene.particleSystems[index];
  31339. if (system.emitter === source) {
  31340. system.clone(system.name, _this);
  31341. }
  31342. }
  31343. _this.computeWorldMatrix(true);
  31344. }
  31345. // Parent
  31346. if (parent !== null) {
  31347. _this.parent = parent;
  31348. }
  31349. return _this;
  31350. }
  31351. Object.defineProperty(Mesh, "FRONTSIDE", {
  31352. /**
  31353. * Mesh side orientation : usually the external or front surface
  31354. */
  31355. get: function () {
  31356. return Mesh._FRONTSIDE;
  31357. },
  31358. enumerable: true,
  31359. configurable: true
  31360. });
  31361. Object.defineProperty(Mesh, "BACKSIDE", {
  31362. /**
  31363. * Mesh side orientation : usually the internal or back surface
  31364. */
  31365. get: function () {
  31366. return Mesh._BACKSIDE;
  31367. },
  31368. enumerable: true,
  31369. configurable: true
  31370. });
  31371. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31372. /**
  31373. * Mesh side orientation : both internal and external or front and back surfaces
  31374. */
  31375. get: function () {
  31376. return Mesh._DOUBLESIDE;
  31377. },
  31378. enumerable: true,
  31379. configurable: true
  31380. });
  31381. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31382. /**
  31383. * Mesh side orientation : by default, `FRONTSIDE`
  31384. */
  31385. get: function () {
  31386. return Mesh._DEFAULTSIDE;
  31387. },
  31388. enumerable: true,
  31389. configurable: true
  31390. });
  31391. Object.defineProperty(Mesh, "NO_CAP", {
  31392. /**
  31393. * Mesh cap setting : no cap
  31394. */
  31395. get: function () {
  31396. return Mesh._NO_CAP;
  31397. },
  31398. enumerable: true,
  31399. configurable: true
  31400. });
  31401. Object.defineProperty(Mesh, "CAP_START", {
  31402. /**
  31403. * Mesh cap setting : one cap at the beginning of the mesh
  31404. */
  31405. get: function () {
  31406. return Mesh._CAP_START;
  31407. },
  31408. enumerable: true,
  31409. configurable: true
  31410. });
  31411. Object.defineProperty(Mesh, "CAP_END", {
  31412. /**
  31413. * Mesh cap setting : one cap at the end of the mesh
  31414. */
  31415. get: function () {
  31416. return Mesh._CAP_END;
  31417. },
  31418. enumerable: true,
  31419. configurable: true
  31420. });
  31421. Object.defineProperty(Mesh, "CAP_ALL", {
  31422. /**
  31423. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31424. */
  31425. get: function () {
  31426. return Mesh._CAP_ALL;
  31427. },
  31428. enumerable: true,
  31429. configurable: true
  31430. });
  31431. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31432. set: function (callback) {
  31433. if (this._onBeforeDrawObserver) {
  31434. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31435. }
  31436. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31437. },
  31438. enumerable: true,
  31439. configurable: true
  31440. });
  31441. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31442. get: function () {
  31443. return this._morphTargetManager;
  31444. },
  31445. set: function (value) {
  31446. if (this._morphTargetManager === value) {
  31447. return;
  31448. }
  31449. this._morphTargetManager = value;
  31450. this._syncGeometryWithMorphTargetManager();
  31451. },
  31452. enumerable: true,
  31453. configurable: true
  31454. });
  31455. Object.defineProperty(Mesh.prototype, "source", {
  31456. get: function () {
  31457. return this._source;
  31458. },
  31459. enumerable: true,
  31460. configurable: true
  31461. });
  31462. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31463. get: function () {
  31464. return this._unIndexed;
  31465. },
  31466. set: function (value) {
  31467. if (this._unIndexed !== value) {
  31468. this._unIndexed = value;
  31469. this._markSubMeshesAsAttributesDirty();
  31470. }
  31471. },
  31472. enumerable: true,
  31473. configurable: true
  31474. });
  31475. // Methods
  31476. /**
  31477. * Returns the string "Mesh".
  31478. */
  31479. Mesh.prototype.getClassName = function () {
  31480. return "Mesh";
  31481. };
  31482. /**
  31483. * Returns a string.
  31484. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31485. */
  31486. Mesh.prototype.toString = function (fullDetails) {
  31487. var ret = _super.prototype.toString.call(this, fullDetails);
  31488. ret += ", n vertices: " + this.getTotalVertices();
  31489. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31490. if (this.animations) {
  31491. for (var i = 0; i < this.animations.length; i++) {
  31492. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31493. }
  31494. }
  31495. if (fullDetails) {
  31496. if (this._geometry) {
  31497. var ib = this.getIndices();
  31498. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31499. if (vb && ib) {
  31500. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31501. }
  31502. }
  31503. else {
  31504. ret += ", flat shading: UNKNOWN";
  31505. }
  31506. }
  31507. return ret;
  31508. };
  31509. Mesh.prototype._unBindEffect = function () {
  31510. _super.prototype._unBindEffect.call(this);
  31511. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31512. var instance = _a[_i];
  31513. instance._unBindEffect();
  31514. }
  31515. };
  31516. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31517. /**
  31518. * True if the mesh has some Levels Of Details (LOD).
  31519. * Returns a boolean.
  31520. */
  31521. get: function () {
  31522. return this._LODLevels.length > 0;
  31523. },
  31524. enumerable: true,
  31525. configurable: true
  31526. });
  31527. /**
  31528. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31529. * @returns an array of {BABYLON.MeshLODLevel}
  31530. */
  31531. Mesh.prototype.getLODLevels = function () {
  31532. return this._LODLevels;
  31533. };
  31534. Mesh.prototype._sortLODLevels = function () {
  31535. this._LODLevels.sort(function (a, b) {
  31536. if (a.distance < b.distance) {
  31537. return 1;
  31538. }
  31539. if (a.distance > b.distance) {
  31540. return -1;
  31541. }
  31542. return 0;
  31543. });
  31544. };
  31545. /**
  31546. * Add a mesh as LOD level triggered at the given distance.
  31547. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31548. * @param {number} distance The distance from the center of the object to show this level
  31549. * @param {Mesh} mesh The mesh to be added as LOD level
  31550. * @return {Mesh} This mesh (for chaining)
  31551. */
  31552. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31553. if (mesh && mesh._masterMesh) {
  31554. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31555. return this;
  31556. }
  31557. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31558. this._LODLevels.push(level);
  31559. if (mesh) {
  31560. mesh._masterMesh = this;
  31561. }
  31562. this._sortLODLevels();
  31563. return this;
  31564. };
  31565. /**
  31566. * Returns the LOD level mesh at the passed distance or null if not found.
  31567. * It is related to the method `addLODLevel(distance, mesh)`.
  31568. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31569. * Returns an object Mesh or `null`.
  31570. */
  31571. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31572. for (var index = 0; index < this._LODLevels.length; index++) {
  31573. var level = this._LODLevels[index];
  31574. if (level.distance === distance) {
  31575. return level.mesh;
  31576. }
  31577. }
  31578. return null;
  31579. };
  31580. /**
  31581. * Remove a mesh from the LOD array
  31582. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31583. * @param {Mesh} mesh The mesh to be removed.
  31584. * @return {Mesh} This mesh (for chaining)
  31585. */
  31586. Mesh.prototype.removeLODLevel = function (mesh) {
  31587. for (var index = 0; index < this._LODLevels.length; index++) {
  31588. if (this._LODLevels[index].mesh === mesh) {
  31589. this._LODLevels.splice(index, 1);
  31590. if (mesh) {
  31591. mesh._masterMesh = null;
  31592. }
  31593. }
  31594. }
  31595. this._sortLODLevels();
  31596. return this;
  31597. };
  31598. /**
  31599. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31600. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31601. */
  31602. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31603. if (!this._LODLevels || this._LODLevels.length === 0) {
  31604. return this;
  31605. }
  31606. var bSphere;
  31607. if (boundingSphere) {
  31608. bSphere = boundingSphere;
  31609. }
  31610. else {
  31611. var boundingInfo = this.getBoundingInfo();
  31612. bSphere = boundingInfo.boundingSphere;
  31613. }
  31614. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31615. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31616. if (this.onLODLevelSelection) {
  31617. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31618. }
  31619. return this;
  31620. }
  31621. for (var index = 0; index < this._LODLevels.length; index++) {
  31622. var level = this._LODLevels[index];
  31623. if (level.distance < distanceToCamera) {
  31624. if (level.mesh) {
  31625. level.mesh._preActivate();
  31626. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31627. }
  31628. if (this.onLODLevelSelection) {
  31629. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31630. }
  31631. return level.mesh;
  31632. }
  31633. }
  31634. if (this.onLODLevelSelection) {
  31635. this.onLODLevelSelection(distanceToCamera, this, this);
  31636. }
  31637. return this;
  31638. };
  31639. Object.defineProperty(Mesh.prototype, "geometry", {
  31640. /**
  31641. * Returns the mesh internal Geometry object.
  31642. */
  31643. get: function () {
  31644. return this._geometry;
  31645. },
  31646. enumerable: true,
  31647. configurable: true
  31648. });
  31649. /**
  31650. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31651. */
  31652. Mesh.prototype.getTotalVertices = function () {
  31653. if (this._geometry === null || this._geometry === undefined) {
  31654. return 0;
  31655. }
  31656. return this._geometry.getTotalVertices();
  31657. };
  31658. /**
  31659. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31660. * 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.
  31661. * You can force the copy with forceCopy === true
  31662. * Returns null if the mesh has no geometry or no vertex buffer.
  31663. * Possible `kind` values :
  31664. * - BABYLON.VertexBuffer.PositionKind
  31665. * - BABYLON.VertexBuffer.UVKind
  31666. * - BABYLON.VertexBuffer.UV2Kind
  31667. * - BABYLON.VertexBuffer.UV3Kind
  31668. * - BABYLON.VertexBuffer.UV4Kind
  31669. * - BABYLON.VertexBuffer.UV5Kind
  31670. * - BABYLON.VertexBuffer.UV6Kind
  31671. * - BABYLON.VertexBuffer.ColorKind
  31672. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31673. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31674. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31675. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31676. */
  31677. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31678. if (!this._geometry) {
  31679. return null;
  31680. }
  31681. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31682. };
  31683. /**
  31684. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31685. * Returns `null` if the mesh has no geometry.
  31686. * Possible `kind` values :
  31687. * - BABYLON.VertexBuffer.PositionKind
  31688. * - BABYLON.VertexBuffer.UVKind
  31689. * - BABYLON.VertexBuffer.UV2Kind
  31690. * - BABYLON.VertexBuffer.UV3Kind
  31691. * - BABYLON.VertexBuffer.UV4Kind
  31692. * - BABYLON.VertexBuffer.UV5Kind
  31693. * - BABYLON.VertexBuffer.UV6Kind
  31694. * - BABYLON.VertexBuffer.ColorKind
  31695. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31696. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31697. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31698. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31699. */
  31700. Mesh.prototype.getVertexBuffer = function (kind) {
  31701. if (!this._geometry) {
  31702. return null;
  31703. }
  31704. return this._geometry.getVertexBuffer(kind);
  31705. };
  31706. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31707. if (!this._geometry) {
  31708. if (this._delayInfo) {
  31709. return this._delayInfo.indexOf(kind) !== -1;
  31710. }
  31711. return false;
  31712. }
  31713. return this._geometry.isVerticesDataPresent(kind);
  31714. };
  31715. /**
  31716. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31717. * Possible `kind` values :
  31718. * - BABYLON.VertexBuffer.PositionKind
  31719. * - BABYLON.VertexBuffer.UVKind
  31720. * - BABYLON.VertexBuffer.UV2Kind
  31721. * - BABYLON.VertexBuffer.UV3Kind
  31722. * - BABYLON.VertexBuffer.UV4Kind
  31723. * - BABYLON.VertexBuffer.UV5Kind
  31724. * - BABYLON.VertexBuffer.UV6Kind
  31725. * - BABYLON.VertexBuffer.ColorKind
  31726. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31727. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31728. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31729. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31730. */
  31731. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31732. if (!this._geometry) {
  31733. if (this._delayInfo) {
  31734. return this._delayInfo.indexOf(kind) !== -1;
  31735. }
  31736. return false;
  31737. }
  31738. return this._geometry.isVertexBufferUpdatable(kind);
  31739. };
  31740. /**
  31741. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31742. * Possible `kind` values :
  31743. * - BABYLON.VertexBuffer.PositionKind
  31744. * - BABYLON.VertexBuffer.UVKind
  31745. * - BABYLON.VertexBuffer.UV2Kind
  31746. * - BABYLON.VertexBuffer.UV3Kind
  31747. * - BABYLON.VertexBuffer.UV4Kind
  31748. * - BABYLON.VertexBuffer.UV5Kind
  31749. * - BABYLON.VertexBuffer.UV6Kind
  31750. * - BABYLON.VertexBuffer.ColorKind
  31751. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31752. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31753. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31754. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31755. */
  31756. Mesh.prototype.getVerticesDataKinds = function () {
  31757. if (!this._geometry) {
  31758. var result = new Array();
  31759. if (this._delayInfo) {
  31760. this._delayInfo.forEach(function (kind, index, array) {
  31761. result.push(kind);
  31762. });
  31763. }
  31764. return result;
  31765. }
  31766. return this._geometry.getVerticesDataKinds();
  31767. };
  31768. /**
  31769. * Returns a positive integer : the total number of indices in this mesh geometry.
  31770. * Returns zero if the mesh has no geometry.
  31771. */
  31772. Mesh.prototype.getTotalIndices = function () {
  31773. if (!this._geometry) {
  31774. return 0;
  31775. }
  31776. return this._geometry.getTotalIndices();
  31777. };
  31778. /**
  31779. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31780. * 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.
  31781. * Returns an empty array if the mesh has no geometry.
  31782. */
  31783. Mesh.prototype.getIndices = function (copyWhenShared) {
  31784. if (!this._geometry) {
  31785. return [];
  31786. }
  31787. return this._geometry.getIndices(copyWhenShared);
  31788. };
  31789. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31790. get: function () {
  31791. return this._masterMesh !== null && this._masterMesh !== undefined;
  31792. },
  31793. enumerable: true,
  31794. configurable: true
  31795. });
  31796. /**
  31797. * Determine if the current mesh is ready to be rendered
  31798. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31799. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31800. * @returns true if all associated assets are ready (material, textures, shaders)
  31801. */
  31802. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31803. if (completeCheck === void 0) { completeCheck = false; }
  31804. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31805. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31806. return false;
  31807. }
  31808. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31809. return false;
  31810. }
  31811. if (!this.subMeshes || this.subMeshes.length === 0) {
  31812. return true;
  31813. }
  31814. if (!completeCheck) {
  31815. return true;
  31816. }
  31817. var engine = this.getEngine();
  31818. var scene = this.getScene();
  31819. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31820. this.computeWorldMatrix();
  31821. var mat = this.material || scene.defaultMaterial;
  31822. if (mat) {
  31823. if (mat.storeEffectOnSubMeshes) {
  31824. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31825. var subMesh = _a[_i];
  31826. var effectiveMaterial = subMesh.getMaterial();
  31827. if (effectiveMaterial) {
  31828. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31829. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31830. return false;
  31831. }
  31832. }
  31833. else {
  31834. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31835. return false;
  31836. }
  31837. }
  31838. }
  31839. }
  31840. }
  31841. else {
  31842. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31843. return false;
  31844. }
  31845. }
  31846. }
  31847. // Shadows
  31848. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31849. var light = _c[_b];
  31850. var generator = light.getShadowGenerator();
  31851. if (generator) {
  31852. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31853. var subMesh = _e[_d];
  31854. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31855. return false;
  31856. }
  31857. }
  31858. }
  31859. }
  31860. // LOD
  31861. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31862. var lod = _g[_f];
  31863. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31864. return false;
  31865. }
  31866. }
  31867. return true;
  31868. };
  31869. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31870. /**
  31871. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31872. * This property is pertinent only for updatable parametric shapes.
  31873. */
  31874. get: function () {
  31875. return this._areNormalsFrozen;
  31876. },
  31877. enumerable: true,
  31878. configurable: true
  31879. });
  31880. /**
  31881. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31882. * It has no effect at all on other shapes.
  31883. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31884. * Returns the Mesh.
  31885. */
  31886. Mesh.prototype.freezeNormals = function () {
  31887. this._areNormalsFrozen = true;
  31888. return this;
  31889. };
  31890. /**
  31891. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31892. * It has no effect at all on other shapes.
  31893. * It reactivates the mesh normals computation if it was previously frozen.
  31894. * Returns the Mesh.
  31895. */
  31896. Mesh.prototype.unfreezeNormals = function () {
  31897. this._areNormalsFrozen = false;
  31898. return this;
  31899. };
  31900. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31901. /**
  31902. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31903. */
  31904. set: function (count) {
  31905. this._overridenInstanceCount = count;
  31906. },
  31907. enumerable: true,
  31908. configurable: true
  31909. });
  31910. // Methods
  31911. Mesh.prototype._preActivate = function () {
  31912. var sceneRenderId = this.getScene().getRenderId();
  31913. if (this._preActivateId === sceneRenderId) {
  31914. return this;
  31915. }
  31916. this._preActivateId = sceneRenderId;
  31917. this._visibleInstances = null;
  31918. return this;
  31919. };
  31920. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31921. if (this._visibleInstances) {
  31922. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31923. }
  31924. return this;
  31925. };
  31926. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31927. if (!this._visibleInstances) {
  31928. this._visibleInstances = {};
  31929. this._visibleInstances.defaultRenderId = renderId;
  31930. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31931. }
  31932. if (!this._visibleInstances[renderId]) {
  31933. this._visibleInstances[renderId] = new Array();
  31934. }
  31935. this._visibleInstances[renderId].push(instance);
  31936. return this;
  31937. };
  31938. /**
  31939. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31940. * This means the mesh underlying bounding box and sphere are recomputed.
  31941. * Returns the Mesh.
  31942. */
  31943. Mesh.prototype.refreshBoundingInfo = function () {
  31944. return this._refreshBoundingInfo(false);
  31945. };
  31946. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31947. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31948. return this;
  31949. }
  31950. var data = this._getPositionData(applySkeleton);
  31951. if (data) {
  31952. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31953. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31954. }
  31955. if (this.subMeshes) {
  31956. for (var index = 0; index < this.subMeshes.length; index++) {
  31957. this.subMeshes[index].refreshBoundingInfo();
  31958. }
  31959. }
  31960. this._updateBoundingInfo();
  31961. return this;
  31962. };
  31963. Mesh.prototype._getPositionData = function (applySkeleton) {
  31964. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31965. if (data && applySkeleton && this.skeleton) {
  31966. data = BABYLON.Tools.Slice(data);
  31967. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31968. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31969. if (matricesWeightsData && matricesIndicesData) {
  31970. var needExtras = this.numBoneInfluencers > 4;
  31971. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31972. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31973. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31974. var tempVector = BABYLON.Tmp.Vector3[0];
  31975. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31976. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31977. var matWeightIdx = 0;
  31978. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31979. finalMatrix.reset();
  31980. var inf;
  31981. var weight;
  31982. for (inf = 0; inf < 4; inf++) {
  31983. weight = matricesWeightsData[matWeightIdx + inf];
  31984. if (weight <= 0)
  31985. break;
  31986. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31987. finalMatrix.addToSelf(tempMatrix);
  31988. }
  31989. if (needExtras) {
  31990. for (inf = 0; inf < 4; inf++) {
  31991. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31992. if (weight <= 0)
  31993. break;
  31994. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31995. finalMatrix.addToSelf(tempMatrix);
  31996. }
  31997. }
  31998. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31999. tempVector.toArray(data, index);
  32000. }
  32001. }
  32002. }
  32003. return data;
  32004. };
  32005. Mesh.prototype._createGlobalSubMesh = function (force) {
  32006. var totalVertices = this.getTotalVertices();
  32007. if (!totalVertices || !this.getIndices()) {
  32008. return null;
  32009. }
  32010. // Check if we need to recreate the submeshes
  32011. if (this.subMeshes && this.subMeshes.length > 0) {
  32012. var ib = this.getIndices();
  32013. if (!ib) {
  32014. return null;
  32015. }
  32016. var totalIndices = ib.length;
  32017. var needToRecreate = false;
  32018. if (force) {
  32019. needToRecreate = true;
  32020. }
  32021. else {
  32022. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32023. var submesh = _a[_i];
  32024. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32025. needToRecreate = true;
  32026. break;
  32027. }
  32028. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32029. needToRecreate = true;
  32030. break;
  32031. }
  32032. }
  32033. }
  32034. if (!needToRecreate) {
  32035. return this.subMeshes[0];
  32036. }
  32037. }
  32038. this.releaseSubMeshes();
  32039. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32040. };
  32041. Mesh.prototype.subdivide = function (count) {
  32042. if (count < 1) {
  32043. return;
  32044. }
  32045. var totalIndices = this.getTotalIndices();
  32046. var subdivisionSize = (totalIndices / count) | 0;
  32047. var offset = 0;
  32048. // Ensure that subdivisionSize is a multiple of 3
  32049. while (subdivisionSize % 3 !== 0) {
  32050. subdivisionSize++;
  32051. }
  32052. this.releaseSubMeshes();
  32053. for (var index = 0; index < count; index++) {
  32054. if (offset >= totalIndices) {
  32055. break;
  32056. }
  32057. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32058. offset += subdivisionSize;
  32059. }
  32060. this.synchronizeInstances();
  32061. };
  32062. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32063. if (updatable === void 0) { updatable = false; }
  32064. if (!this._geometry) {
  32065. var vertexData = new BABYLON.VertexData();
  32066. vertexData.set(data, kind);
  32067. var scene = this.getScene();
  32068. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32069. }
  32070. else {
  32071. this._geometry.setVerticesData(kind, data, updatable, stride);
  32072. }
  32073. return this;
  32074. };
  32075. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32076. if (updatable === void 0) { updatable = true; }
  32077. var vb = this.getVertexBuffer(kind);
  32078. if (!vb || vb.isUpdatable() === updatable) {
  32079. return;
  32080. }
  32081. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32082. };
  32083. /**
  32084. * Sets the mesh VertexBuffer.
  32085. * Returns the Mesh.
  32086. */
  32087. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32088. if (!this._geometry) {
  32089. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32090. }
  32091. this._geometry.setVerticesBuffer(buffer);
  32092. return this;
  32093. };
  32094. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32095. if (!this._geometry) {
  32096. return this;
  32097. }
  32098. if (!makeItUnique) {
  32099. this._geometry.updateVerticesData(kind, data, updateExtends);
  32100. }
  32101. else {
  32102. this.makeGeometryUnique();
  32103. this.updateVerticesData(kind, data, updateExtends, false);
  32104. }
  32105. return this;
  32106. };
  32107. /**
  32108. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32109. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32110. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32111. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32112. * Returns the Mesh.
  32113. */
  32114. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32115. if (computeNormals === void 0) { computeNormals = true; }
  32116. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32117. if (!positions) {
  32118. return this;
  32119. }
  32120. positionFunction(positions);
  32121. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32122. if (computeNormals) {
  32123. var indices = this.getIndices();
  32124. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32125. if (!normals) {
  32126. return this;
  32127. }
  32128. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32129. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32130. }
  32131. return this;
  32132. };
  32133. /**
  32134. * Creates a un-shared specific occurence of the geometry for the mesh.
  32135. * Returns the Mesh.
  32136. */
  32137. Mesh.prototype.makeGeometryUnique = function () {
  32138. if (!this._geometry) {
  32139. return this;
  32140. }
  32141. var oldGeometry = this._geometry;
  32142. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32143. oldGeometry.releaseForMesh(this, true);
  32144. geometry.applyToMesh(this);
  32145. return this;
  32146. };
  32147. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32148. if (totalVertices === void 0) { totalVertices = null; }
  32149. if (updatable === void 0) { updatable = false; }
  32150. if (!this._geometry) {
  32151. var vertexData = new BABYLON.VertexData();
  32152. vertexData.indices = indices;
  32153. var scene = this.getScene();
  32154. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32155. }
  32156. else {
  32157. this._geometry.setIndices(indices, totalVertices, updatable);
  32158. }
  32159. return this;
  32160. };
  32161. /**
  32162. * Update the current index buffer
  32163. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32164. * Returns the Mesh.
  32165. */
  32166. Mesh.prototype.updateIndices = function (indices, offset) {
  32167. if (!this._geometry) {
  32168. return this;
  32169. }
  32170. this._geometry.updateIndices(indices, offset);
  32171. return this;
  32172. };
  32173. /**
  32174. * Invert the geometry to move from a right handed system to a left handed one.
  32175. * Returns the Mesh.
  32176. */
  32177. Mesh.prototype.toLeftHanded = function () {
  32178. if (!this._geometry) {
  32179. return this;
  32180. }
  32181. this._geometry.toLeftHanded();
  32182. return this;
  32183. };
  32184. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32185. if (!this._geometry) {
  32186. return this;
  32187. }
  32188. var engine = this.getScene().getEngine();
  32189. // Wireframe
  32190. var indexToBind;
  32191. if (this._unIndexed) {
  32192. indexToBind = null;
  32193. }
  32194. else {
  32195. switch (fillMode) {
  32196. case BABYLON.Material.PointFillMode:
  32197. indexToBind = null;
  32198. break;
  32199. case BABYLON.Material.WireFrameFillMode:
  32200. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32201. break;
  32202. default:
  32203. case BABYLON.Material.TriangleFillMode:
  32204. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32205. break;
  32206. }
  32207. }
  32208. // VBOs
  32209. this._geometry._bind(effect, indexToBind);
  32210. return this;
  32211. };
  32212. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32213. if (alternate === void 0) { alternate = false; }
  32214. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32215. return this;
  32216. }
  32217. this.onBeforeDrawObservable.notifyObservers(this);
  32218. var scene = this.getScene();
  32219. var engine = scene.getEngine();
  32220. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32221. // or triangles as points
  32222. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32223. }
  32224. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32225. // Triangles as wireframe
  32226. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32227. }
  32228. else {
  32229. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32230. }
  32231. if (scene._isAlternateRenderingEnabled && !alternate) {
  32232. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32233. if (!effect || !scene.activeCamera) {
  32234. return this;
  32235. }
  32236. scene._switchToAlternateCameraConfiguration(true);
  32237. this._effectiveMaterial.bindView(effect);
  32238. this._effectiveMaterial.bindViewProjection(effect);
  32239. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32240. this._draw(subMesh, fillMode, instancesCount, true);
  32241. engine.setViewport(scene.activeCamera.viewport);
  32242. scene._switchToAlternateCameraConfiguration(false);
  32243. this._effectiveMaterial.bindView(effect);
  32244. this._effectiveMaterial.bindViewProjection(effect);
  32245. }
  32246. return this;
  32247. };
  32248. /**
  32249. * Registers for this mesh a javascript function called just before the rendering process.
  32250. * This function is passed the current mesh.
  32251. * Return the Mesh.
  32252. */
  32253. Mesh.prototype.registerBeforeRender = function (func) {
  32254. this.onBeforeRenderObservable.add(func);
  32255. return this;
  32256. };
  32257. /**
  32258. * Disposes a previously registered javascript function called before the rendering.
  32259. * This function is passed the current mesh.
  32260. * Returns the Mesh.
  32261. */
  32262. Mesh.prototype.unregisterBeforeRender = function (func) {
  32263. this.onBeforeRenderObservable.removeCallback(func);
  32264. return this;
  32265. };
  32266. /**
  32267. * Registers for this mesh a javascript function called just after the rendering is complete.
  32268. * This function is passed the current mesh.
  32269. * Returns the Mesh.
  32270. */
  32271. Mesh.prototype.registerAfterRender = function (func) {
  32272. this.onAfterRenderObservable.add(func);
  32273. return this;
  32274. };
  32275. /**
  32276. * Disposes a previously registered javascript function called after the rendering.
  32277. * This function is passed the current mesh.
  32278. * Return the Mesh.
  32279. */
  32280. Mesh.prototype.unregisterAfterRender = function (func) {
  32281. this.onAfterRenderObservable.removeCallback(func);
  32282. return this;
  32283. };
  32284. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32285. var scene = this.getScene();
  32286. this._batchCache.mustReturn = false;
  32287. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32288. this._batchCache.visibleInstances[subMeshId] = null;
  32289. if (this._visibleInstances) {
  32290. var currentRenderId = scene.getRenderId();
  32291. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32292. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32293. var selfRenderId = this._renderId;
  32294. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32295. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32296. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32297. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32298. }
  32299. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32300. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32301. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32302. this._batchCache.mustReturn = true;
  32303. return this._batchCache;
  32304. }
  32305. if (currentRenderId !== selfRenderId) {
  32306. this._batchCache.renderSelf[subMeshId] = false;
  32307. }
  32308. }
  32309. this._renderIdForInstances[subMeshId] = currentRenderId;
  32310. }
  32311. return this._batchCache;
  32312. };
  32313. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32314. var visibleInstances = batch.visibleInstances[subMesh._id];
  32315. if (!visibleInstances) {
  32316. return this;
  32317. }
  32318. var matricesCount = visibleInstances.length + 1;
  32319. var bufferSize = matricesCount * 16 * 4;
  32320. var currentInstancesBufferSize = this._instancesBufferSize;
  32321. var instancesBuffer = this._instancesBuffer;
  32322. while (this._instancesBufferSize < bufferSize) {
  32323. this._instancesBufferSize *= 2;
  32324. }
  32325. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32326. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32327. }
  32328. var offset = 0;
  32329. var instancesCount = 0;
  32330. var world = this.getWorldMatrix();
  32331. if (batch.renderSelf[subMesh._id]) {
  32332. world.copyToArray(this._instancesData, offset);
  32333. offset += 16;
  32334. instancesCount++;
  32335. }
  32336. if (visibleInstances) {
  32337. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32338. var instance = visibleInstances[instanceIndex];
  32339. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32340. offset += 16;
  32341. instancesCount++;
  32342. }
  32343. }
  32344. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32345. if (instancesBuffer) {
  32346. instancesBuffer.dispose();
  32347. }
  32348. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32349. this._instancesBuffer = instancesBuffer;
  32350. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32351. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32352. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32353. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32354. }
  32355. else {
  32356. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32357. }
  32358. this._bind(subMesh, effect, fillMode);
  32359. this._draw(subMesh, fillMode, instancesCount);
  32360. engine.unbindInstanceAttributes();
  32361. return this;
  32362. };
  32363. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32364. var scene = this.getScene();
  32365. var engine = scene.getEngine();
  32366. if (hardwareInstancedRendering) {
  32367. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32368. }
  32369. else {
  32370. if (batch.renderSelf[subMesh._id]) {
  32371. // Draw
  32372. if (onBeforeDraw) {
  32373. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32374. }
  32375. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32376. }
  32377. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32378. if (visibleInstancesForSubMesh) {
  32379. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32380. var instance = visibleInstancesForSubMesh[instanceIndex];
  32381. // World
  32382. var world = instance.getWorldMatrix();
  32383. if (onBeforeDraw) {
  32384. onBeforeDraw(true, world, effectiveMaterial);
  32385. }
  32386. // Draw
  32387. this._draw(subMesh, fillMode);
  32388. }
  32389. }
  32390. }
  32391. return this;
  32392. };
  32393. /**
  32394. * Triggers the draw call for the mesh.
  32395. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32396. * Returns the Mesh.
  32397. */
  32398. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32399. this._checkOcclusionQuery();
  32400. if (this._isOccluded) {
  32401. return this;
  32402. }
  32403. var scene = this.getScene();
  32404. // Managing instances
  32405. var batch = this._getInstancesRenderList(subMesh._id);
  32406. if (batch.mustReturn) {
  32407. return this;
  32408. }
  32409. // Checking geometry state
  32410. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32411. return this;
  32412. }
  32413. this.onBeforeRenderObservable.notifyObservers(this);
  32414. var engine = scene.getEngine();
  32415. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32416. // Material
  32417. var material = subMesh.getMaterial();
  32418. if (!material) {
  32419. return this;
  32420. }
  32421. this._effectiveMaterial = material;
  32422. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32423. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32424. return this;
  32425. }
  32426. }
  32427. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32428. return this;
  32429. }
  32430. // Alpha mode
  32431. if (enableAlphaMode) {
  32432. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32433. }
  32434. // Outline - step 1
  32435. var savedDepthWrite = engine.getDepthWrite();
  32436. if (this.renderOutline) {
  32437. engine.setDepthWrite(false);
  32438. scene.getOutlineRenderer().render(subMesh, batch);
  32439. engine.setDepthWrite(savedDepthWrite);
  32440. }
  32441. var effect;
  32442. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32443. effect = subMesh.effect;
  32444. }
  32445. else {
  32446. effect = this._effectiveMaterial.getEffect();
  32447. }
  32448. if (!effect) {
  32449. return this;
  32450. }
  32451. var sideOrientation = this.overrideMaterialSideOrientation;
  32452. if (sideOrientation == null) {
  32453. sideOrientation = this._effectiveMaterial.sideOrientation;
  32454. if (this._getWorldMatrixDeterminant() < 0) {
  32455. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32456. }
  32457. }
  32458. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32459. if (this._effectiveMaterial.forceDepthWrite) {
  32460. engine.setDepthWrite(true);
  32461. }
  32462. // Bind
  32463. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32464. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32465. this._bind(subMesh, effect, fillMode);
  32466. }
  32467. var world = this.getWorldMatrix();
  32468. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32469. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32470. }
  32471. else {
  32472. this._effectiveMaterial.bind(world, this);
  32473. }
  32474. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32475. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32476. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32477. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32478. }
  32479. // Draw
  32480. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32481. // Unbind
  32482. this._effectiveMaterial.unbind();
  32483. // Outline - step 2
  32484. if (this.renderOutline && savedDepthWrite) {
  32485. engine.setDepthWrite(true);
  32486. engine.setColorWrite(false);
  32487. scene.getOutlineRenderer().render(subMesh, batch);
  32488. engine.setColorWrite(true);
  32489. }
  32490. // Overlay
  32491. if (this.renderOverlay) {
  32492. var currentMode = engine.getAlphaMode();
  32493. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32494. scene.getOutlineRenderer().render(subMesh, batch, true);
  32495. engine.setAlphaMode(currentMode);
  32496. }
  32497. this.onAfterRenderObservable.notifyObservers(this);
  32498. return this;
  32499. };
  32500. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32501. if (isInstance && effectiveMaterial) {
  32502. effectiveMaterial.bindOnlyWorldMatrix(world);
  32503. }
  32504. };
  32505. /**
  32506. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32507. */
  32508. Mesh.prototype.getEmittedParticleSystems = function () {
  32509. var results = new Array();
  32510. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32511. var particleSystem = this.getScene().particleSystems[index];
  32512. if (particleSystem.emitter === this) {
  32513. results.push(particleSystem);
  32514. }
  32515. }
  32516. return results;
  32517. };
  32518. /**
  32519. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32520. */
  32521. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32522. var results = new Array();
  32523. var descendants = this.getDescendants();
  32524. descendants.push(this);
  32525. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32526. var particleSystem = this.getScene().particleSystems[index];
  32527. var emitter = particleSystem.emitter;
  32528. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32529. results.push(particleSystem);
  32530. }
  32531. }
  32532. return results;
  32533. };
  32534. /**
  32535. * Normalize matrix weights so that all vertices have a total weight set to 1
  32536. */
  32537. Mesh.prototype.cleanMatrixWeights = function () {
  32538. var epsilon = 1e-3;
  32539. var noInfluenceBoneIndex = 0.0;
  32540. if (this.skeleton) {
  32541. noInfluenceBoneIndex = this.skeleton.bones.length;
  32542. }
  32543. else {
  32544. return;
  32545. }
  32546. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32547. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32548. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32549. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32550. var influencers = this.numBoneInfluencers;
  32551. var size = matricesWeights.length;
  32552. for (var i = 0; i < size; i += 4) {
  32553. var weight = 0.0;
  32554. var firstZeroWeight = -1;
  32555. for (var j = 0; j < 4; j++) {
  32556. var w = matricesWeights[i + j];
  32557. weight += w;
  32558. if (w < epsilon && firstZeroWeight < 0) {
  32559. firstZeroWeight = j;
  32560. }
  32561. }
  32562. if (matricesWeightsExtra) {
  32563. for (var j = 0; j < 4; j++) {
  32564. var w = matricesWeightsExtra[i + j];
  32565. weight += w;
  32566. if (w < epsilon && firstZeroWeight < 0) {
  32567. firstZeroWeight = j + 4;
  32568. }
  32569. }
  32570. }
  32571. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32572. firstZeroWeight = influencers - 1;
  32573. }
  32574. if (weight > epsilon) {
  32575. var mweight = 1.0 / weight;
  32576. for (var j = 0; j < 4; j++) {
  32577. matricesWeights[i + j] *= mweight;
  32578. }
  32579. if (matricesWeightsExtra) {
  32580. for (var j = 0; j < 4; j++) {
  32581. matricesWeightsExtra[i + j] *= mweight;
  32582. }
  32583. }
  32584. }
  32585. else {
  32586. if (firstZeroWeight >= 4) {
  32587. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32588. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32589. }
  32590. else {
  32591. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32592. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32593. }
  32594. }
  32595. }
  32596. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32597. if (matricesIndicesExtra) {
  32598. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32599. }
  32600. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32601. if (matricesWeightsExtra) {
  32602. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32603. }
  32604. };
  32605. Mesh.prototype._checkDelayState = function () {
  32606. var scene = this.getScene();
  32607. if (this._geometry) {
  32608. this._geometry.load(scene);
  32609. }
  32610. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32611. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32612. this._queueLoad(scene);
  32613. }
  32614. return this;
  32615. };
  32616. Mesh.prototype._queueLoad = function (scene) {
  32617. var _this = this;
  32618. scene._addPendingData(this);
  32619. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32620. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32621. if (data instanceof ArrayBuffer) {
  32622. _this._delayLoadingFunction(data, _this);
  32623. }
  32624. else {
  32625. _this._delayLoadingFunction(JSON.parse(data), _this);
  32626. }
  32627. _this.instances.forEach(function (instance) {
  32628. instance._syncSubMeshes();
  32629. });
  32630. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32631. scene._removePendingData(_this);
  32632. }, function () { }, scene.database, getBinaryData);
  32633. return this;
  32634. };
  32635. /**
  32636. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32637. */
  32638. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32639. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32640. return false;
  32641. }
  32642. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32643. return false;
  32644. }
  32645. this._checkDelayState();
  32646. return true;
  32647. };
  32648. /**
  32649. * Sets the mesh material by the material or multiMaterial `id` property.
  32650. * The material `id` is a string identifying the material or the multiMaterial.
  32651. * This method returns the Mesh.
  32652. */
  32653. Mesh.prototype.setMaterialByID = function (id) {
  32654. var materials = this.getScene().materials;
  32655. var index;
  32656. for (index = materials.length - 1; index > -1; index--) {
  32657. if (materials[index].id === id) {
  32658. this.material = materials[index];
  32659. return this;
  32660. }
  32661. }
  32662. // Multi
  32663. var multiMaterials = this.getScene().multiMaterials;
  32664. for (index = multiMaterials.length - 1; index > -1; index--) {
  32665. if (multiMaterials[index].id === id) {
  32666. this.material = multiMaterials[index];
  32667. return this;
  32668. }
  32669. }
  32670. return this;
  32671. };
  32672. /**
  32673. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32674. */
  32675. Mesh.prototype.getAnimatables = function () {
  32676. var results = new Array();
  32677. if (this.material) {
  32678. results.push(this.material);
  32679. }
  32680. if (this.skeleton) {
  32681. results.push(this.skeleton);
  32682. }
  32683. return results;
  32684. };
  32685. /**
  32686. * Modifies the mesh geometry according to the passed transformation matrix.
  32687. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32688. * The mesh normals are modified accordingly the same transformation.
  32689. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32690. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32691. * Returns the Mesh.
  32692. */
  32693. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32694. // Position
  32695. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32696. return this;
  32697. }
  32698. var submeshes = this.subMeshes.splice(0);
  32699. this._resetPointsArrayCache();
  32700. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32701. var temp = new Array();
  32702. var index;
  32703. for (index = 0; index < data.length; index += 3) {
  32704. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32705. }
  32706. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32707. // Normals
  32708. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32709. return this;
  32710. }
  32711. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32712. temp = [];
  32713. for (index = 0; index < data.length; index += 3) {
  32714. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32715. }
  32716. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32717. // flip faces?
  32718. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32719. this.flipFaces();
  32720. }
  32721. // Restore submeshes
  32722. this.releaseSubMeshes();
  32723. this.subMeshes = submeshes;
  32724. return this;
  32725. };
  32726. /**
  32727. * Modifies the mesh geometry according to its own current World Matrix.
  32728. * The mesh World Matrix is then reset.
  32729. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32730. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32731. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32732. * Returns the Mesh.
  32733. */
  32734. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32735. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32736. this.scaling.copyFromFloats(1, 1, 1);
  32737. this.position.copyFromFloats(0, 0, 0);
  32738. this.rotation.copyFromFloats(0, 0, 0);
  32739. //only if quaternion is already set
  32740. if (this.rotationQuaternion) {
  32741. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32742. }
  32743. this._worldMatrix = BABYLON.Matrix.Identity();
  32744. return this;
  32745. };
  32746. Object.defineProperty(Mesh.prototype, "_positions", {
  32747. // Cache
  32748. get: function () {
  32749. if (this._geometry) {
  32750. return this._geometry._positions;
  32751. }
  32752. return null;
  32753. },
  32754. enumerable: true,
  32755. configurable: true
  32756. });
  32757. Mesh.prototype._resetPointsArrayCache = function () {
  32758. if (this._geometry) {
  32759. this._geometry._resetPointsArrayCache();
  32760. }
  32761. return this;
  32762. };
  32763. Mesh.prototype._generatePointsArray = function () {
  32764. if (this._geometry) {
  32765. return this._geometry._generatePointsArray();
  32766. }
  32767. return false;
  32768. };
  32769. /**
  32770. * Returns a new Mesh object generated from the current mesh properties.
  32771. * This method must not get confused with createInstance().
  32772. * The parameter `name` is a string, the name given to the new mesh.
  32773. * The optional parameter `newParent` can be any Node object (default `null`).
  32774. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32775. * 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.
  32776. */
  32777. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32778. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32779. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32780. };
  32781. /**
  32782. * Releases resources associated with this mesh.
  32783. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32784. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32785. */
  32786. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32787. var _this = this;
  32788. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32789. this.morphTargetManager = null;
  32790. if (this._geometry) {
  32791. this._geometry.releaseForMesh(this, true);
  32792. }
  32793. // Sources
  32794. var meshes = this.getScene().meshes;
  32795. meshes.forEach(function (abstractMesh) {
  32796. var mesh = abstractMesh;
  32797. if (mesh._source && mesh._source === _this) {
  32798. mesh._source = null;
  32799. }
  32800. });
  32801. this._source = null;
  32802. // Instances
  32803. if (this._instancesBuffer) {
  32804. this._instancesBuffer.dispose();
  32805. this._instancesBuffer = null;
  32806. }
  32807. while (this.instances.length) {
  32808. this.instances[0].dispose();
  32809. }
  32810. // Effect layers.
  32811. var effectLayers = this.getScene().effectLayers;
  32812. for (var i = 0; i < effectLayers.length; i++) {
  32813. var effectLayer = effectLayers[i];
  32814. if (effectLayer) {
  32815. effectLayer._disposeMesh(this);
  32816. }
  32817. }
  32818. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32819. };
  32820. /**
  32821. * Modifies the mesh geometry according to a displacement map.
  32822. * 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.
  32823. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32824. * This method returns nothing.
  32825. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32826. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32827. * 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.
  32828. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32829. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32830. *
  32831. * Returns the Mesh.
  32832. */
  32833. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32834. var _this = this;
  32835. var scene = this.getScene();
  32836. var onload = function (img) {
  32837. // Getting height map data
  32838. var canvas = document.createElement("canvas");
  32839. var context = canvas.getContext("2d");
  32840. var heightMapWidth = img.width;
  32841. var heightMapHeight = img.height;
  32842. canvas.width = heightMapWidth;
  32843. canvas.height = heightMapHeight;
  32844. context.drawImage(img, 0, 0);
  32845. // Create VertexData from map data
  32846. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32847. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32848. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32849. //execute success callback, if set
  32850. if (onSuccess) {
  32851. onSuccess(_this);
  32852. }
  32853. };
  32854. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32855. return this;
  32856. };
  32857. /**
  32858. * Modifies the mesh geometry according to a displacementMap buffer.
  32859. * 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.
  32860. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32861. * This method returns nothing.
  32862. * 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.
  32863. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32864. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32865. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32866. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32867. *
  32868. * Returns the Mesh.
  32869. */
  32870. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32871. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32872. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32873. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32874. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32875. return this;
  32876. }
  32877. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32878. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32879. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32880. var position = BABYLON.Vector3.Zero();
  32881. var normal = BABYLON.Vector3.Zero();
  32882. var uv = BABYLON.Vector2.Zero();
  32883. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32884. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32885. for (var index = 0; index < positions.length; index += 3) {
  32886. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32887. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32888. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32889. // Compute height
  32890. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32891. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32892. var pos = (u + v * heightMapWidth) * 4;
  32893. var r = buffer[pos] / 255.0;
  32894. var g = buffer[pos + 1] / 255.0;
  32895. var b = buffer[pos + 2] / 255.0;
  32896. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32897. normal.normalize();
  32898. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32899. position = position.add(normal);
  32900. position.toArray(positions, index);
  32901. }
  32902. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32903. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32904. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32905. return this;
  32906. };
  32907. /**
  32908. * Modify the mesh to get a flat shading rendering.
  32909. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32910. * This method returns the Mesh.
  32911. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32912. */
  32913. Mesh.prototype.convertToFlatShadedMesh = function () {
  32914. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32915. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32916. var kinds = this.getVerticesDataKinds();
  32917. var vbs = {};
  32918. var data = {};
  32919. var newdata = {};
  32920. var updatableNormals = false;
  32921. var kindIndex;
  32922. var kind;
  32923. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32924. kind = kinds[kindIndex];
  32925. var vertexBuffer = this.getVertexBuffer(kind);
  32926. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32927. updatableNormals = vertexBuffer.isUpdatable();
  32928. kinds.splice(kindIndex, 1);
  32929. kindIndex--;
  32930. continue;
  32931. }
  32932. vbs[kind] = vertexBuffer;
  32933. data[kind] = vbs[kind].getData();
  32934. newdata[kind] = [];
  32935. }
  32936. // Save previous submeshes
  32937. var previousSubmeshes = this.subMeshes.slice(0);
  32938. var indices = this.getIndices();
  32939. var totalIndices = this.getTotalIndices();
  32940. // Generating unique vertices per face
  32941. var index;
  32942. for (index = 0; index < totalIndices; index++) {
  32943. var vertexIndex = indices[index];
  32944. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32945. kind = kinds[kindIndex];
  32946. var stride = vbs[kind].getStrideSize();
  32947. for (var offset = 0; offset < stride; offset++) {
  32948. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32949. }
  32950. }
  32951. }
  32952. // Updating faces & normal
  32953. var normals = [];
  32954. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32955. for (index = 0; index < totalIndices; index += 3) {
  32956. indices[index] = index;
  32957. indices[index + 1] = index + 1;
  32958. indices[index + 2] = index + 2;
  32959. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32960. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32961. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32962. var p1p2 = p1.subtract(p2);
  32963. var p3p2 = p3.subtract(p2);
  32964. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32965. // Store same normals for every vertex
  32966. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32967. normals.push(normal.x);
  32968. normals.push(normal.y);
  32969. normals.push(normal.z);
  32970. }
  32971. }
  32972. this.setIndices(indices);
  32973. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32974. // Updating vertex buffers
  32975. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32976. kind = kinds[kindIndex];
  32977. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32978. }
  32979. // Updating submeshes
  32980. this.releaseSubMeshes();
  32981. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32982. var previousOne = previousSubmeshes[submeshIndex];
  32983. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32984. }
  32985. this.synchronizeInstances();
  32986. return this;
  32987. };
  32988. /**
  32989. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32990. * In other words, more vertices, no more indices and a single bigger VBO.
  32991. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32992. * Returns the Mesh.
  32993. */
  32994. Mesh.prototype.convertToUnIndexedMesh = function () {
  32995. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32996. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32997. var kinds = this.getVerticesDataKinds();
  32998. var vbs = {};
  32999. var data = {};
  33000. var newdata = {};
  33001. var kindIndex;
  33002. var kind;
  33003. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33004. kind = kinds[kindIndex];
  33005. var vertexBuffer = this.getVertexBuffer(kind);
  33006. vbs[kind] = vertexBuffer;
  33007. data[kind] = vbs[kind].getData();
  33008. newdata[kind] = [];
  33009. }
  33010. // Save previous submeshes
  33011. var previousSubmeshes = this.subMeshes.slice(0);
  33012. var indices = this.getIndices();
  33013. var totalIndices = this.getTotalIndices();
  33014. // Generating unique vertices per face
  33015. var index;
  33016. for (index = 0; index < totalIndices; index++) {
  33017. var vertexIndex = indices[index];
  33018. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33019. kind = kinds[kindIndex];
  33020. var stride = vbs[kind].getStrideSize();
  33021. for (var offset = 0; offset < stride; offset++) {
  33022. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33023. }
  33024. }
  33025. }
  33026. // Updating indices
  33027. for (index = 0; index < totalIndices; index += 3) {
  33028. indices[index] = index;
  33029. indices[index + 1] = index + 1;
  33030. indices[index + 2] = index + 2;
  33031. }
  33032. this.setIndices(indices);
  33033. // Updating vertex buffers
  33034. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33035. kind = kinds[kindIndex];
  33036. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33037. }
  33038. // Updating submeshes
  33039. this.releaseSubMeshes();
  33040. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33041. var previousOne = previousSubmeshes[submeshIndex];
  33042. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33043. }
  33044. this._unIndexed = true;
  33045. this.synchronizeInstances();
  33046. return this;
  33047. };
  33048. /**
  33049. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33050. * This method returns the Mesh.
  33051. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33052. */
  33053. Mesh.prototype.flipFaces = function (flipNormals) {
  33054. if (flipNormals === void 0) { flipNormals = false; }
  33055. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33056. var i;
  33057. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33058. for (i = 0; i < vertex_data.normals.length; i++) {
  33059. vertex_data.normals[i] *= -1;
  33060. }
  33061. }
  33062. if (vertex_data.indices) {
  33063. var temp;
  33064. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33065. // reassign indices
  33066. temp = vertex_data.indices[i + 1];
  33067. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33068. vertex_data.indices[i + 2] = temp;
  33069. }
  33070. }
  33071. vertex_data.applyToMesh(this);
  33072. return this;
  33073. };
  33074. // Instances
  33075. /**
  33076. * Creates a new InstancedMesh object from the mesh model.
  33077. * An instance shares the same properties and the same material than its model.
  33078. * Only these properties of each instance can then be set individually :
  33079. * - position
  33080. * - rotation
  33081. * - rotationQuaternion
  33082. * - setPivotMatrix
  33083. * - scaling
  33084. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33085. * Warning : this method is not supported for Line mesh and LineSystem
  33086. */
  33087. Mesh.prototype.createInstance = function (name) {
  33088. return new BABYLON.InstancedMesh(name, this);
  33089. };
  33090. /**
  33091. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33092. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33093. * This method returns the Mesh.
  33094. */
  33095. Mesh.prototype.synchronizeInstances = function () {
  33096. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33097. var instance = this.instances[instanceIndex];
  33098. instance._syncSubMeshes();
  33099. }
  33100. return this;
  33101. };
  33102. /**
  33103. * Simplify the mesh according to the given array of settings.
  33104. * Function will return immediately and will simplify async. It returns the Mesh.
  33105. * @param settings a collection of simplification settings.
  33106. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33107. * @param type the type of simplification to run.
  33108. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33109. */
  33110. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33111. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33112. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33113. this.getScene().simplificationQueue.addTask({
  33114. settings: settings,
  33115. parallelProcessing: parallelProcessing,
  33116. mesh: this,
  33117. simplificationType: simplificationType,
  33118. successCallback: successCallback
  33119. });
  33120. return this;
  33121. };
  33122. /**
  33123. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33124. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33125. * This should be used together with the simplification to avoid disappearing triangles.
  33126. * Returns the Mesh.
  33127. * @param successCallback an optional success callback to be called after the optimization finished.
  33128. */
  33129. Mesh.prototype.optimizeIndices = function (successCallback) {
  33130. var _this = this;
  33131. var indices = this.getIndices();
  33132. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33133. if (!positions || !indices) {
  33134. return this;
  33135. }
  33136. var vectorPositions = new Array();
  33137. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33138. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33139. }
  33140. var dupes = new Array();
  33141. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33142. var realPos = vectorPositions.length - 1 - iteration;
  33143. var testedPosition = vectorPositions[realPos];
  33144. for (var j = 0; j < realPos; ++j) {
  33145. var againstPosition = vectorPositions[j];
  33146. if (testedPosition.equals(againstPosition)) {
  33147. dupes[realPos] = j;
  33148. break;
  33149. }
  33150. }
  33151. }, function () {
  33152. for (var i = 0; i < indices.length; ++i) {
  33153. indices[i] = dupes[indices[i]] || indices[i];
  33154. }
  33155. //indices are now reordered
  33156. var originalSubMeshes = _this.subMeshes.slice(0);
  33157. _this.setIndices(indices);
  33158. _this.subMeshes = originalSubMeshes;
  33159. if (successCallback) {
  33160. successCallback(_this);
  33161. }
  33162. });
  33163. return this;
  33164. };
  33165. Mesh.prototype.serialize = function (serializationObject) {
  33166. serializationObject.name = this.name;
  33167. serializationObject.id = this.id;
  33168. serializationObject.type = this.getClassName();
  33169. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33170. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33171. }
  33172. serializationObject.position = this.position.asArray();
  33173. if (this.rotationQuaternion) {
  33174. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33175. }
  33176. else if (this.rotation) {
  33177. serializationObject.rotation = this.rotation.asArray();
  33178. }
  33179. serializationObject.scaling = this.scaling.asArray();
  33180. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33181. serializationObject.isEnabled = this.isEnabled(false);
  33182. serializationObject.isVisible = this.isVisible;
  33183. serializationObject.infiniteDistance = this.infiniteDistance;
  33184. serializationObject.pickable = this.isPickable;
  33185. serializationObject.receiveShadows = this.receiveShadows;
  33186. serializationObject.billboardMode = this.billboardMode;
  33187. serializationObject.visibility = this.visibility;
  33188. serializationObject.checkCollisions = this.checkCollisions;
  33189. serializationObject.isBlocker = this.isBlocker;
  33190. // Parent
  33191. if (this.parent) {
  33192. serializationObject.parentId = this.parent.id;
  33193. }
  33194. // Geometry
  33195. serializationObject.isUnIndexed = this.isUnIndexed;
  33196. var geometry = this._geometry;
  33197. if (geometry) {
  33198. var geometryId = geometry.id;
  33199. serializationObject.geometryId = geometryId;
  33200. // SubMeshes
  33201. serializationObject.subMeshes = [];
  33202. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33203. var subMesh = this.subMeshes[subIndex];
  33204. serializationObject.subMeshes.push({
  33205. materialIndex: subMesh.materialIndex,
  33206. verticesStart: subMesh.verticesStart,
  33207. verticesCount: subMesh.verticesCount,
  33208. indexStart: subMesh.indexStart,
  33209. indexCount: subMesh.indexCount
  33210. });
  33211. }
  33212. }
  33213. // Material
  33214. if (this.material) {
  33215. serializationObject.materialId = this.material.id;
  33216. }
  33217. else {
  33218. this.material = null;
  33219. }
  33220. // Morph targets
  33221. if (this.morphTargetManager) {
  33222. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33223. }
  33224. // Skeleton
  33225. if (this.skeleton) {
  33226. serializationObject.skeletonId = this.skeleton.id;
  33227. }
  33228. // Physics
  33229. //TODO implement correct serialization for physics impostors.
  33230. var impostor = this.getPhysicsImpostor();
  33231. if (impostor) {
  33232. serializationObject.physicsMass = impostor.getParam("mass");
  33233. serializationObject.physicsFriction = impostor.getParam("friction");
  33234. serializationObject.physicsRestitution = impostor.getParam("mass");
  33235. serializationObject.physicsImpostor = impostor.type;
  33236. }
  33237. // Metadata
  33238. if (this.metadata) {
  33239. serializationObject.metadata = this.metadata;
  33240. }
  33241. // Instances
  33242. serializationObject.instances = [];
  33243. for (var index = 0; index < this.instances.length; index++) {
  33244. var instance = this.instances[index];
  33245. var serializationInstance = {
  33246. name: instance.name,
  33247. id: instance.id,
  33248. position: instance.position.asArray(),
  33249. scaling: instance.scaling.asArray()
  33250. };
  33251. if (instance.rotationQuaternion) {
  33252. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33253. }
  33254. else if (instance.rotation) {
  33255. serializationInstance.rotation = instance.rotation.asArray();
  33256. }
  33257. serializationObject.instances.push(serializationInstance);
  33258. // Animations
  33259. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33260. serializationInstance.ranges = instance.serializeAnimationRanges();
  33261. }
  33262. //
  33263. // Animations
  33264. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33265. serializationObject.ranges = this.serializeAnimationRanges();
  33266. // Layer mask
  33267. serializationObject.layerMask = this.layerMask;
  33268. // Alpha
  33269. serializationObject.alphaIndex = this.alphaIndex;
  33270. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33271. // Overlay
  33272. serializationObject.overlayAlpha = this.overlayAlpha;
  33273. serializationObject.overlayColor = this.overlayColor.asArray();
  33274. serializationObject.renderOverlay = this.renderOverlay;
  33275. // Fog
  33276. serializationObject.applyFog = this.applyFog;
  33277. // Action Manager
  33278. if (this.actionManager) {
  33279. serializationObject.actions = this.actionManager.serialize(this.name);
  33280. }
  33281. };
  33282. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33283. if (!this.geometry) {
  33284. return;
  33285. }
  33286. this._markSubMeshesAsAttributesDirty();
  33287. var morphTargetManager = this._morphTargetManager;
  33288. if (morphTargetManager && morphTargetManager.vertexCount) {
  33289. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33290. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33291. this.morphTargetManager = null;
  33292. return;
  33293. }
  33294. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33295. var morphTarget = morphTargetManager.getActiveTarget(index);
  33296. var positions = morphTarget.getPositions();
  33297. if (!positions) {
  33298. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33299. return;
  33300. }
  33301. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33302. var normals = morphTarget.getNormals();
  33303. if (normals) {
  33304. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33305. }
  33306. var tangents = morphTarget.getTangents();
  33307. if (tangents) {
  33308. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33309. }
  33310. }
  33311. }
  33312. else {
  33313. var index = 0;
  33314. // Positions
  33315. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33316. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33317. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33318. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33319. }
  33320. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33321. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33322. }
  33323. index++;
  33324. }
  33325. }
  33326. };
  33327. // Statics
  33328. /**
  33329. * Returns a new Mesh object parsed from the source provided.
  33330. * The parameter `parsedMesh` is the source.
  33331. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33332. */
  33333. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33334. var mesh;
  33335. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33336. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33337. }
  33338. else {
  33339. mesh = new Mesh(parsedMesh.name, scene);
  33340. }
  33341. mesh.id = parsedMesh.id;
  33342. if (BABYLON.Tags) {
  33343. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33344. }
  33345. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33346. if (parsedMesh.metadata !== undefined) {
  33347. mesh.metadata = parsedMesh.metadata;
  33348. }
  33349. if (parsedMesh.rotationQuaternion) {
  33350. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33351. }
  33352. else if (parsedMesh.rotation) {
  33353. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33354. }
  33355. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33356. if (parsedMesh.localMatrix) {
  33357. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33358. }
  33359. else if (parsedMesh.pivotMatrix) {
  33360. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33361. }
  33362. mesh.setEnabled(parsedMesh.isEnabled);
  33363. mesh.isVisible = parsedMesh.isVisible;
  33364. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33365. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33366. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33367. if (parsedMesh.applyFog !== undefined) {
  33368. mesh.applyFog = parsedMesh.applyFog;
  33369. }
  33370. if (parsedMesh.pickable !== undefined) {
  33371. mesh.isPickable = parsedMesh.pickable;
  33372. }
  33373. if (parsedMesh.alphaIndex !== undefined) {
  33374. mesh.alphaIndex = parsedMesh.alphaIndex;
  33375. }
  33376. mesh.receiveShadows = parsedMesh.receiveShadows;
  33377. mesh.billboardMode = parsedMesh.billboardMode;
  33378. if (parsedMesh.visibility !== undefined) {
  33379. mesh.visibility = parsedMesh.visibility;
  33380. }
  33381. mesh.checkCollisions = parsedMesh.checkCollisions;
  33382. if (parsedMesh.isBlocker !== undefined) {
  33383. mesh.isBlocker = parsedMesh.isBlocker;
  33384. }
  33385. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33386. // freezeWorldMatrix
  33387. if (parsedMesh.freezeWorldMatrix) {
  33388. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33389. }
  33390. // Parent
  33391. if (parsedMesh.parentId) {
  33392. mesh._waitingParentId = parsedMesh.parentId;
  33393. }
  33394. // Actions
  33395. if (parsedMesh.actions !== undefined) {
  33396. mesh._waitingActions = parsedMesh.actions;
  33397. }
  33398. // Overlay
  33399. if (parsedMesh.overlayAlpha !== undefined) {
  33400. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33401. }
  33402. if (parsedMesh.overlayColor !== undefined) {
  33403. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33404. }
  33405. if (parsedMesh.renderOverlay !== undefined) {
  33406. mesh.renderOverlay = parsedMesh.renderOverlay;
  33407. }
  33408. // Geometry
  33409. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33410. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33411. if (parsedMesh.delayLoadingFile) {
  33412. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33413. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33414. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33415. if (parsedMesh._binaryInfo) {
  33416. mesh._binaryInfo = parsedMesh._binaryInfo;
  33417. }
  33418. mesh._delayInfo = [];
  33419. if (parsedMesh.hasUVs) {
  33420. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33421. }
  33422. if (parsedMesh.hasUVs2) {
  33423. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33424. }
  33425. if (parsedMesh.hasUVs3) {
  33426. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33427. }
  33428. if (parsedMesh.hasUVs4) {
  33429. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33430. }
  33431. if (parsedMesh.hasUVs5) {
  33432. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33433. }
  33434. if (parsedMesh.hasUVs6) {
  33435. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33436. }
  33437. if (parsedMesh.hasColors) {
  33438. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33439. }
  33440. if (parsedMesh.hasMatricesIndices) {
  33441. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33442. }
  33443. if (parsedMesh.hasMatricesWeights) {
  33444. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33445. }
  33446. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33447. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33448. mesh._checkDelayState();
  33449. }
  33450. }
  33451. else {
  33452. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33453. }
  33454. // Material
  33455. if (parsedMesh.materialId) {
  33456. mesh.setMaterialByID(parsedMesh.materialId);
  33457. }
  33458. else {
  33459. mesh.material = null;
  33460. }
  33461. // Morph targets
  33462. if (parsedMesh.morphTargetManagerId > -1) {
  33463. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33464. }
  33465. // Skeleton
  33466. if (parsedMesh.skeletonId > -1) {
  33467. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33468. if (parsedMesh.numBoneInfluencers) {
  33469. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33470. }
  33471. }
  33472. // Animations
  33473. if (parsedMesh.animations) {
  33474. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33475. var parsedAnimation = parsedMesh.animations[animationIndex];
  33476. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33477. }
  33478. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33479. }
  33480. if (parsedMesh.autoAnimate) {
  33481. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33482. }
  33483. // Layer Mask
  33484. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33485. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33486. }
  33487. else {
  33488. mesh.layerMask = 0x0FFFFFFF;
  33489. }
  33490. // Physics
  33491. if (parsedMesh.physicsImpostor) {
  33492. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33493. mass: parsedMesh.physicsMass,
  33494. friction: parsedMesh.physicsFriction,
  33495. restitution: parsedMesh.physicsRestitution
  33496. }, scene);
  33497. }
  33498. // Instances
  33499. if (parsedMesh.instances) {
  33500. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33501. var parsedInstance = parsedMesh.instances[index];
  33502. var instance = mesh.createInstance(parsedInstance.name);
  33503. if (parsedInstance.id) {
  33504. instance.id = parsedInstance.id;
  33505. }
  33506. if (BABYLON.Tags) {
  33507. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33508. }
  33509. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33510. if (parsedInstance.parentId) {
  33511. instance._waitingParentId = parsedInstance.parentId;
  33512. }
  33513. if (parsedInstance.rotationQuaternion) {
  33514. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33515. }
  33516. else if (parsedInstance.rotation) {
  33517. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33518. }
  33519. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33520. instance.checkCollisions = mesh.checkCollisions;
  33521. if (parsedMesh.animations) {
  33522. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33523. parsedAnimation = parsedMesh.animations[animationIndex];
  33524. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33525. }
  33526. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33527. }
  33528. }
  33529. }
  33530. return mesh;
  33531. };
  33532. /**
  33533. * Creates a ribbon mesh.
  33534. * Please consider using the same method from the MeshBuilder class instead.
  33535. * 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.
  33536. *
  33537. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33538. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33539. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33540. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33541. * 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.
  33542. * 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.
  33543. * 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
  33544. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33545. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33546. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33547. */
  33548. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33549. if (closeArray === void 0) { closeArray = false; }
  33550. if (updatable === void 0) { updatable = false; }
  33551. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33552. pathArray: pathArray,
  33553. closeArray: closeArray,
  33554. closePath: closePath,
  33555. offset: offset,
  33556. updatable: updatable,
  33557. sideOrientation: sideOrientation,
  33558. instance: instance
  33559. }, scene);
  33560. };
  33561. /**
  33562. * Creates a plane polygonal mesh. By default, this is a disc.
  33563. * Please consider using the same method from the MeshBuilder class instead.
  33564. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33565. * 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.
  33566. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33567. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33569. */
  33570. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33571. if (scene === void 0) { scene = null; }
  33572. var options = {
  33573. radius: radius,
  33574. tessellation: tessellation,
  33575. sideOrientation: sideOrientation,
  33576. updatable: updatable
  33577. };
  33578. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33579. };
  33580. /**
  33581. * Creates a box mesh.
  33582. * Please consider using the same method from the MeshBuilder class instead.
  33583. * The parameter `size` sets the size (float) of each box side (default 1).
  33584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33585. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33587. */
  33588. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33589. if (scene === void 0) { scene = null; }
  33590. var options = {
  33591. size: size,
  33592. sideOrientation: sideOrientation,
  33593. updatable: updatable
  33594. };
  33595. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33596. };
  33597. /**
  33598. * Creates a sphere mesh.
  33599. * Please consider using the same method from the MeshBuilder class instead.
  33600. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33601. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33602. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33603. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33605. */
  33606. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33607. var options = {
  33608. segments: segments,
  33609. diameterX: diameter,
  33610. diameterY: diameter,
  33611. diameterZ: diameter,
  33612. sideOrientation: sideOrientation,
  33613. updatable: updatable
  33614. };
  33615. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33616. };
  33617. /**
  33618. * Creates a cylinder or a cone mesh.
  33619. * Please consider using the same method from the MeshBuilder class instead.
  33620. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33621. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33622. * 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.
  33623. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33624. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33626. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33628. */
  33629. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33630. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33631. if (scene !== undefined) {
  33632. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33633. updatable = scene;
  33634. }
  33635. scene = subdivisions;
  33636. subdivisions = 1;
  33637. }
  33638. var options = {
  33639. height: height,
  33640. diameterTop: diameterTop,
  33641. diameterBottom: diameterBottom,
  33642. tessellation: tessellation,
  33643. subdivisions: subdivisions,
  33644. sideOrientation: sideOrientation,
  33645. updatable: updatable
  33646. };
  33647. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33648. };
  33649. // Torus (Code from SharpDX.org)
  33650. /**
  33651. * Creates a torus mesh.
  33652. * Please consider using the same method from the MeshBuilder class instead.
  33653. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33654. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33655. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33656. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33657. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33659. */
  33660. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33661. var options = {
  33662. diameter: diameter,
  33663. thickness: thickness,
  33664. tessellation: tessellation,
  33665. sideOrientation: sideOrientation,
  33666. updatable: updatable
  33667. };
  33668. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33669. };
  33670. /**
  33671. * Creates a torus knot mesh.
  33672. * Please consider using the same method from the MeshBuilder class instead.
  33673. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33674. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33675. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33676. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33677. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33678. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33680. */
  33681. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33682. var options = {
  33683. radius: radius,
  33684. tube: tube,
  33685. radialSegments: radialSegments,
  33686. tubularSegments: tubularSegments,
  33687. p: p,
  33688. q: q,
  33689. sideOrientation: sideOrientation,
  33690. updatable: updatable
  33691. };
  33692. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33693. };
  33694. /**
  33695. * Creates a line mesh.
  33696. * Please consider using the same method from the MeshBuilder class instead.
  33697. * 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.
  33698. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33699. * The parameter `points` is an array successive Vector3.
  33700. * 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
  33701. * When updating an instance, remember that only point positions can change, not the number of points.
  33702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33703. */
  33704. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33705. if (scene === void 0) { scene = null; }
  33706. if (updatable === void 0) { updatable = false; }
  33707. if (instance === void 0) { instance = null; }
  33708. var options = {
  33709. points: points,
  33710. updatable: updatable,
  33711. instance: instance
  33712. };
  33713. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33714. };
  33715. /**
  33716. * Creates a dashed line mesh.
  33717. * Please consider using the same method from the MeshBuilder class instead.
  33718. * 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.
  33719. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33720. * The parameter `points` is an array successive Vector3.
  33721. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33722. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33723. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33724. * 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
  33725. * When updating an instance, remember that only point positions can change, not the number of points.
  33726. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33727. */
  33728. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33729. if (scene === void 0) { scene = null; }
  33730. var options = {
  33731. points: points,
  33732. dashSize: dashSize,
  33733. gapSize: gapSize,
  33734. dashNb: dashNb,
  33735. updatable: updatable,
  33736. instance: instance
  33737. };
  33738. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33739. };
  33740. /**
  33741. * Creates a polygon mesh.
  33742. * Please consider using the same method from the MeshBuilder class instead.
  33743. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33744. * 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.
  33745. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33747. * Remember you can only change the shape positions, not their number when updating a polygon.
  33748. */
  33749. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33750. var options = {
  33751. shape: shape,
  33752. holes: holes,
  33753. updatable: updatable,
  33754. sideOrientation: sideOrientation
  33755. };
  33756. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33757. };
  33758. /**
  33759. * Creates an extruded polygon mesh, with depth in the Y direction.
  33760. * Please consider using the same method from the MeshBuilder class instead.
  33761. */
  33762. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33763. var options = {
  33764. shape: shape,
  33765. holes: holes,
  33766. depth: depth,
  33767. updatable: updatable,
  33768. sideOrientation: sideOrientation
  33769. };
  33770. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33771. };
  33772. /**
  33773. * Creates an extruded shape mesh.
  33774. * 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.
  33775. * Please consider using the same method from the MeshBuilder class instead.
  33776. *
  33777. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33778. * 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
  33779. * extruded along the Z axis.
  33780. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33781. * 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.
  33782. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33783. * 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
  33784. * 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
  33785. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33787. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33789. */
  33790. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33791. if (scene === void 0) { scene = null; }
  33792. var options = {
  33793. shape: shape,
  33794. path: path,
  33795. scale: scale,
  33796. rotation: rotation,
  33797. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33798. sideOrientation: sideOrientation,
  33799. instance: instance,
  33800. updatable: updatable
  33801. };
  33802. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33803. };
  33804. /**
  33805. * Creates an custom extruded shape mesh.
  33806. * 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.
  33807. * Please consider using the same method from the MeshBuilder class instead.
  33808. *
  33809. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33810. * 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
  33811. * extruded along the Z axis.
  33812. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33813. * 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
  33814. * and the distance of this point from the begining of the path :
  33815. * ```javascript
  33816. * var rotationFunction = function(i, distance) {
  33817. * // do things
  33818. * return rotationValue; }
  33819. * ```
  33820. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33821. * 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
  33822. * and the distance of this point from the begining of the path :
  33823. * ```javascript
  33824. * var scaleFunction = function(i, distance) {
  33825. * // do things
  33826. * return scaleValue;}
  33827. * ```
  33828. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33829. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33830. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33831. * 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
  33832. * 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
  33833. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33835. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33837. */
  33838. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33839. var options = {
  33840. shape: shape,
  33841. path: path,
  33842. scaleFunction: scaleFunction,
  33843. rotationFunction: rotationFunction,
  33844. ribbonCloseArray: ribbonCloseArray,
  33845. ribbonClosePath: ribbonClosePath,
  33846. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33847. sideOrientation: sideOrientation,
  33848. instance: instance,
  33849. updatable: updatable
  33850. };
  33851. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33852. };
  33853. /**
  33854. * Creates lathe mesh.
  33855. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33856. * Please consider using the same method from the MeshBuilder class instead.
  33857. * 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
  33858. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33859. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33860. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33861. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33862. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33864. */
  33865. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33866. var options = {
  33867. shape: shape,
  33868. radius: radius,
  33869. tessellation: tessellation,
  33870. sideOrientation: sideOrientation,
  33871. updatable: updatable
  33872. };
  33873. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33874. };
  33875. /**
  33876. * Creates a plane mesh.
  33877. * Please consider using the same method from the MeshBuilder class instead.
  33878. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33879. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33880. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33881. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33882. */
  33883. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33884. var options = {
  33885. size: size,
  33886. width: size,
  33887. height: size,
  33888. sideOrientation: sideOrientation,
  33889. updatable: updatable
  33890. };
  33891. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33892. };
  33893. /**
  33894. * Creates a ground mesh.
  33895. * Please consider using the same method from the MeshBuilder class instead.
  33896. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33897. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33898. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33899. */
  33900. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33901. var options = {
  33902. width: width,
  33903. height: height,
  33904. subdivisions: subdivisions,
  33905. updatable: updatable
  33906. };
  33907. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33908. };
  33909. /**
  33910. * Creates a tiled ground mesh.
  33911. * Please consider using the same method from the MeshBuilder class instead.
  33912. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33913. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33914. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33915. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33916. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33917. * numbers of subdivisions on the ground width and height of each tile.
  33918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33919. */
  33920. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33921. var options = {
  33922. xmin: xmin,
  33923. zmin: zmin,
  33924. xmax: xmax,
  33925. zmax: zmax,
  33926. subdivisions: subdivisions,
  33927. precision: precision,
  33928. updatable: updatable
  33929. };
  33930. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33931. };
  33932. /**
  33933. * Creates a ground mesh from a height map.
  33934. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33935. * Please consider using the same method from the MeshBuilder class instead.
  33936. * The parameter `url` sets the URL of the height map image resource.
  33937. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33938. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33939. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33940. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33941. * 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).
  33942. * This function is passed the newly built mesh :
  33943. * ```javascript
  33944. * function(mesh) { // do things
  33945. * return; }
  33946. * ```
  33947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33948. */
  33949. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33950. var options = {
  33951. width: width,
  33952. height: height,
  33953. subdivisions: subdivisions,
  33954. minHeight: minHeight,
  33955. maxHeight: maxHeight,
  33956. updatable: updatable,
  33957. onReady: onReady
  33958. };
  33959. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33960. };
  33961. /**
  33962. * Creates a tube mesh.
  33963. * 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.
  33964. * Please consider using the same method from the MeshBuilder class instead.
  33965. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33966. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33967. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33968. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33969. * 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.
  33970. * It must return a radius value (positive float) :
  33971. * ```javascript
  33972. * var radiusFunction = function(i, distance) {
  33973. * // do things
  33974. * return radius; }
  33975. * ```
  33976. * 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
  33977. * 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
  33978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33979. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33981. */
  33982. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33983. var options = {
  33984. path: path,
  33985. radius: radius,
  33986. tessellation: tessellation,
  33987. radiusFunction: radiusFunction,
  33988. arc: 1,
  33989. cap: cap,
  33990. updatable: updatable,
  33991. sideOrientation: sideOrientation,
  33992. instance: instance
  33993. };
  33994. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33995. };
  33996. /**
  33997. * Creates a polyhedron mesh.
  33998. * Please consider using the same method from the MeshBuilder class instead.
  33999. * 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
  34000. * to choose the wanted type.
  34001. * The parameter `size` (positive float, default 1) sets the polygon size.
  34002. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34003. * 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`.
  34004. * 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
  34005. * 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)`).
  34006. * 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
  34007. * 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.
  34008. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34009. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34011. */
  34012. Mesh.CreatePolyhedron = function (name, options, scene) {
  34013. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34014. };
  34015. /**
  34016. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34017. * Please consider using the same method from the MeshBuilder class instead.
  34018. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34019. * 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`).
  34020. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34021. * 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.
  34022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34023. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34025. */
  34026. Mesh.CreateIcoSphere = function (name, options, scene) {
  34027. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34028. };
  34029. /**
  34030. * Creates a decal mesh.
  34031. * Please consider using the same method from the MeshBuilder class instead.
  34032. * 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.
  34033. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34034. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34035. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34036. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34037. */
  34038. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34039. var options = {
  34040. position: position,
  34041. normal: normal,
  34042. size: size,
  34043. angle: angle
  34044. };
  34045. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34046. };
  34047. // Skeletons
  34048. /**
  34049. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34050. */
  34051. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34052. if (!this._sourcePositions) {
  34053. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34054. if (!source) {
  34055. return this._sourcePositions;
  34056. }
  34057. this._sourcePositions = new Float32Array(source);
  34058. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34059. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34060. }
  34061. }
  34062. return this._sourcePositions;
  34063. };
  34064. /**
  34065. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34066. */
  34067. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34068. if (!this._sourceNormals) {
  34069. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34070. if (!source) {
  34071. return this._sourceNormals;
  34072. }
  34073. this._sourceNormals = new Float32Array(source);
  34074. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34075. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34076. }
  34077. }
  34078. return this._sourceNormals;
  34079. };
  34080. /**
  34081. * Updates the vertex buffer by applying transformation from the bones.
  34082. * Returns the Mesh.
  34083. *
  34084. * @param {skeleton} skeleton to apply
  34085. */
  34086. Mesh.prototype.applySkeleton = function (skeleton) {
  34087. if (!this.geometry) {
  34088. return this;
  34089. }
  34090. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34091. return this;
  34092. }
  34093. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34095. return this;
  34096. }
  34097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34098. return this;
  34099. }
  34100. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34101. return this;
  34102. }
  34103. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34104. return this;
  34105. }
  34106. if (!this._sourcePositions) {
  34107. var submeshes = this.subMeshes.slice();
  34108. this.setPositionsForCPUSkinning();
  34109. this.subMeshes = submeshes;
  34110. }
  34111. if (!this._sourceNormals) {
  34112. this.setNormalsForCPUSkinning();
  34113. }
  34114. // positionsData checks for not being Float32Array will only pass at most once
  34115. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34116. if (!positionsData) {
  34117. return this;
  34118. }
  34119. if (!(positionsData instanceof Float32Array)) {
  34120. positionsData = new Float32Array(positionsData);
  34121. }
  34122. // normalsData checks for not being Float32Array will only pass at most once
  34123. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34124. if (!normalsData) {
  34125. return this;
  34126. }
  34127. if (!(normalsData instanceof Float32Array)) {
  34128. normalsData = new Float32Array(normalsData);
  34129. }
  34130. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34131. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34132. if (!matricesWeightsData || !matricesIndicesData) {
  34133. return this;
  34134. }
  34135. var needExtras = this.numBoneInfluencers > 4;
  34136. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34137. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34138. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34139. var tempVector3 = BABYLON.Vector3.Zero();
  34140. var finalMatrix = new BABYLON.Matrix();
  34141. var tempMatrix = new BABYLON.Matrix();
  34142. var matWeightIdx = 0;
  34143. var inf;
  34144. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34145. var weight;
  34146. for (inf = 0; inf < 4; inf++) {
  34147. weight = matricesWeightsData[matWeightIdx + inf];
  34148. if (weight > 0) {
  34149. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34150. finalMatrix.addToSelf(tempMatrix);
  34151. }
  34152. else
  34153. break;
  34154. }
  34155. if (needExtras) {
  34156. for (inf = 0; inf < 4; inf++) {
  34157. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34158. if (weight > 0) {
  34159. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34160. finalMatrix.addToSelf(tempMatrix);
  34161. }
  34162. else
  34163. break;
  34164. }
  34165. }
  34166. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34167. tempVector3.toArray(positionsData, index);
  34168. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34169. tempVector3.toArray(normalsData, index);
  34170. finalMatrix.reset();
  34171. }
  34172. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34173. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34174. return this;
  34175. };
  34176. // Tools
  34177. /**
  34178. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34179. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34180. */
  34181. Mesh.MinMax = function (meshes) {
  34182. var minVector = null;
  34183. var maxVector = null;
  34184. meshes.forEach(function (mesh, index, array) {
  34185. var boundingInfo = mesh.getBoundingInfo();
  34186. var boundingBox = boundingInfo.boundingBox;
  34187. if (!minVector || !maxVector) {
  34188. minVector = boundingBox.minimumWorld;
  34189. maxVector = boundingBox.maximumWorld;
  34190. }
  34191. else {
  34192. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34193. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34194. }
  34195. });
  34196. if (!minVector || !maxVector) {
  34197. return {
  34198. min: BABYLON.Vector3.Zero(),
  34199. max: BABYLON.Vector3.Zero()
  34200. };
  34201. }
  34202. return {
  34203. min: minVector,
  34204. max: maxVector
  34205. };
  34206. };
  34207. /**
  34208. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34209. */
  34210. Mesh.Center = function (meshesOrMinMaxVector) {
  34211. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34212. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34213. };
  34214. /**
  34215. * Merge the array of meshes into a single mesh for performance reasons.
  34216. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34217. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34218. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34219. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34220. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34221. */
  34222. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34223. if (disposeSource === void 0) { disposeSource = true; }
  34224. var index;
  34225. if (!allow32BitsIndices) {
  34226. var totalVertices = 0;
  34227. // Counting vertices
  34228. for (index = 0; index < meshes.length; index++) {
  34229. if (meshes[index]) {
  34230. totalVertices += meshes[index].getTotalVertices();
  34231. if (totalVertices > 65536) {
  34232. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34233. return null;
  34234. }
  34235. }
  34236. }
  34237. }
  34238. // Merge
  34239. var vertexData = null;
  34240. var otherVertexData;
  34241. var indiceArray = new Array();
  34242. var source = null;
  34243. for (index = 0; index < meshes.length; index++) {
  34244. if (meshes[index]) {
  34245. meshes[index].computeWorldMatrix(true);
  34246. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34247. otherVertexData.transform(meshes[index].getWorldMatrix());
  34248. if (vertexData) {
  34249. vertexData.merge(otherVertexData);
  34250. }
  34251. else {
  34252. vertexData = otherVertexData;
  34253. source = meshes[index];
  34254. }
  34255. if (subdivideWithSubMeshes) {
  34256. indiceArray.push(meshes[index].getTotalIndices());
  34257. }
  34258. }
  34259. }
  34260. source = source;
  34261. if (!meshSubclass) {
  34262. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34263. }
  34264. vertexData.applyToMesh(meshSubclass);
  34265. // Setting properties
  34266. meshSubclass.material = source.material;
  34267. meshSubclass.checkCollisions = source.checkCollisions;
  34268. // Cleaning
  34269. if (disposeSource) {
  34270. for (index = 0; index < meshes.length; index++) {
  34271. if (meshes[index]) {
  34272. meshes[index].dispose();
  34273. }
  34274. }
  34275. }
  34276. // Subdivide
  34277. if (subdivideWithSubMeshes) {
  34278. //-- Suppresions du submesh global
  34279. meshSubclass.releaseSubMeshes();
  34280. index = 0;
  34281. var offset = 0;
  34282. //-- aplique la subdivision en fonction du tableau d'indices
  34283. while (index < indiceArray.length) {
  34284. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34285. offset += indiceArray[index];
  34286. index++;
  34287. }
  34288. }
  34289. return meshSubclass;
  34290. };
  34291. // Consts
  34292. Mesh._FRONTSIDE = 0;
  34293. Mesh._BACKSIDE = 1;
  34294. Mesh._DOUBLESIDE = 2;
  34295. Mesh._DEFAULTSIDE = 0;
  34296. Mesh._NO_CAP = 0;
  34297. Mesh._CAP_START = 1;
  34298. Mesh._CAP_END = 2;
  34299. Mesh._CAP_ALL = 3;
  34300. return Mesh;
  34301. }(BABYLON.AbstractMesh));
  34302. BABYLON.Mesh = Mesh;
  34303. })(BABYLON || (BABYLON = {}));
  34304. //# sourceMappingURL=babylon.mesh.js.map
  34305. var BABYLON;
  34306. (function (BABYLON) {
  34307. var BaseSubMesh = /** @class */ (function () {
  34308. function BaseSubMesh() {
  34309. }
  34310. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34311. get: function () {
  34312. return this._materialEffect;
  34313. },
  34314. enumerable: true,
  34315. configurable: true
  34316. });
  34317. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34318. if (defines === void 0) { defines = null; }
  34319. if (this._materialEffect === effect) {
  34320. if (!effect) {
  34321. this._materialDefines = null;
  34322. }
  34323. return;
  34324. }
  34325. this._materialDefines = defines;
  34326. this._materialEffect = effect;
  34327. };
  34328. return BaseSubMesh;
  34329. }());
  34330. BABYLON.BaseSubMesh = BaseSubMesh;
  34331. var SubMesh = /** @class */ (function (_super) {
  34332. __extends(SubMesh, _super);
  34333. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34334. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34335. var _this = _super.call(this) || this;
  34336. _this.materialIndex = materialIndex;
  34337. _this.verticesStart = verticesStart;
  34338. _this.verticesCount = verticesCount;
  34339. _this.indexStart = indexStart;
  34340. _this.indexCount = indexCount;
  34341. _this._renderId = 0;
  34342. _this._mesh = mesh;
  34343. _this._renderingMesh = renderingMesh || mesh;
  34344. mesh.subMeshes.push(_this);
  34345. _this._trianglePlanes = [];
  34346. _this._id = mesh.subMeshes.length - 1;
  34347. if (createBoundingBox) {
  34348. _this.refreshBoundingInfo();
  34349. mesh.computeWorldMatrix(true);
  34350. }
  34351. return _this;
  34352. }
  34353. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34354. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34355. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34356. };
  34357. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34358. get: function () {
  34359. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34360. },
  34361. enumerable: true,
  34362. configurable: true
  34363. });
  34364. /**
  34365. * Returns the submesh BoudingInfo object.
  34366. */
  34367. SubMesh.prototype.getBoundingInfo = function () {
  34368. if (this.IsGlobal) {
  34369. return this._mesh.getBoundingInfo();
  34370. }
  34371. return this._boundingInfo;
  34372. };
  34373. /**
  34374. * Sets the submesh BoundingInfo.
  34375. * Return the SubMesh.
  34376. */
  34377. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34378. this._boundingInfo = boundingInfo;
  34379. return this;
  34380. };
  34381. /**
  34382. * Returns the mesh of the current submesh.
  34383. */
  34384. SubMesh.prototype.getMesh = function () {
  34385. return this._mesh;
  34386. };
  34387. /**
  34388. * Returns the rendering mesh of the submesh.
  34389. */
  34390. SubMesh.prototype.getRenderingMesh = function () {
  34391. return this._renderingMesh;
  34392. };
  34393. /**
  34394. * Returns the submesh material.
  34395. */
  34396. SubMesh.prototype.getMaterial = function () {
  34397. var rootMaterial = this._renderingMesh.material;
  34398. if (rootMaterial === null || rootMaterial === undefined) {
  34399. return this._mesh.getScene().defaultMaterial;
  34400. }
  34401. else if (rootMaterial.getSubMaterial) {
  34402. var multiMaterial = rootMaterial;
  34403. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34404. if (this._currentMaterial !== effectiveMaterial) {
  34405. this._currentMaterial = effectiveMaterial;
  34406. this._materialDefines = null;
  34407. }
  34408. return effectiveMaterial;
  34409. }
  34410. return rootMaterial;
  34411. };
  34412. // Methods
  34413. /**
  34414. * Sets a new updated BoundingInfo object to the submesh.
  34415. * Returns the SubMesh.
  34416. */
  34417. SubMesh.prototype.refreshBoundingInfo = function () {
  34418. this._lastColliderWorldVertices = null;
  34419. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34420. return this;
  34421. }
  34422. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34423. if (!data) {
  34424. this._boundingInfo = this._mesh.getBoundingInfo();
  34425. return this;
  34426. }
  34427. var indices = this._renderingMesh.getIndices();
  34428. var extend;
  34429. //is this the only submesh?
  34430. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34431. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34432. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34433. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34434. }
  34435. else {
  34436. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34437. }
  34438. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34439. return this;
  34440. };
  34441. SubMesh.prototype._checkCollision = function (collider) {
  34442. var boundingInfo = this.getBoundingInfo();
  34443. return boundingInfo._checkCollision(collider);
  34444. };
  34445. /**
  34446. * Updates the submesh BoundingInfo.
  34447. * Returns the Submesh.
  34448. */
  34449. SubMesh.prototype.updateBoundingInfo = function (world) {
  34450. var boundingInfo = this.getBoundingInfo();
  34451. if (!boundingInfo) {
  34452. this.refreshBoundingInfo();
  34453. boundingInfo = this.getBoundingInfo();
  34454. }
  34455. boundingInfo.update(world);
  34456. return this;
  34457. };
  34458. /**
  34459. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34460. * Boolean returned.
  34461. */
  34462. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34463. var boundingInfo = this.getBoundingInfo();
  34464. if (!boundingInfo) {
  34465. return false;
  34466. }
  34467. return boundingInfo.isInFrustum(frustumPlanes);
  34468. };
  34469. /**
  34470. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34471. * Boolean returned.
  34472. */
  34473. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34474. var boundingInfo = this.getBoundingInfo();
  34475. if (!boundingInfo) {
  34476. return false;
  34477. }
  34478. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34479. };
  34480. /**
  34481. * Renders the submesh.
  34482. * Returns it.
  34483. */
  34484. SubMesh.prototype.render = function (enableAlphaMode) {
  34485. this._renderingMesh.render(this, enableAlphaMode);
  34486. return this;
  34487. };
  34488. /**
  34489. * Returns a new Index Buffer.
  34490. * Type returned : WebGLBuffer.
  34491. */
  34492. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34493. if (!this._linesIndexBuffer) {
  34494. var linesIndices = [];
  34495. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34496. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34497. }
  34498. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34499. this.linesIndexCount = linesIndices.length;
  34500. }
  34501. return this._linesIndexBuffer;
  34502. };
  34503. /**
  34504. * True is the passed Ray intersects the submesh bounding box.
  34505. * Boolean returned.
  34506. */
  34507. SubMesh.prototype.canIntersects = function (ray) {
  34508. var boundingInfo = this.getBoundingInfo();
  34509. if (!boundingInfo) {
  34510. return false;
  34511. }
  34512. return ray.intersectsBox(boundingInfo.boundingBox);
  34513. };
  34514. /**
  34515. * Returns an object IntersectionInfo.
  34516. */
  34517. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34518. var intersectInfo = null;
  34519. var material = this.getMaterial();
  34520. if (!material) {
  34521. return null;
  34522. }
  34523. switch (material.fillMode) {
  34524. case BABYLON.Material.PointListDrawMode:
  34525. case BABYLON.Material.LineListDrawMode:
  34526. case BABYLON.Material.LineLoopDrawMode:
  34527. case BABYLON.Material.LineStripDrawMode:
  34528. case BABYLON.Material.TriangleFanDrawMode:
  34529. case BABYLON.Material.TriangleStripDrawMode:
  34530. return null;
  34531. }
  34532. // LineMesh first as it's also a Mesh...
  34533. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34534. var lineMesh = this._mesh;
  34535. // Line test
  34536. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34537. var p0 = positions[indices[index]];
  34538. var p1 = positions[indices[index + 1]];
  34539. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34540. if (length < 0) {
  34541. continue;
  34542. }
  34543. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34544. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34545. if (fastCheck) {
  34546. break;
  34547. }
  34548. }
  34549. }
  34550. }
  34551. else {
  34552. // Triangles test
  34553. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34554. var p0 = positions[indices[index]];
  34555. var p1 = positions[indices[index + 1]];
  34556. var p2 = positions[indices[index + 2]];
  34557. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34558. if (currentIntersectInfo) {
  34559. if (currentIntersectInfo.distance < 0) {
  34560. continue;
  34561. }
  34562. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34563. intersectInfo = currentIntersectInfo;
  34564. intersectInfo.faceId = index / 3;
  34565. if (fastCheck) {
  34566. break;
  34567. }
  34568. }
  34569. }
  34570. }
  34571. }
  34572. return intersectInfo;
  34573. };
  34574. SubMesh.prototype._rebuild = function () {
  34575. if (this._linesIndexBuffer) {
  34576. this._linesIndexBuffer = null;
  34577. }
  34578. };
  34579. // Clone
  34580. /**
  34581. * Creates a new Submesh from the passed Mesh.
  34582. */
  34583. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34584. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34585. if (!this.IsGlobal) {
  34586. var boundingInfo = this.getBoundingInfo();
  34587. if (!boundingInfo) {
  34588. return result;
  34589. }
  34590. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34591. }
  34592. return result;
  34593. };
  34594. // Dispose
  34595. /**
  34596. * Disposes the Submesh.
  34597. * Returns nothing.
  34598. */
  34599. SubMesh.prototype.dispose = function () {
  34600. if (this._linesIndexBuffer) {
  34601. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34602. this._linesIndexBuffer = null;
  34603. }
  34604. // Remove from mesh
  34605. var index = this._mesh.subMeshes.indexOf(this);
  34606. this._mesh.subMeshes.splice(index, 1);
  34607. };
  34608. // Statics
  34609. /**
  34610. * Creates a new Submesh from the passed parameters :
  34611. * - materialIndex (integer) : the index of the main mesh material.
  34612. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34613. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34614. * - mesh (Mesh) : the main mesh to create the submesh from.
  34615. * - renderingMesh (optional Mesh) : rendering mesh.
  34616. */
  34617. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34618. var minVertexIndex = Number.MAX_VALUE;
  34619. var maxVertexIndex = -Number.MAX_VALUE;
  34620. renderingMesh = (renderingMesh || mesh);
  34621. var indices = renderingMesh.getIndices();
  34622. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34623. var vertexIndex = indices[index];
  34624. if (vertexIndex < minVertexIndex)
  34625. minVertexIndex = vertexIndex;
  34626. if (vertexIndex > maxVertexIndex)
  34627. maxVertexIndex = vertexIndex;
  34628. }
  34629. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34630. };
  34631. return SubMesh;
  34632. }(BaseSubMesh));
  34633. BABYLON.SubMesh = SubMesh;
  34634. })(BABYLON || (BABYLON = {}));
  34635. //# sourceMappingURL=babylon.subMesh.js.map
  34636. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34637. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34638. s = arguments[i];
  34639. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34640. t[p] = s[p];
  34641. }
  34642. return t;
  34643. };
  34644. var BABYLON;
  34645. (function (BABYLON) {
  34646. /**
  34647. * Manages the defines for the Material
  34648. */
  34649. var MaterialDefines = /** @class */ (function () {
  34650. function MaterialDefines() {
  34651. this._isDirty = true;
  34652. /** @hidden */
  34653. this._areLightsDirty = true;
  34654. /** @hidden */
  34655. this._areAttributesDirty = true;
  34656. /** @hidden */
  34657. this._areTexturesDirty = true;
  34658. /** @hidden */
  34659. this._areFresnelDirty = true;
  34660. /** @hidden */
  34661. this._areMiscDirty = true;
  34662. /** @hidden */
  34663. this._areImageProcessingDirty = true;
  34664. /** @hidden */
  34665. this._normals = false;
  34666. /** @hidden */
  34667. this._uvs = false;
  34668. /** @hidden */
  34669. this._needNormals = false;
  34670. /** @hidden */
  34671. this._needUVs = false;
  34672. }
  34673. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34674. /**
  34675. * Specifies if the material needs to be re-calculated
  34676. */
  34677. get: function () {
  34678. return this._isDirty;
  34679. },
  34680. enumerable: true,
  34681. configurable: true
  34682. });
  34683. /**
  34684. * Marks the material to indicate that it has been re-calculated
  34685. */
  34686. MaterialDefines.prototype.markAsProcessed = function () {
  34687. this._isDirty = false;
  34688. this._areAttributesDirty = false;
  34689. this._areTexturesDirty = false;
  34690. this._areFresnelDirty = false;
  34691. this._areLightsDirty = false;
  34692. this._areMiscDirty = false;
  34693. this._areImageProcessingDirty = false;
  34694. };
  34695. /**
  34696. * Marks the material to indicate that it needs to be re-calculated
  34697. */
  34698. MaterialDefines.prototype.markAsUnprocessed = function () {
  34699. this._isDirty = true;
  34700. };
  34701. /**
  34702. * Marks the material to indicate all of its defines need to be re-calculated
  34703. */
  34704. MaterialDefines.prototype.markAllAsDirty = function () {
  34705. this._areTexturesDirty = true;
  34706. this._areAttributesDirty = true;
  34707. this._areLightsDirty = true;
  34708. this._areFresnelDirty = true;
  34709. this._areMiscDirty = true;
  34710. this._areImageProcessingDirty = true;
  34711. this._isDirty = true;
  34712. };
  34713. /**
  34714. * Marks the material to indicate that image processing needs to be re-calculated
  34715. */
  34716. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34717. this._areImageProcessingDirty = true;
  34718. this._isDirty = true;
  34719. };
  34720. /**
  34721. * Marks the material to indicate the lights need to be re-calculated
  34722. */
  34723. MaterialDefines.prototype.markAsLightDirty = function () {
  34724. this._areLightsDirty = true;
  34725. this._isDirty = true;
  34726. };
  34727. /**
  34728. * Marks the attribute state as changed
  34729. */
  34730. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34731. this._areAttributesDirty = true;
  34732. this._isDirty = true;
  34733. };
  34734. /**
  34735. * Marks the texture state as changed
  34736. */
  34737. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34738. this._areTexturesDirty = true;
  34739. this._isDirty = true;
  34740. };
  34741. /**
  34742. * Marks the fresnel state as changed
  34743. */
  34744. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34745. this._areFresnelDirty = true;
  34746. this._isDirty = true;
  34747. };
  34748. /**
  34749. * Marks the misc state as changed
  34750. */
  34751. MaterialDefines.prototype.markAsMiscDirty = function () {
  34752. this._areMiscDirty = true;
  34753. this._isDirty = true;
  34754. };
  34755. /**
  34756. * Rebuilds the material defines
  34757. */
  34758. MaterialDefines.prototype.rebuild = function () {
  34759. if (this._keys) {
  34760. delete this._keys;
  34761. }
  34762. this._keys = [];
  34763. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34764. var key = _a[_i];
  34765. if (key[0] === "_") {
  34766. continue;
  34767. }
  34768. this._keys.push(key);
  34769. }
  34770. };
  34771. /**
  34772. * Specifies if two material defines are equal
  34773. * @param other - A material define instance to compare to
  34774. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34775. */
  34776. MaterialDefines.prototype.isEqual = function (other) {
  34777. if (this._keys.length !== other._keys.length) {
  34778. return false;
  34779. }
  34780. for (var index = 0; index < this._keys.length; index++) {
  34781. var prop = this._keys[index];
  34782. if (this[prop] !== other[prop]) {
  34783. return false;
  34784. }
  34785. }
  34786. return true;
  34787. };
  34788. /**
  34789. * Clones this instance's defines to another instance
  34790. * @param other - material defines to clone values to
  34791. */
  34792. MaterialDefines.prototype.cloneTo = function (other) {
  34793. if (this._keys.length !== other._keys.length) {
  34794. other._keys = this._keys.slice(0);
  34795. }
  34796. for (var index = 0; index < this._keys.length; index++) {
  34797. var prop = this._keys[index];
  34798. other[prop] = this[prop];
  34799. }
  34800. };
  34801. /**
  34802. * Resets the material define values
  34803. */
  34804. MaterialDefines.prototype.reset = function () {
  34805. for (var index = 0; index < this._keys.length; index++) {
  34806. var prop = this._keys[index];
  34807. var type = typeof this[prop];
  34808. switch (type) {
  34809. case "number":
  34810. this[prop] = 0;
  34811. break;
  34812. case "string":
  34813. this[prop] = "";
  34814. break;
  34815. default:
  34816. this[prop] = false;
  34817. break;
  34818. }
  34819. }
  34820. };
  34821. /**
  34822. * Converts the material define values to a string
  34823. * @returns - String of material define information
  34824. */
  34825. MaterialDefines.prototype.toString = function () {
  34826. var result = "";
  34827. for (var index = 0; index < this._keys.length; index++) {
  34828. var prop = this._keys[index];
  34829. var value = this[prop];
  34830. var type = typeof value;
  34831. switch (type) {
  34832. case "number":
  34833. case "string":
  34834. result += "#define " + prop + " " + value + "\n";
  34835. break;
  34836. default:
  34837. if (value) {
  34838. result += "#define " + prop + "\n";
  34839. }
  34840. break;
  34841. }
  34842. }
  34843. return result;
  34844. };
  34845. return MaterialDefines;
  34846. }());
  34847. BABYLON.MaterialDefines = MaterialDefines;
  34848. /**
  34849. * Base class for the main features of a material in Babylon.js
  34850. */
  34851. var Material = /** @class */ (function () {
  34852. /**
  34853. * Creates a material instance
  34854. * @param name defines the name of the material
  34855. * @param scene defines the scene to reference
  34856. * @param doNotAdd specifies if the material should be added to the scene
  34857. */
  34858. function Material(name, scene, doNotAdd) {
  34859. /**
  34860. * Specifies if the ready state should be checked on each call
  34861. */
  34862. this.checkReadyOnEveryCall = false;
  34863. /**
  34864. * Specifies if the ready state should be checked once
  34865. */
  34866. this.checkReadyOnlyOnce = false;
  34867. /**
  34868. * The state of the material
  34869. */
  34870. this.state = "";
  34871. /**
  34872. * The alpha value of the material
  34873. */
  34874. this._alpha = 1.0;
  34875. /**
  34876. * Specifies if back face culling is enabled
  34877. */
  34878. this._backFaceCulling = true;
  34879. /**
  34880. * Specifies if the material should be serialized
  34881. */
  34882. this.doNotSerialize = false;
  34883. /**
  34884. * Specifies if the effect should be stored on sub meshes
  34885. */
  34886. this.storeEffectOnSubMeshes = false;
  34887. /**
  34888. * An event triggered when the material is disposed
  34889. */
  34890. this.onDisposeObservable = new BABYLON.Observable();
  34891. /**
  34892. * An event triggered when the material is bound
  34893. */
  34894. this.onBindObservable = new BABYLON.Observable();
  34895. /**
  34896. * An event triggered when the material is unbound
  34897. */
  34898. this.onUnBindObservable = new BABYLON.Observable();
  34899. /**
  34900. * Stores the value of the alpha mode
  34901. */
  34902. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34903. /**
  34904. * Stores the state of the need depth pre-pass value
  34905. */
  34906. this._needDepthPrePass = false;
  34907. /**
  34908. * Specifies if depth writing should be disabled
  34909. */
  34910. this.disableDepthWrite = false;
  34911. /**
  34912. * Specifies if depth writing should be forced
  34913. */
  34914. this.forceDepthWrite = false;
  34915. /**
  34916. * Specifies if there should be a separate pass for culling
  34917. */
  34918. this.separateCullingPass = false;
  34919. /**
  34920. * Stores the state specifing if fog should be enabled
  34921. */
  34922. this._fogEnabled = true;
  34923. /**
  34924. * Stores the size of points
  34925. */
  34926. this.pointSize = 1.0;
  34927. /**
  34928. * Stores the z offset value
  34929. */
  34930. this.zOffset = 0;
  34931. /**
  34932. * Specifies if the material was previously ready
  34933. */
  34934. this._wasPreviouslyReady = false;
  34935. /**
  34936. * Stores the fill mode state
  34937. */
  34938. this._fillMode = Material.TriangleFillMode;
  34939. this.name = name;
  34940. this.id = name || BABYLON.Tools.RandomId();
  34941. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34942. this.uniqueId = this._scene.getUniqueId();
  34943. if (this._scene.useRightHandedSystem) {
  34944. this.sideOrientation = Material.ClockWiseSideOrientation;
  34945. }
  34946. else {
  34947. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34948. }
  34949. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34950. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34951. if (!doNotAdd) {
  34952. this._scene.materials.push(this);
  34953. }
  34954. }
  34955. Object.defineProperty(Material, "TriangleFillMode", {
  34956. /**
  34957. * Returns the triangle fill mode
  34958. */
  34959. get: function () {
  34960. return Material._TriangleFillMode;
  34961. },
  34962. enumerable: true,
  34963. configurable: true
  34964. });
  34965. Object.defineProperty(Material, "WireFrameFillMode", {
  34966. /**
  34967. * Returns the wireframe mode
  34968. */
  34969. get: function () {
  34970. return Material._WireFrameFillMode;
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. Object.defineProperty(Material, "PointFillMode", {
  34976. /**
  34977. * Returns the point fill mode
  34978. */
  34979. get: function () {
  34980. return Material._PointFillMode;
  34981. },
  34982. enumerable: true,
  34983. configurable: true
  34984. });
  34985. Object.defineProperty(Material, "PointListDrawMode", {
  34986. /**
  34987. * Returns the point list draw mode
  34988. */
  34989. get: function () {
  34990. return Material._PointListDrawMode;
  34991. },
  34992. enumerable: true,
  34993. configurable: true
  34994. });
  34995. Object.defineProperty(Material, "LineListDrawMode", {
  34996. /**
  34997. * Returns the line list draw mode
  34998. */
  34999. get: function () {
  35000. return Material._LineListDrawMode;
  35001. },
  35002. enumerable: true,
  35003. configurable: true
  35004. });
  35005. Object.defineProperty(Material, "LineLoopDrawMode", {
  35006. /**
  35007. * Returns the line loop draw mode
  35008. */
  35009. get: function () {
  35010. return Material._LineLoopDrawMode;
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. Object.defineProperty(Material, "LineStripDrawMode", {
  35016. /**
  35017. * Returns the line strip draw mode
  35018. */
  35019. get: function () {
  35020. return Material._LineStripDrawMode;
  35021. },
  35022. enumerable: true,
  35023. configurable: true
  35024. });
  35025. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35026. /**
  35027. * Returns the triangle strip draw mode
  35028. */
  35029. get: function () {
  35030. return Material._TriangleStripDrawMode;
  35031. },
  35032. enumerable: true,
  35033. configurable: true
  35034. });
  35035. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35036. /**
  35037. * Returns the triangle fan draw mode
  35038. */
  35039. get: function () {
  35040. return Material._TriangleFanDrawMode;
  35041. },
  35042. enumerable: true,
  35043. configurable: true
  35044. });
  35045. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35046. /**
  35047. * Returns the clock-wise side orientation
  35048. */
  35049. get: function () {
  35050. return Material._ClockWiseSideOrientation;
  35051. },
  35052. enumerable: true,
  35053. configurable: true
  35054. });
  35055. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35056. /**
  35057. * Returns the counter clock-wise side orientation
  35058. */
  35059. get: function () {
  35060. return Material._CounterClockWiseSideOrientation;
  35061. },
  35062. enumerable: true,
  35063. configurable: true
  35064. });
  35065. Object.defineProperty(Material, "TextureDirtyFlag", {
  35066. /**
  35067. * Returns the dirty texture flag value
  35068. */
  35069. get: function () {
  35070. return Material._TextureDirtyFlag;
  35071. },
  35072. enumerable: true,
  35073. configurable: true
  35074. });
  35075. Object.defineProperty(Material, "LightDirtyFlag", {
  35076. /**
  35077. * Returns the dirty light flag value
  35078. */
  35079. get: function () {
  35080. return Material._LightDirtyFlag;
  35081. },
  35082. enumerable: true,
  35083. configurable: true
  35084. });
  35085. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35086. /**
  35087. * Returns the dirty fresnel flag value
  35088. */
  35089. get: function () {
  35090. return Material._FresnelDirtyFlag;
  35091. },
  35092. enumerable: true,
  35093. configurable: true
  35094. });
  35095. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35096. /**
  35097. * Returns the dirty attributes flag value
  35098. */
  35099. get: function () {
  35100. return Material._AttributesDirtyFlag;
  35101. },
  35102. enumerable: true,
  35103. configurable: true
  35104. });
  35105. Object.defineProperty(Material, "MiscDirtyFlag", {
  35106. /**
  35107. * Returns the dirty misc flag value
  35108. */
  35109. get: function () {
  35110. return Material._MiscDirtyFlag;
  35111. },
  35112. enumerable: true,
  35113. configurable: true
  35114. });
  35115. Object.defineProperty(Material.prototype, "alpha", {
  35116. /**
  35117. * Gets the alpha value of the material
  35118. */
  35119. get: function () {
  35120. return this._alpha;
  35121. },
  35122. /**
  35123. * Sets the alpha value of the material
  35124. */
  35125. set: function (value) {
  35126. if (this._alpha === value) {
  35127. return;
  35128. }
  35129. this._alpha = value;
  35130. this.markAsDirty(Material.MiscDirtyFlag);
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35136. /**
  35137. * Gets the back-face culling state
  35138. */
  35139. get: function () {
  35140. return this._backFaceCulling;
  35141. },
  35142. /**
  35143. * Sets the back-face culling state
  35144. */
  35145. set: function (value) {
  35146. if (this._backFaceCulling === value) {
  35147. return;
  35148. }
  35149. this._backFaceCulling = value;
  35150. this.markAsDirty(Material.TextureDirtyFlag);
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. Object.defineProperty(Material.prototype, "onDispose", {
  35156. /**
  35157. * Called during a dispose event
  35158. */
  35159. set: function (callback) {
  35160. if (this._onDisposeObserver) {
  35161. this.onDisposeObservable.remove(this._onDisposeObserver);
  35162. }
  35163. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35164. },
  35165. enumerable: true,
  35166. configurable: true
  35167. });
  35168. Object.defineProperty(Material.prototype, "onBind", {
  35169. /**
  35170. * Called during a bind event
  35171. */
  35172. set: function (callback) {
  35173. if (this._onBindObserver) {
  35174. this.onBindObservable.remove(this._onBindObserver);
  35175. }
  35176. this._onBindObserver = this.onBindObservable.add(callback);
  35177. },
  35178. enumerable: true,
  35179. configurable: true
  35180. });
  35181. Object.defineProperty(Material.prototype, "alphaMode", {
  35182. /**
  35183. * Gets the value of the alpha mode
  35184. */
  35185. get: function () {
  35186. return this._alphaMode;
  35187. },
  35188. /**
  35189. * Sets the value of the alpha mode.
  35190. *
  35191. * | Value | Type | Description |
  35192. * | --- | --- | --- |
  35193. * | 0 | ALPHA_DISABLE | |
  35194. * | 1 | ALPHA_ADD | |
  35195. * | 2 | ALPHA_COMBINE | |
  35196. * | 3 | ALPHA_SUBTRACT | |
  35197. * | 4 | ALPHA_MULTIPLY | |
  35198. * | 5 | ALPHA_MAXIMIZED | |
  35199. * | 6 | ALPHA_ONEONE | |
  35200. * | 7 | ALPHA_PREMULTIPLIED | |
  35201. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35202. * | 9 | ALPHA_INTERPOLATE | |
  35203. * | 10 | ALPHA_SCREENMODE | |
  35204. *
  35205. */
  35206. set: function (value) {
  35207. if (this._alphaMode === value) {
  35208. return;
  35209. }
  35210. this._alphaMode = value;
  35211. this.markAsDirty(Material.TextureDirtyFlag);
  35212. },
  35213. enumerable: true,
  35214. configurable: true
  35215. });
  35216. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35217. /**
  35218. * Gets the depth pre-pass value
  35219. */
  35220. get: function () {
  35221. return this._needDepthPrePass;
  35222. },
  35223. /**
  35224. * Sets the need depth pre-pass value
  35225. */
  35226. set: function (value) {
  35227. if (this._needDepthPrePass === value) {
  35228. return;
  35229. }
  35230. this._needDepthPrePass = value;
  35231. if (this._needDepthPrePass) {
  35232. this.checkReadyOnEveryCall = true;
  35233. }
  35234. },
  35235. enumerable: true,
  35236. configurable: true
  35237. });
  35238. Object.defineProperty(Material.prototype, "fogEnabled", {
  35239. /**
  35240. * Gets the value of the fog enabled state
  35241. */
  35242. get: function () {
  35243. return this._fogEnabled;
  35244. },
  35245. /**
  35246. * Sets the state for enabling fog
  35247. */
  35248. set: function (value) {
  35249. if (this._fogEnabled === value) {
  35250. return;
  35251. }
  35252. this._fogEnabled = value;
  35253. this.markAsDirty(Material.MiscDirtyFlag);
  35254. },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. Object.defineProperty(Material.prototype, "wireframe", {
  35259. /**
  35260. * Gets a value specifying if wireframe mode is enabled
  35261. */
  35262. get: function () {
  35263. switch (this._fillMode) {
  35264. case Material.WireFrameFillMode:
  35265. case Material.LineListDrawMode:
  35266. case Material.LineLoopDrawMode:
  35267. case Material.LineStripDrawMode:
  35268. return true;
  35269. }
  35270. return this._scene.forceWireframe;
  35271. },
  35272. /**
  35273. * Sets the state of wireframe mode
  35274. */
  35275. set: function (value) {
  35276. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. Object.defineProperty(Material.prototype, "pointsCloud", {
  35282. /**
  35283. * Gets the value specifying if point clouds are enabled
  35284. */
  35285. get: function () {
  35286. switch (this._fillMode) {
  35287. case Material.PointFillMode:
  35288. case Material.PointListDrawMode:
  35289. return true;
  35290. }
  35291. return this._scene.forcePointsCloud;
  35292. },
  35293. /**
  35294. * Sets the state of point cloud mode
  35295. */
  35296. set: function (value) {
  35297. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35298. },
  35299. enumerable: true,
  35300. configurable: true
  35301. });
  35302. Object.defineProperty(Material.prototype, "fillMode", {
  35303. /**
  35304. * Gets the material fill mode
  35305. */
  35306. get: function () {
  35307. return this._fillMode;
  35308. },
  35309. /**
  35310. * Sets the material fill mode
  35311. */
  35312. set: function (value) {
  35313. if (this._fillMode === value) {
  35314. return;
  35315. }
  35316. this._fillMode = value;
  35317. this.markAsDirty(Material.MiscDirtyFlag);
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. /**
  35323. * Returns a string representation of the current material
  35324. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35325. * @returns a string with material information
  35326. */
  35327. Material.prototype.toString = function (fullDetails) {
  35328. var ret = "Name: " + this.name;
  35329. if (fullDetails) {
  35330. }
  35331. return ret;
  35332. };
  35333. /**
  35334. * Gets the class name of the material
  35335. * @returns a string with the class name of the material
  35336. */
  35337. Material.prototype.getClassName = function () {
  35338. return "Material";
  35339. };
  35340. Object.defineProperty(Material.prototype, "isFrozen", {
  35341. /**
  35342. * Specifies if updates for the material been locked
  35343. */
  35344. get: function () {
  35345. return this.checkReadyOnlyOnce;
  35346. },
  35347. enumerable: true,
  35348. configurable: true
  35349. });
  35350. /**
  35351. * Locks updates for the material
  35352. */
  35353. Material.prototype.freeze = function () {
  35354. this.checkReadyOnlyOnce = true;
  35355. };
  35356. /**
  35357. * Unlocks updates for the material
  35358. */
  35359. Material.prototype.unfreeze = function () {
  35360. this.checkReadyOnlyOnce = false;
  35361. };
  35362. /**
  35363. * Specifies if the material is ready to be used
  35364. * @param mesh defines the mesh to check
  35365. * @param useInstances specifies if instances should be used
  35366. * @returns a boolean indicating if the material is ready to be used
  35367. */
  35368. Material.prototype.isReady = function (mesh, useInstances) {
  35369. return true;
  35370. };
  35371. /**
  35372. * Specifies that the submesh is ready to be used
  35373. * @param mesh defines the mesh to check
  35374. * @param subMesh defines which submesh to check
  35375. * @param useInstances specifies that instances should be used
  35376. * @returns a boolean indicating that the submesh is ready or not
  35377. */
  35378. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35379. return false;
  35380. };
  35381. /**
  35382. * Returns the material effect
  35383. * @returns the effect associated with the material
  35384. */
  35385. Material.prototype.getEffect = function () {
  35386. return this._effect;
  35387. };
  35388. /**
  35389. * Returns the current scene
  35390. * @returns a Scene
  35391. */
  35392. Material.prototype.getScene = function () {
  35393. return this._scene;
  35394. };
  35395. /**
  35396. * Specifies if the material will require alpha blending
  35397. * @returns a boolean specifying if alpha blending is needed
  35398. */
  35399. Material.prototype.needAlphaBlending = function () {
  35400. return (this.alpha < 1.0);
  35401. };
  35402. /**
  35403. * Specifies if the mesh will require alpha blending
  35404. * @param mesh defines the mesh to check
  35405. * @returns a boolean specifying if alpha blending is needed for the mesh
  35406. */
  35407. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35408. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35409. };
  35410. /**
  35411. * Specifies if this material should be rendered in alpha test mode
  35412. * @returns a boolean specifying if an alpha test is needed.
  35413. */
  35414. Material.prototype.needAlphaTesting = function () {
  35415. return false;
  35416. };
  35417. /**
  35418. * Gets the texture used for the alpha test
  35419. * @returns the texture to use for alpha testing
  35420. */
  35421. Material.prototype.getAlphaTestTexture = function () {
  35422. return null;
  35423. };
  35424. /**
  35425. * Marks the material to indicate that it needs to be re-calculated
  35426. */
  35427. Material.prototype.markDirty = function () {
  35428. this._wasPreviouslyReady = false;
  35429. };
  35430. /** @hidden */
  35431. Material.prototype._preBind = function (effect, overrideOrientation) {
  35432. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35433. var engine = this._scene.getEngine();
  35434. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35435. var reverse = orientation === Material.ClockWiseSideOrientation;
  35436. engine.enableEffect(effect ? effect : this._effect);
  35437. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35438. return reverse;
  35439. };
  35440. /**
  35441. * Binds the material to the mesh
  35442. * @param world defines the world transformation matrix
  35443. * @param mesh defines the mesh to bind the material to
  35444. */
  35445. Material.prototype.bind = function (world, mesh) {
  35446. };
  35447. /**
  35448. * Binds the submesh to the material
  35449. * @param world defines the world transformation matrix
  35450. * @param mesh defines the mesh containing the submesh
  35451. * @param subMesh defines the submesh to bind the material to
  35452. */
  35453. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35454. };
  35455. /**
  35456. * Binds the world matrix to the material
  35457. * @param world defines the world transformation matrix
  35458. */
  35459. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35460. };
  35461. /**
  35462. * Binds the scene's uniform buffer to the effect.
  35463. * @param effect defines the effect to bind to the scene uniform buffer
  35464. * @param sceneUbo defines the uniform buffer storing scene data
  35465. */
  35466. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35467. sceneUbo.bindToEffect(effect, "Scene");
  35468. };
  35469. /**
  35470. * Binds the view matrix to the effect
  35471. * @param effect defines the effect to bind the view matrix to
  35472. */
  35473. Material.prototype.bindView = function (effect) {
  35474. if (!this._useUBO) {
  35475. effect.setMatrix("view", this.getScene().getViewMatrix());
  35476. }
  35477. else {
  35478. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35479. }
  35480. };
  35481. /**
  35482. * Binds the view projection matrix to the effect
  35483. * @param effect defines the effect to bind the view projection matrix to
  35484. */
  35485. Material.prototype.bindViewProjection = function (effect) {
  35486. if (!this._useUBO) {
  35487. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35488. }
  35489. else {
  35490. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35491. }
  35492. };
  35493. /**
  35494. * Specifies if material alpha testing should be turned on for the mesh
  35495. * @param mesh defines the mesh to check
  35496. */
  35497. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35498. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35499. };
  35500. /**
  35501. * Processes to execute after binding the material to a mesh
  35502. * @param mesh defines the rendered mesh
  35503. */
  35504. Material.prototype._afterBind = function (mesh) {
  35505. this._scene._cachedMaterial = this;
  35506. if (mesh) {
  35507. this._scene._cachedVisibility = mesh.visibility;
  35508. }
  35509. else {
  35510. this._scene._cachedVisibility = 1;
  35511. }
  35512. if (mesh) {
  35513. this.onBindObservable.notifyObservers(mesh);
  35514. }
  35515. if (this.disableDepthWrite) {
  35516. var engine = this._scene.getEngine();
  35517. this._cachedDepthWriteState = engine.getDepthWrite();
  35518. engine.setDepthWrite(false);
  35519. }
  35520. };
  35521. /**
  35522. * Unbinds the material from the mesh
  35523. */
  35524. Material.prototype.unbind = function () {
  35525. this.onUnBindObservable.notifyObservers(this);
  35526. if (this.disableDepthWrite) {
  35527. var engine = this._scene.getEngine();
  35528. engine.setDepthWrite(this._cachedDepthWriteState);
  35529. }
  35530. };
  35531. /**
  35532. * Gets the active textures from the material
  35533. * @returns an array of textures
  35534. */
  35535. Material.prototype.getActiveTextures = function () {
  35536. return [];
  35537. };
  35538. /**
  35539. * Specifies if the material uses a texture
  35540. * @param texture defines the texture to check against the material
  35541. * @returns a boolean specifying if the material uses the texture
  35542. */
  35543. Material.prototype.hasTexture = function (texture) {
  35544. return false;
  35545. };
  35546. /**
  35547. * Makes a duplicate of the material, and gives it a new name
  35548. * @param name defines the new name for the duplicated material
  35549. * @returns the cloned material
  35550. */
  35551. Material.prototype.clone = function (name) {
  35552. return null;
  35553. };
  35554. /**
  35555. * Gets the meshes bound to the material
  35556. * @returns an array of meshes bound to the material
  35557. */
  35558. Material.prototype.getBindedMeshes = function () {
  35559. var result = new Array();
  35560. for (var index = 0; index < this._scene.meshes.length; index++) {
  35561. var mesh = this._scene.meshes[index];
  35562. if (mesh.material === this) {
  35563. result.push(mesh);
  35564. }
  35565. }
  35566. return result;
  35567. };
  35568. /**
  35569. * Force shader compilation
  35570. * @param mesh defines the mesh associated with this material
  35571. * @param onCompiled defines a function to execute once the material is compiled
  35572. * @param options defines the options to configure the compilation
  35573. */
  35574. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35575. var _this = this;
  35576. var localOptions = __assign({ clipPlane: false }, options);
  35577. var subMesh = new BABYLON.BaseSubMesh();
  35578. var scene = this.getScene();
  35579. var checkReady = function () {
  35580. if (!_this._scene || !_this._scene.getEngine()) {
  35581. return;
  35582. }
  35583. if (subMesh._materialDefines) {
  35584. subMesh._materialDefines._renderId = -1;
  35585. }
  35586. var clipPlaneState = scene.clipPlane;
  35587. if (localOptions.clipPlane) {
  35588. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35589. }
  35590. if (_this.storeEffectOnSubMeshes) {
  35591. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35592. if (onCompiled) {
  35593. onCompiled(_this);
  35594. }
  35595. }
  35596. else {
  35597. setTimeout(checkReady, 16);
  35598. }
  35599. }
  35600. else {
  35601. if (_this.isReady(mesh)) {
  35602. if (onCompiled) {
  35603. onCompiled(_this);
  35604. }
  35605. }
  35606. else {
  35607. setTimeout(checkReady, 16);
  35608. }
  35609. }
  35610. if (localOptions.clipPlane) {
  35611. scene.clipPlane = clipPlaneState;
  35612. }
  35613. };
  35614. checkReady();
  35615. };
  35616. /**
  35617. * Force shader compilation
  35618. * @param mesh defines the mesh that will use this material
  35619. * @param options defines additional options for compiling the shaders
  35620. * @returns a promise that resolves when the compilation completes
  35621. */
  35622. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35623. var _this = this;
  35624. return new Promise(function (resolve) {
  35625. _this.forceCompilation(mesh, function () {
  35626. resolve();
  35627. }, options);
  35628. });
  35629. };
  35630. /**
  35631. * Marks a define in the material to indicate that it needs to be re-computed
  35632. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35633. */
  35634. Material.prototype.markAsDirty = function (flag) {
  35635. if (flag & Material.TextureDirtyFlag) {
  35636. this._markAllSubMeshesAsTexturesDirty();
  35637. }
  35638. if (flag & Material.LightDirtyFlag) {
  35639. this._markAllSubMeshesAsLightsDirty();
  35640. }
  35641. if (flag & Material.FresnelDirtyFlag) {
  35642. this._markAllSubMeshesAsFresnelDirty();
  35643. }
  35644. if (flag & Material.AttributesDirtyFlag) {
  35645. this._markAllSubMeshesAsAttributesDirty();
  35646. }
  35647. if (flag & Material.MiscDirtyFlag) {
  35648. this._markAllSubMeshesAsMiscDirty();
  35649. }
  35650. this.getScene().resetCachedMaterial();
  35651. };
  35652. /**
  35653. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35654. * @param func defines a function which checks material defines against the submeshes
  35655. */
  35656. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35657. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35658. var mesh = _a[_i];
  35659. if (!mesh.subMeshes) {
  35660. continue;
  35661. }
  35662. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35663. var subMesh = _c[_b];
  35664. if (subMesh.getMaterial() !== this) {
  35665. continue;
  35666. }
  35667. if (!subMesh._materialDefines) {
  35668. continue;
  35669. }
  35670. func(subMesh._materialDefines);
  35671. }
  35672. }
  35673. };
  35674. /**
  35675. * Indicates that image processing needs to be re-calculated for all submeshes
  35676. */
  35677. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35678. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35679. };
  35680. /**
  35681. * Indicates that textures need to be re-calculated for all submeshes
  35682. */
  35683. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35684. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35685. };
  35686. /**
  35687. * Indicates that fresnel needs to be re-calculated for all submeshes
  35688. */
  35689. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35690. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35691. };
  35692. /**
  35693. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35694. */
  35695. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35696. this._markAllSubMeshesAsDirty(function (defines) {
  35697. defines.markAsFresnelDirty();
  35698. defines.markAsMiscDirty();
  35699. });
  35700. };
  35701. /**
  35702. * Indicates that lights need to be re-calculated for all submeshes
  35703. */
  35704. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35705. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35706. };
  35707. /**
  35708. * Indicates that attributes need to be re-calculated for all submeshes
  35709. */
  35710. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35711. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35712. };
  35713. /**
  35714. * Indicates that misc needs to be re-calculated for all submeshes
  35715. */
  35716. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35717. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35718. };
  35719. /**
  35720. * Indicates that textures and misc need to be re-calculated for all submeshes
  35721. */
  35722. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35723. this._markAllSubMeshesAsDirty(function (defines) {
  35724. defines.markAsTexturesDirty();
  35725. defines.markAsMiscDirty();
  35726. });
  35727. };
  35728. /**
  35729. * Disposes the material
  35730. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35731. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35732. */
  35733. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35734. // Animations
  35735. this.getScene().stopAnimation(this);
  35736. this.getScene().freeProcessedMaterials();
  35737. // Remove from scene
  35738. var index = this._scene.materials.indexOf(this);
  35739. if (index >= 0) {
  35740. this._scene.materials.splice(index, 1);
  35741. }
  35742. // Remove from meshes
  35743. for (index = 0; index < this._scene.meshes.length; index++) {
  35744. var mesh = this._scene.meshes[index];
  35745. if (mesh.material === this) {
  35746. mesh.material = null;
  35747. if (mesh.geometry) {
  35748. var geometry = (mesh.geometry);
  35749. if (this.storeEffectOnSubMeshes) {
  35750. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35751. var subMesh = _a[_i];
  35752. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35753. if (forceDisposeEffect && subMesh._materialEffect) {
  35754. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35755. }
  35756. }
  35757. }
  35758. else {
  35759. geometry._releaseVertexArrayObject(this._effect);
  35760. }
  35761. }
  35762. }
  35763. }
  35764. this._uniformBuffer.dispose();
  35765. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35766. if (forceDisposeEffect && this._effect) {
  35767. if (!this.storeEffectOnSubMeshes) {
  35768. this._scene.getEngine()._releaseEffect(this._effect);
  35769. }
  35770. this._effect = null;
  35771. }
  35772. // Callback
  35773. this.onDisposeObservable.notifyObservers(this);
  35774. this.onDisposeObservable.clear();
  35775. this.onBindObservable.clear();
  35776. this.onUnBindObservable.clear();
  35777. };
  35778. /**
  35779. * Serializes this material
  35780. * @returns the serialized material object
  35781. */
  35782. Material.prototype.serialize = function () {
  35783. return BABYLON.SerializationHelper.Serialize(this);
  35784. };
  35785. /**
  35786. * Creates a MultiMaterial from parsed MultiMaterial data.
  35787. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35788. * @param scene defines the hosting scene
  35789. * @returns a new MultiMaterial
  35790. */
  35791. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35792. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35793. multiMaterial.id = parsedMultiMaterial.id;
  35794. if (BABYLON.Tags) {
  35795. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35796. }
  35797. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35798. var subMatId = parsedMultiMaterial.materials[matIndex];
  35799. if (subMatId) {
  35800. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35801. }
  35802. else {
  35803. multiMaterial.subMaterials.push(null);
  35804. }
  35805. }
  35806. return multiMaterial;
  35807. };
  35808. /**
  35809. * Creates a material from parsed material data
  35810. * @param parsedMaterial defines parsed material data
  35811. * @param scene defines the hosting scene
  35812. * @param rootUrl defines the root URL to use to load textures
  35813. * @returns a new material
  35814. */
  35815. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35816. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35817. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35818. }
  35819. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35820. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35821. if (!BABYLON.LegacyPBRMaterial) {
  35822. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35823. return;
  35824. }
  35825. }
  35826. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35827. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35828. };
  35829. // Triangle views
  35830. Material._TriangleFillMode = 0;
  35831. Material._WireFrameFillMode = 1;
  35832. Material._PointFillMode = 2;
  35833. // Draw modes
  35834. Material._PointListDrawMode = 3;
  35835. Material._LineListDrawMode = 4;
  35836. Material._LineLoopDrawMode = 5;
  35837. Material._LineStripDrawMode = 6;
  35838. Material._TriangleStripDrawMode = 7;
  35839. Material._TriangleFanDrawMode = 8;
  35840. /**
  35841. * Stores the clock-wise side orientation
  35842. */
  35843. Material._ClockWiseSideOrientation = 0;
  35844. /**
  35845. * Stores the counter clock-wise side orientation
  35846. */
  35847. Material._CounterClockWiseSideOrientation = 1;
  35848. /**
  35849. * The dirty texture flag value
  35850. */
  35851. Material._TextureDirtyFlag = 1;
  35852. /**
  35853. * The dirty light flag value
  35854. */
  35855. Material._LightDirtyFlag = 2;
  35856. /**
  35857. * The dirty fresnel flag value
  35858. */
  35859. Material._FresnelDirtyFlag = 4;
  35860. /**
  35861. * The dirty attribute flag value
  35862. */
  35863. Material._AttributesDirtyFlag = 8;
  35864. /**
  35865. * The dirty misc flag value
  35866. */
  35867. Material._MiscDirtyFlag = 16;
  35868. __decorate([
  35869. BABYLON.serialize()
  35870. ], Material.prototype, "id", void 0);
  35871. __decorate([
  35872. BABYLON.serialize()
  35873. ], Material.prototype, "uniqueId", void 0);
  35874. __decorate([
  35875. BABYLON.serialize()
  35876. ], Material.prototype, "name", void 0);
  35877. __decorate([
  35878. BABYLON.serialize()
  35879. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35880. __decorate([
  35881. BABYLON.serialize()
  35882. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35883. __decorate([
  35884. BABYLON.serialize()
  35885. ], Material.prototype, "state", void 0);
  35886. __decorate([
  35887. BABYLON.serialize("alpha")
  35888. ], Material.prototype, "_alpha", void 0);
  35889. __decorate([
  35890. BABYLON.serialize("backFaceCulling")
  35891. ], Material.prototype, "_backFaceCulling", void 0);
  35892. __decorate([
  35893. BABYLON.serialize()
  35894. ], Material.prototype, "sideOrientation", void 0);
  35895. __decorate([
  35896. BABYLON.serialize("alphaMode")
  35897. ], Material.prototype, "_alphaMode", void 0);
  35898. __decorate([
  35899. BABYLON.serialize()
  35900. ], Material.prototype, "_needDepthPrePass", void 0);
  35901. __decorate([
  35902. BABYLON.serialize()
  35903. ], Material.prototype, "disableDepthWrite", void 0);
  35904. __decorate([
  35905. BABYLON.serialize()
  35906. ], Material.prototype, "forceDepthWrite", void 0);
  35907. __decorate([
  35908. BABYLON.serialize()
  35909. ], Material.prototype, "separateCullingPass", void 0);
  35910. __decorate([
  35911. BABYLON.serialize("fogEnabled")
  35912. ], Material.prototype, "_fogEnabled", void 0);
  35913. __decorate([
  35914. BABYLON.serialize()
  35915. ], Material.prototype, "pointSize", void 0);
  35916. __decorate([
  35917. BABYLON.serialize()
  35918. ], Material.prototype, "zOffset", void 0);
  35919. __decorate([
  35920. BABYLON.serialize()
  35921. ], Material.prototype, "wireframe", null);
  35922. __decorate([
  35923. BABYLON.serialize()
  35924. ], Material.prototype, "pointsCloud", null);
  35925. __decorate([
  35926. BABYLON.serialize()
  35927. ], Material.prototype, "fillMode", null);
  35928. return Material;
  35929. }());
  35930. BABYLON.Material = Material;
  35931. })(BABYLON || (BABYLON = {}));
  35932. //# sourceMappingURL=babylon.material.js.map
  35933. var BABYLON;
  35934. (function (BABYLON) {
  35935. var UniformBuffer = /** @class */ (function () {
  35936. /**
  35937. * Uniform buffer objects.
  35938. *
  35939. * Handles blocks of uniform on the GPU.
  35940. *
  35941. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35942. *
  35943. * For more information, please refer to :
  35944. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35945. */
  35946. function UniformBuffer(engine, data, dynamic) {
  35947. this._engine = engine;
  35948. this._noUBO = !engine.supportsUniformBuffers;
  35949. this._dynamic = dynamic;
  35950. this._data = data || [];
  35951. this._uniformLocations = {};
  35952. this._uniformSizes = {};
  35953. this._uniformLocationPointer = 0;
  35954. this._needSync = false;
  35955. if (this._noUBO) {
  35956. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35957. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35958. this.updateFloat = this._updateFloatForEffect;
  35959. this.updateFloat2 = this._updateFloat2ForEffect;
  35960. this.updateFloat3 = this._updateFloat3ForEffect;
  35961. this.updateFloat4 = this._updateFloat4ForEffect;
  35962. this.updateMatrix = this._updateMatrixForEffect;
  35963. this.updateVector3 = this._updateVector3ForEffect;
  35964. this.updateVector4 = this._updateVector4ForEffect;
  35965. this.updateColor3 = this._updateColor3ForEffect;
  35966. this.updateColor4 = this._updateColor4ForEffect;
  35967. }
  35968. else {
  35969. this._engine._uniformBuffers.push(this);
  35970. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35971. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35972. this.updateFloat = this._updateFloatForUniform;
  35973. this.updateFloat2 = this._updateFloat2ForUniform;
  35974. this.updateFloat3 = this._updateFloat3ForUniform;
  35975. this.updateFloat4 = this._updateFloat4ForUniform;
  35976. this.updateMatrix = this._updateMatrixForUniform;
  35977. this.updateVector3 = this._updateVector3ForUniform;
  35978. this.updateVector4 = this._updateVector4ForUniform;
  35979. this.updateColor3 = this._updateColor3ForUniform;
  35980. this.updateColor4 = this._updateColor4ForUniform;
  35981. }
  35982. }
  35983. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35984. // Properties
  35985. /**
  35986. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35987. * or just falling back on setUniformXXX calls.
  35988. */
  35989. get: function () {
  35990. return !this._noUBO;
  35991. },
  35992. enumerable: true,
  35993. configurable: true
  35994. });
  35995. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35996. /**
  35997. * Indicates if the WebGL underlying uniform buffer is in sync
  35998. * with the javascript cache data.
  35999. */
  36000. get: function () {
  36001. return !this._needSync;
  36002. },
  36003. enumerable: true,
  36004. configurable: true
  36005. });
  36006. /**
  36007. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36008. * Also, a dynamic UniformBuffer will disable cache verification and always
  36009. * update the underlying WebGL uniform buffer to the GPU.
  36010. */
  36011. UniformBuffer.prototype.isDynamic = function () {
  36012. return this._dynamic !== undefined;
  36013. };
  36014. /**
  36015. * The data cache on JS side.
  36016. */
  36017. UniformBuffer.prototype.getData = function () {
  36018. return this._bufferData;
  36019. };
  36020. /**
  36021. * The underlying WebGL Uniform buffer.
  36022. */
  36023. UniformBuffer.prototype.getBuffer = function () {
  36024. return this._buffer;
  36025. };
  36026. /**
  36027. * std140 layout specifies how to align data within an UBO structure.
  36028. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36029. * for specs.
  36030. */
  36031. UniformBuffer.prototype._fillAlignment = function (size) {
  36032. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36033. // and 4x4 matrices
  36034. // TODO : change if other types are used
  36035. var alignment;
  36036. if (size <= 2) {
  36037. alignment = size;
  36038. }
  36039. else {
  36040. alignment = 4;
  36041. }
  36042. if ((this._uniformLocationPointer % alignment) !== 0) {
  36043. var oldPointer = this._uniformLocationPointer;
  36044. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36045. var diff = this._uniformLocationPointer - oldPointer;
  36046. for (var i = 0; i < diff; i++) {
  36047. this._data.push(0);
  36048. }
  36049. }
  36050. };
  36051. /**
  36052. * Adds an uniform in the buffer.
  36053. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36054. * for the layout to be correct !
  36055. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36056. * @param {number|number[]} size Data size, or data directly.
  36057. */
  36058. UniformBuffer.prototype.addUniform = function (name, size) {
  36059. if (this._noUBO) {
  36060. return;
  36061. }
  36062. if (this._uniformLocations[name] !== undefined) {
  36063. // Already existing uniform
  36064. return;
  36065. }
  36066. // This function must be called in the order of the shader layout !
  36067. // size can be the size of the uniform, or data directly
  36068. var data;
  36069. if (size instanceof Array) {
  36070. data = size;
  36071. size = data.length;
  36072. }
  36073. else {
  36074. size = size;
  36075. data = [];
  36076. // Fill with zeros
  36077. for (var i = 0; i < size; i++) {
  36078. data.push(0);
  36079. }
  36080. }
  36081. this._fillAlignment(size);
  36082. this._uniformSizes[name] = size;
  36083. this._uniformLocations[name] = this._uniformLocationPointer;
  36084. this._uniformLocationPointer += size;
  36085. for (var i = 0; i < size; i++) {
  36086. this._data.push(data[i]);
  36087. }
  36088. this._needSync = true;
  36089. };
  36090. /**
  36091. * Wrapper for addUniform.
  36092. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36093. * @param {Matrix} mat A 4x4 matrix.
  36094. */
  36095. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36096. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36097. };
  36098. /**
  36099. * Wrapper for addUniform.
  36100. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36101. * @param {number} x
  36102. * @param {number} y
  36103. */
  36104. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36105. var temp = [x, y];
  36106. this.addUniform(name, temp);
  36107. };
  36108. /**
  36109. * Wrapper for addUniform.
  36110. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36111. * @param {number} x
  36112. * @param {number} y
  36113. * @param {number} z
  36114. */
  36115. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36116. var temp = [x, y, z];
  36117. this.addUniform(name, temp);
  36118. };
  36119. /**
  36120. * Wrapper for addUniform.
  36121. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36122. * @param {Color3} color
  36123. */
  36124. UniformBuffer.prototype.addColor3 = function (name, color) {
  36125. var temp = new Array();
  36126. color.toArray(temp);
  36127. this.addUniform(name, temp);
  36128. };
  36129. /**
  36130. * Wrapper for addUniform.
  36131. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36132. * @param {Color3} color
  36133. * @param {number} alpha
  36134. */
  36135. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36136. var temp = new Array();
  36137. color.toArray(temp);
  36138. temp.push(alpha);
  36139. this.addUniform(name, temp);
  36140. };
  36141. /**
  36142. * Wrapper for addUniform.
  36143. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36144. * @param {Vector3} vector
  36145. */
  36146. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36147. var temp = new Array();
  36148. vector.toArray(temp);
  36149. this.addUniform(name, temp);
  36150. };
  36151. /**
  36152. * Wrapper for addUniform.
  36153. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36154. */
  36155. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36156. this.addUniform(name, 12);
  36157. };
  36158. /**
  36159. * Wrapper for addUniform.
  36160. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36161. */
  36162. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36163. this.addUniform(name, 8);
  36164. };
  36165. /**
  36166. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36167. */
  36168. UniformBuffer.prototype.create = function () {
  36169. if (this._noUBO) {
  36170. return;
  36171. }
  36172. if (this._buffer) {
  36173. return; // nothing to do
  36174. }
  36175. // See spec, alignment must be filled as a vec4
  36176. this._fillAlignment(4);
  36177. this._bufferData = new Float32Array(this._data);
  36178. this._rebuild();
  36179. this._needSync = true;
  36180. };
  36181. UniformBuffer.prototype._rebuild = function () {
  36182. if (this._noUBO) {
  36183. return;
  36184. }
  36185. if (this._dynamic) {
  36186. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36187. }
  36188. else {
  36189. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36190. }
  36191. };
  36192. /**
  36193. * Updates the WebGL Uniform Buffer on the GPU.
  36194. * If the `dynamic` flag is set to true, no cache comparison is done.
  36195. * Otherwise, the buffer will be updated only if the cache differs.
  36196. */
  36197. UniformBuffer.prototype.update = function () {
  36198. if (!this._buffer) {
  36199. this.create();
  36200. return;
  36201. }
  36202. if (!this._dynamic && !this._needSync) {
  36203. return;
  36204. }
  36205. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36206. this._needSync = false;
  36207. };
  36208. /**
  36209. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36210. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36211. * @param {number[]|Float32Array} data Flattened data
  36212. * @param {number} size Size of the data.
  36213. */
  36214. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36215. var location = this._uniformLocations[uniformName];
  36216. if (location === undefined) {
  36217. if (this._buffer) {
  36218. // Cannot add an uniform if the buffer is already created
  36219. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36220. return;
  36221. }
  36222. this.addUniform(uniformName, size);
  36223. location = this._uniformLocations[uniformName];
  36224. }
  36225. if (!this._buffer) {
  36226. this.create();
  36227. }
  36228. if (!this._dynamic) {
  36229. // Cache for static uniform buffers
  36230. var changed = false;
  36231. for (var i = 0; i < size; i++) {
  36232. if (this._bufferData[location + i] !== data[i]) {
  36233. changed = true;
  36234. this._bufferData[location + i] = data[i];
  36235. }
  36236. }
  36237. this._needSync = this._needSync || changed;
  36238. }
  36239. else {
  36240. // No cache for dynamic
  36241. for (var i = 0; i < size; i++) {
  36242. this._bufferData[location + i] = data[i];
  36243. }
  36244. }
  36245. };
  36246. // Update methods
  36247. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36248. // To match std140, matrix must be realigned
  36249. for (var i = 0; i < 3; i++) {
  36250. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36251. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36252. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36253. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36254. }
  36255. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36256. };
  36257. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36258. this._currentEffect.setMatrix3x3(name, matrix);
  36259. };
  36260. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36261. this._currentEffect.setMatrix2x2(name, matrix);
  36262. };
  36263. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36264. // To match std140, matrix must be realigned
  36265. for (var i = 0; i < 2; i++) {
  36266. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36267. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36268. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36269. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36270. }
  36271. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36272. };
  36273. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36274. this._currentEffect.setFloat(name, x);
  36275. };
  36276. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36277. UniformBuffer._tempBuffer[0] = x;
  36278. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36279. };
  36280. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36281. if (suffix === void 0) { suffix = ""; }
  36282. this._currentEffect.setFloat2(name + suffix, x, y);
  36283. };
  36284. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36285. if (suffix === void 0) { suffix = ""; }
  36286. UniformBuffer._tempBuffer[0] = x;
  36287. UniformBuffer._tempBuffer[1] = y;
  36288. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36289. };
  36290. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36291. if (suffix === void 0) { suffix = ""; }
  36292. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36293. };
  36294. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36295. if (suffix === void 0) { suffix = ""; }
  36296. UniformBuffer._tempBuffer[0] = x;
  36297. UniformBuffer._tempBuffer[1] = y;
  36298. UniformBuffer._tempBuffer[2] = z;
  36299. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36300. };
  36301. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36302. if (suffix === void 0) { suffix = ""; }
  36303. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36304. };
  36305. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36306. if (suffix === void 0) { suffix = ""; }
  36307. UniformBuffer._tempBuffer[0] = x;
  36308. UniformBuffer._tempBuffer[1] = y;
  36309. UniformBuffer._tempBuffer[2] = z;
  36310. UniformBuffer._tempBuffer[3] = w;
  36311. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36312. };
  36313. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36314. this._currentEffect.setMatrix(name, mat);
  36315. };
  36316. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36317. this.updateUniform(name, mat.toArray(), 16);
  36318. };
  36319. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36320. this._currentEffect.setVector3(name, vector);
  36321. };
  36322. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36323. vector.toArray(UniformBuffer._tempBuffer);
  36324. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36325. };
  36326. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36327. this._currentEffect.setVector4(name, vector);
  36328. };
  36329. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36330. vector.toArray(UniformBuffer._tempBuffer);
  36331. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36332. };
  36333. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36334. if (suffix === void 0) { suffix = ""; }
  36335. this._currentEffect.setColor3(name + suffix, color);
  36336. };
  36337. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36338. if (suffix === void 0) { suffix = ""; }
  36339. color.toArray(UniformBuffer._tempBuffer);
  36340. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36341. };
  36342. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36343. if (suffix === void 0) { suffix = ""; }
  36344. this._currentEffect.setColor4(name + suffix, color, alpha);
  36345. };
  36346. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36347. if (suffix === void 0) { suffix = ""; }
  36348. color.toArray(UniformBuffer._tempBuffer);
  36349. UniformBuffer._tempBuffer[3] = alpha;
  36350. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36351. };
  36352. /**
  36353. * Sets a sampler uniform on the effect.
  36354. * @param {string} name Name of the sampler.
  36355. * @param {Texture} texture
  36356. */
  36357. UniformBuffer.prototype.setTexture = function (name, texture) {
  36358. this._currentEffect.setTexture(name, texture);
  36359. };
  36360. /**
  36361. * Directly updates the value of the uniform in the cache AND on the GPU.
  36362. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36363. * @param {number[]|Float32Array} data Flattened data
  36364. */
  36365. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36366. this.updateUniform(uniformName, data, data.length);
  36367. this.update();
  36368. };
  36369. /**
  36370. * Binds this uniform buffer to an effect.
  36371. * @param {Effect} effect
  36372. * @param {string} name Name of the uniform block in the shader.
  36373. */
  36374. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36375. this._currentEffect = effect;
  36376. if (this._noUBO || !this._buffer) {
  36377. return;
  36378. }
  36379. effect.bindUniformBuffer(this._buffer, name);
  36380. };
  36381. /**
  36382. * Disposes the uniform buffer.
  36383. */
  36384. UniformBuffer.prototype.dispose = function () {
  36385. if (this._noUBO) {
  36386. return;
  36387. }
  36388. var index = this._engine._uniformBuffers.indexOf(this);
  36389. if (index !== -1) {
  36390. this._engine._uniformBuffers.splice(index, 1);
  36391. }
  36392. if (!this._buffer) {
  36393. return;
  36394. }
  36395. if (this._engine._releaseBuffer(this._buffer)) {
  36396. this._buffer = null;
  36397. }
  36398. };
  36399. // Pool for avoiding memory leaks
  36400. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36401. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36402. return UniformBuffer;
  36403. }());
  36404. BABYLON.UniformBuffer = UniformBuffer;
  36405. })(BABYLON || (BABYLON = {}));
  36406. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36407. var BABYLON;
  36408. (function (BABYLON) {
  36409. /**
  36410. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36411. */
  36412. var VertexData = /** @class */ (function () {
  36413. function VertexData() {
  36414. }
  36415. /**
  36416. * Uses the passed data array to set the set the values for the specified kind of data
  36417. * @param data a linear array of floating numbers
  36418. * @param kind the type of data that is being set, eg positions, colors etc
  36419. */
  36420. VertexData.prototype.set = function (data, kind) {
  36421. switch (kind) {
  36422. case BABYLON.VertexBuffer.PositionKind:
  36423. this.positions = data;
  36424. break;
  36425. case BABYLON.VertexBuffer.NormalKind:
  36426. this.normals = data;
  36427. break;
  36428. case BABYLON.VertexBuffer.TangentKind:
  36429. this.tangents = data;
  36430. break;
  36431. case BABYLON.VertexBuffer.UVKind:
  36432. this.uvs = data;
  36433. break;
  36434. case BABYLON.VertexBuffer.UV2Kind:
  36435. this.uvs2 = data;
  36436. break;
  36437. case BABYLON.VertexBuffer.UV3Kind:
  36438. this.uvs3 = data;
  36439. break;
  36440. case BABYLON.VertexBuffer.UV4Kind:
  36441. this.uvs4 = data;
  36442. break;
  36443. case BABYLON.VertexBuffer.UV5Kind:
  36444. this.uvs5 = data;
  36445. break;
  36446. case BABYLON.VertexBuffer.UV6Kind:
  36447. this.uvs6 = data;
  36448. break;
  36449. case BABYLON.VertexBuffer.ColorKind:
  36450. this.colors = data;
  36451. break;
  36452. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36453. this.matricesIndices = data;
  36454. break;
  36455. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36456. this.matricesWeights = data;
  36457. break;
  36458. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36459. this.matricesIndicesExtra = data;
  36460. break;
  36461. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36462. this.matricesWeightsExtra = data;
  36463. break;
  36464. }
  36465. };
  36466. /**
  36467. * Associates the vertexData to the passed Mesh.
  36468. * Sets it as updatable or not (default `false`)
  36469. * @param mesh the mesh the vertexData is applied to
  36470. * @param updatable when used and having the value true allows new data to update the vertexData
  36471. * @returns the VertexData
  36472. */
  36473. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36474. this._applyTo(mesh, updatable);
  36475. return this;
  36476. };
  36477. /**
  36478. * Associates the vertexData to the passed Geometry.
  36479. * Sets it as updatable or not (default `false`)
  36480. * @param geometry the geometry the vertexData is applied to
  36481. * @param updatable when used and having the value true allows new data to update the vertexData
  36482. * @returns VertexData
  36483. */
  36484. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36485. this._applyTo(geometry, updatable);
  36486. return this;
  36487. };
  36488. /**
  36489. * Updates the associated mesh
  36490. * @param mesh the mesh to be updated
  36491. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36492. * @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
  36493. * @returns VertexData
  36494. */
  36495. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36496. this._update(mesh);
  36497. return this;
  36498. };
  36499. /**
  36500. * Updates the associated geometry
  36501. * @param geometry the geometry to be updated
  36502. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36503. * @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
  36504. * @returns VertexData.
  36505. */
  36506. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36507. this._update(geometry);
  36508. return this;
  36509. };
  36510. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36511. if (updatable === void 0) { updatable = false; }
  36512. if (this.positions) {
  36513. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36514. }
  36515. if (this.normals) {
  36516. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36517. }
  36518. if (this.tangents) {
  36519. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36520. }
  36521. if (this.uvs) {
  36522. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36523. }
  36524. if (this.uvs2) {
  36525. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36526. }
  36527. if (this.uvs3) {
  36528. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36529. }
  36530. if (this.uvs4) {
  36531. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36532. }
  36533. if (this.uvs5) {
  36534. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36535. }
  36536. if (this.uvs6) {
  36537. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36538. }
  36539. if (this.colors) {
  36540. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36541. }
  36542. if (this.matricesIndices) {
  36543. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36544. }
  36545. if (this.matricesWeights) {
  36546. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36547. }
  36548. if (this.matricesIndicesExtra) {
  36549. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36550. }
  36551. if (this.matricesWeightsExtra) {
  36552. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36553. }
  36554. if (this.indices) {
  36555. meshOrGeometry.setIndices(this.indices, null, updatable);
  36556. }
  36557. return this;
  36558. };
  36559. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36560. if (this.positions) {
  36561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36562. }
  36563. if (this.normals) {
  36564. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36565. }
  36566. if (this.tangents) {
  36567. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36568. }
  36569. if (this.uvs) {
  36570. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36571. }
  36572. if (this.uvs2) {
  36573. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36574. }
  36575. if (this.uvs3) {
  36576. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36577. }
  36578. if (this.uvs4) {
  36579. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36580. }
  36581. if (this.uvs5) {
  36582. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36583. }
  36584. if (this.uvs6) {
  36585. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36586. }
  36587. if (this.colors) {
  36588. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36589. }
  36590. if (this.matricesIndices) {
  36591. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36592. }
  36593. if (this.matricesWeights) {
  36594. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36595. }
  36596. if (this.matricesIndicesExtra) {
  36597. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36598. }
  36599. if (this.matricesWeightsExtra) {
  36600. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36601. }
  36602. if (this.indices) {
  36603. meshOrGeometry.setIndices(this.indices, null);
  36604. }
  36605. return this;
  36606. };
  36607. /**
  36608. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36609. * @param matrix the transforming matrix
  36610. * @returns the VertexData
  36611. */
  36612. VertexData.prototype.transform = function (matrix) {
  36613. var transformed = BABYLON.Vector3.Zero();
  36614. var index;
  36615. if (this.positions) {
  36616. var position = BABYLON.Vector3.Zero();
  36617. for (index = 0; index < this.positions.length; index += 3) {
  36618. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36619. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36620. this.positions[index] = transformed.x;
  36621. this.positions[index + 1] = transformed.y;
  36622. this.positions[index + 2] = transformed.z;
  36623. }
  36624. }
  36625. if (this.normals) {
  36626. var normal = BABYLON.Vector3.Zero();
  36627. for (index = 0; index < this.normals.length; index += 3) {
  36628. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36629. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36630. this.normals[index] = transformed.x;
  36631. this.normals[index + 1] = transformed.y;
  36632. this.normals[index + 2] = transformed.z;
  36633. }
  36634. }
  36635. if (this.tangents) {
  36636. var tangent = BABYLON.Vector4.Zero();
  36637. var tangentTransformed = BABYLON.Vector4.Zero();
  36638. for (index = 0; index < this.tangents.length; index += 4) {
  36639. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36640. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36641. this.tangents[index] = tangentTransformed.x;
  36642. this.tangents[index + 1] = tangentTransformed.y;
  36643. this.tangents[index + 2] = tangentTransformed.z;
  36644. this.tangents[index + 3] = tangentTransformed.w;
  36645. }
  36646. }
  36647. return this;
  36648. };
  36649. /**
  36650. * Merges the passed VertexData into the current one
  36651. * @param other the VertexData to be merged into the current one
  36652. * @returns the modified VertexData
  36653. */
  36654. VertexData.prototype.merge = function (other) {
  36655. this._validate();
  36656. other._validate();
  36657. if (!this.normals !== !other.normals ||
  36658. !this.tangents !== !other.tangents ||
  36659. !this.uvs !== !other.uvs ||
  36660. !this.uvs2 !== !other.uvs2 ||
  36661. !this.uvs3 !== !other.uvs3 ||
  36662. !this.uvs4 !== !other.uvs4 ||
  36663. !this.uvs5 !== !other.uvs5 ||
  36664. !this.uvs6 !== !other.uvs6 ||
  36665. !this.colors !== !other.colors ||
  36666. !this.matricesIndices !== !other.matricesIndices ||
  36667. !this.matricesWeights !== !other.matricesWeights ||
  36668. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36669. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36670. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36671. }
  36672. if (other.indices) {
  36673. if (!this.indices) {
  36674. this.indices = [];
  36675. }
  36676. var offset = this.positions ? this.positions.length / 3 : 0;
  36677. for (var index = 0; index < other.indices.length; index++) {
  36678. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36679. this.indices.push(other.indices[index] + offset);
  36680. }
  36681. }
  36682. this.positions = this._mergeElement(this.positions, other.positions);
  36683. this.normals = this._mergeElement(this.normals, other.normals);
  36684. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36685. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36686. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36687. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36688. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36689. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36690. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36691. this.colors = this._mergeElement(this.colors, other.colors);
  36692. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36693. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36694. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36695. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36696. return this;
  36697. };
  36698. VertexData.prototype._mergeElement = function (source, other) {
  36699. if (!source) {
  36700. return other;
  36701. }
  36702. if (!other) {
  36703. return source;
  36704. }
  36705. var len = other.length + source.length;
  36706. var isSrcTypedArray = source instanceof Float32Array;
  36707. var isOthTypedArray = other instanceof Float32Array;
  36708. // use non-loop method when the source is Float32Array
  36709. if (isSrcTypedArray) {
  36710. var ret32 = new Float32Array(len);
  36711. ret32.set(source);
  36712. ret32.set(other, source.length);
  36713. return ret32;
  36714. // source is number[], when other is also use concat
  36715. }
  36716. else if (!isOthTypedArray) {
  36717. return source.concat(other);
  36718. // source is a number[], but other is a Float32Array, loop required
  36719. }
  36720. else {
  36721. var ret = source.slice(0); // copy source to a separate array
  36722. for (var i = 0, len = other.length; i < len; i++) {
  36723. ret.push(other[i]);
  36724. }
  36725. return ret;
  36726. }
  36727. };
  36728. VertexData.prototype._validate = function () {
  36729. if (!this.positions) {
  36730. throw new Error("Positions are required");
  36731. }
  36732. var getElementCount = function (kind, values) {
  36733. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36734. if ((values.length % stride) !== 0) {
  36735. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36736. }
  36737. return values.length / stride;
  36738. };
  36739. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36740. var validateElementCount = function (kind, values) {
  36741. var elementCount = getElementCount(kind, values);
  36742. if (elementCount !== positionsElementCount) {
  36743. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36744. }
  36745. };
  36746. if (this.normals)
  36747. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36748. if (this.tangents)
  36749. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36750. if (this.uvs)
  36751. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36752. if (this.uvs2)
  36753. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36754. if (this.uvs3)
  36755. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36756. if (this.uvs4)
  36757. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36758. if (this.uvs5)
  36759. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36760. if (this.uvs6)
  36761. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36762. if (this.colors)
  36763. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36764. if (this.matricesIndices)
  36765. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36766. if (this.matricesWeights)
  36767. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36768. if (this.matricesIndicesExtra)
  36769. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36770. if (this.matricesWeightsExtra)
  36771. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36772. };
  36773. /**
  36774. * Serializes the VertexData
  36775. * @returns a serialized object
  36776. */
  36777. VertexData.prototype.serialize = function () {
  36778. var serializationObject = this.serialize();
  36779. if (this.positions) {
  36780. serializationObject.positions = this.positions;
  36781. }
  36782. if (this.normals) {
  36783. serializationObject.normals = this.normals;
  36784. }
  36785. if (this.tangents) {
  36786. serializationObject.tangents = this.tangents;
  36787. }
  36788. if (this.uvs) {
  36789. serializationObject.uvs = this.uvs;
  36790. }
  36791. if (this.uvs2) {
  36792. serializationObject.uvs2 = this.uvs2;
  36793. }
  36794. if (this.uvs3) {
  36795. serializationObject.uvs3 = this.uvs3;
  36796. }
  36797. if (this.uvs4) {
  36798. serializationObject.uvs4 = this.uvs4;
  36799. }
  36800. if (this.uvs5) {
  36801. serializationObject.uvs5 = this.uvs5;
  36802. }
  36803. if (this.uvs6) {
  36804. serializationObject.uvs6 = this.uvs6;
  36805. }
  36806. if (this.colors) {
  36807. serializationObject.colors = this.colors;
  36808. }
  36809. if (this.matricesIndices) {
  36810. serializationObject.matricesIndices = this.matricesIndices;
  36811. serializationObject.matricesIndices._isExpanded = true;
  36812. }
  36813. if (this.matricesWeights) {
  36814. serializationObject.matricesWeights = this.matricesWeights;
  36815. }
  36816. if (this.matricesIndicesExtra) {
  36817. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36818. serializationObject.matricesIndicesExtra._isExpanded = true;
  36819. }
  36820. if (this.matricesWeightsExtra) {
  36821. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36822. }
  36823. serializationObject.indices = this.indices;
  36824. return serializationObject;
  36825. };
  36826. // Statics
  36827. /**
  36828. * Extracts the vertexData from a mesh
  36829. * @param mesh the mesh from which to extract the VertexData
  36830. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36831. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36832. * @returns the object VertexData associated to the passed mesh
  36833. */
  36834. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36835. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36836. };
  36837. /**
  36838. * Extracts the vertexData from the geometry
  36839. * @param geometry the geometry from which to extract the VertexData
  36840. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36841. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36842. * @returns the object VertexData associated to the passed mesh
  36843. */
  36844. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36845. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36846. };
  36847. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36848. var result = new VertexData();
  36849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36850. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36851. }
  36852. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36853. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36854. }
  36855. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36856. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36857. }
  36858. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36859. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36860. }
  36861. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36862. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36863. }
  36864. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36865. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36866. }
  36867. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36868. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36869. }
  36870. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36871. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36872. }
  36873. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36874. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36875. }
  36876. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36877. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36878. }
  36879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36880. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36881. }
  36882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36883. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36884. }
  36885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36886. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36887. }
  36888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36889. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36890. }
  36891. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36892. return result;
  36893. };
  36894. /**
  36895. * Creates the VertexData for a Ribbon
  36896. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36897. * * pathArray array of paths, each of which an array of successive Vector3
  36898. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36899. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36900. * * 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
  36901. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36902. * * 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)
  36903. * * 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)
  36904. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36905. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36906. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36907. * @returns the VertexData of the ribbon
  36908. */
  36909. VertexData.CreateRibbon = function (options) {
  36910. var pathArray = options.pathArray;
  36911. var closeArray = options.closeArray || false;
  36912. var closePath = options.closePath || false;
  36913. var invertUV = options.invertUV || false;
  36914. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36915. var offset = options.offset || defaultOffset;
  36916. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36917. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36918. var customUV = options.uvs;
  36919. var customColors = options.colors;
  36920. var positions = [];
  36921. var indices = [];
  36922. var normals = [];
  36923. var uvs = [];
  36924. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36925. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36926. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36927. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36928. var minlg; // minimal length among all paths from pathArray
  36929. var lg = []; // array of path lengths : nb of vertex per path
  36930. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36931. var p; // path iterator
  36932. var i; // point iterator
  36933. var j; // point iterator
  36934. // if single path in pathArray
  36935. if (pathArray.length < 2) {
  36936. var ar1 = [];
  36937. var ar2 = [];
  36938. for (i = 0; i < pathArray[0].length - offset; i++) {
  36939. ar1.push(pathArray[0][i]);
  36940. ar2.push(pathArray[0][i + offset]);
  36941. }
  36942. pathArray = [ar1, ar2];
  36943. }
  36944. // positions and horizontal distances (u)
  36945. var idc = 0;
  36946. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36947. var path;
  36948. var l;
  36949. minlg = pathArray[0].length;
  36950. var vectlg;
  36951. var dist;
  36952. for (p = 0; p < pathArray.length; p++) {
  36953. uTotalDistance[p] = 0;
  36954. us[p] = [0];
  36955. path = pathArray[p];
  36956. l = path.length;
  36957. minlg = (minlg < l) ? minlg : l;
  36958. j = 0;
  36959. while (j < l) {
  36960. positions.push(path[j].x, path[j].y, path[j].z);
  36961. if (j > 0) {
  36962. vectlg = path[j].subtract(path[j - 1]).length();
  36963. dist = vectlg + uTotalDistance[p];
  36964. us[p].push(dist);
  36965. uTotalDistance[p] = dist;
  36966. }
  36967. j++;
  36968. }
  36969. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36970. j--;
  36971. positions.push(path[0].x, path[0].y, path[0].z);
  36972. vectlg = path[j].subtract(path[0]).length();
  36973. dist = vectlg + uTotalDistance[p];
  36974. us[p].push(dist);
  36975. uTotalDistance[p] = dist;
  36976. }
  36977. lg[p] = l + closePathCorr;
  36978. idx[p] = idc;
  36979. idc += (l + closePathCorr);
  36980. }
  36981. // vertical distances (v)
  36982. var path1;
  36983. var path2;
  36984. var vertex1 = null;
  36985. var vertex2 = null;
  36986. for (i = 0; i < minlg + closePathCorr; i++) {
  36987. vTotalDistance[i] = 0;
  36988. vs[i] = [0];
  36989. for (p = 0; p < pathArray.length - 1; p++) {
  36990. path1 = pathArray[p];
  36991. path2 = pathArray[p + 1];
  36992. if (i === minlg) { // closePath
  36993. vertex1 = path1[0];
  36994. vertex2 = path2[0];
  36995. }
  36996. else {
  36997. vertex1 = path1[i];
  36998. vertex2 = path2[i];
  36999. }
  37000. vectlg = vertex2.subtract(vertex1).length();
  37001. dist = vectlg + vTotalDistance[i];
  37002. vs[i].push(dist);
  37003. vTotalDistance[i] = dist;
  37004. }
  37005. if (closeArray && vertex2 && vertex1) {
  37006. path1 = pathArray[p];
  37007. path2 = pathArray[0];
  37008. if (i === minlg) { // closePath
  37009. vertex2 = path2[0];
  37010. }
  37011. vectlg = vertex2.subtract(vertex1).length();
  37012. dist = vectlg + vTotalDistance[i];
  37013. vTotalDistance[i] = dist;
  37014. }
  37015. }
  37016. // uvs
  37017. var u;
  37018. var v;
  37019. if (customUV) {
  37020. for (p = 0; p < customUV.length; p++) {
  37021. uvs.push(customUV[p].x, customUV[p].y);
  37022. }
  37023. }
  37024. else {
  37025. for (p = 0; p < pathArray.length; p++) {
  37026. for (i = 0; i < minlg + closePathCorr; i++) {
  37027. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37028. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37029. if (invertUV) {
  37030. uvs.push(v, u);
  37031. }
  37032. else {
  37033. uvs.push(u, v);
  37034. }
  37035. }
  37036. }
  37037. }
  37038. // indices
  37039. p = 0; // path index
  37040. var pi = 0; // positions array index
  37041. var l1 = lg[p] - 1; // path1 length
  37042. var l2 = lg[p + 1] - 1; // path2 length
  37043. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37044. var shft = idx[1] - idx[0]; // shift
  37045. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37046. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37047. // 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
  37048. indices.push(pi, pi + shft, pi + 1);
  37049. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37050. pi += 1;
  37051. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37052. p++;
  37053. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37054. shft = idx[0] - idx[p];
  37055. l1 = lg[p] - 1;
  37056. l2 = lg[0] - 1;
  37057. }
  37058. else {
  37059. shft = idx[p + 1] - idx[p];
  37060. l1 = lg[p] - 1;
  37061. l2 = lg[p + 1] - 1;
  37062. }
  37063. pi = idx[p];
  37064. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37065. }
  37066. }
  37067. // normals
  37068. VertexData.ComputeNormals(positions, indices, normals);
  37069. if (closePath) { // update both the first and last vertex normals to their average value
  37070. var indexFirst = 0;
  37071. var indexLast = 0;
  37072. for (p = 0; p < pathArray.length; p++) {
  37073. indexFirst = idx[p] * 3;
  37074. if (p + 1 < pathArray.length) {
  37075. indexLast = (idx[p + 1] - 1) * 3;
  37076. }
  37077. else {
  37078. indexLast = normals.length - 3;
  37079. }
  37080. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37081. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37082. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37083. normals[indexLast] = normals[indexFirst];
  37084. normals[indexLast + 1] = normals[indexFirst + 1];
  37085. normals[indexLast + 2] = normals[indexFirst + 2];
  37086. }
  37087. }
  37088. // sides
  37089. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37090. // Colors
  37091. var colors = null;
  37092. if (customColors) {
  37093. colors = new Float32Array(customColors.length * 4);
  37094. for (var c = 0; c < customColors.length; c++) {
  37095. colors[c * 4] = customColors[c].r;
  37096. colors[c * 4 + 1] = customColors[c].g;
  37097. colors[c * 4 + 2] = customColors[c].b;
  37098. colors[c * 4 + 3] = customColors[c].a;
  37099. }
  37100. }
  37101. // Result
  37102. var vertexData = new VertexData();
  37103. var positions32 = new Float32Array(positions);
  37104. var normals32 = new Float32Array(normals);
  37105. var uvs32 = new Float32Array(uvs);
  37106. vertexData.indices = indices;
  37107. vertexData.positions = positions32;
  37108. vertexData.normals = normals32;
  37109. vertexData.uvs = uvs32;
  37110. if (colors) {
  37111. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37112. }
  37113. if (closePath) {
  37114. vertexData._idx = idx;
  37115. }
  37116. return vertexData;
  37117. };
  37118. /**
  37119. * Creates the VertexData for a box
  37120. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37121. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37122. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37123. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37124. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37125. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37126. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37127. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37128. * * 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)
  37129. * * 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)
  37130. * @returns the VertexData of the box
  37131. */
  37132. VertexData.CreateBox = function (options) {
  37133. var normalsSource = [
  37134. new BABYLON.Vector3(0, 0, 1),
  37135. new BABYLON.Vector3(0, 0, -1),
  37136. new BABYLON.Vector3(1, 0, 0),
  37137. new BABYLON.Vector3(-1, 0, 0),
  37138. new BABYLON.Vector3(0, 1, 0),
  37139. new BABYLON.Vector3(0, -1, 0)
  37140. ];
  37141. var indices = [];
  37142. var positions = [];
  37143. var normals = [];
  37144. var uvs = [];
  37145. var width = options.width || options.size || 1;
  37146. var height = options.height || options.size || 1;
  37147. var depth = options.depth || options.size || 1;
  37148. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37149. var faceUV = options.faceUV || new Array(6);
  37150. var faceColors = options.faceColors;
  37151. var colors = [];
  37152. // default face colors and UV if undefined
  37153. for (var f = 0; f < 6; f++) {
  37154. if (faceUV[f] === undefined) {
  37155. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37156. }
  37157. if (faceColors && faceColors[f] === undefined) {
  37158. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37159. }
  37160. }
  37161. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37162. // Create each face in turn.
  37163. for (var index = 0; index < normalsSource.length; index++) {
  37164. var normal = normalsSource[index];
  37165. // Get two vectors perpendicular to the face normal and to each other.
  37166. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37167. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37168. // Six indices (two triangles) per face.
  37169. var verticesLength = positions.length / 3;
  37170. indices.push(verticesLength);
  37171. indices.push(verticesLength + 1);
  37172. indices.push(verticesLength + 2);
  37173. indices.push(verticesLength);
  37174. indices.push(verticesLength + 2);
  37175. indices.push(verticesLength + 3);
  37176. // Four vertices per face.
  37177. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37178. positions.push(vertex.x, vertex.y, vertex.z);
  37179. normals.push(normal.x, normal.y, normal.z);
  37180. uvs.push(faceUV[index].z, faceUV[index].w);
  37181. if (faceColors) {
  37182. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37183. }
  37184. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37185. positions.push(vertex.x, vertex.y, vertex.z);
  37186. normals.push(normal.x, normal.y, normal.z);
  37187. uvs.push(faceUV[index].x, faceUV[index].w);
  37188. if (faceColors) {
  37189. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37190. }
  37191. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37192. positions.push(vertex.x, vertex.y, vertex.z);
  37193. normals.push(normal.x, normal.y, normal.z);
  37194. uvs.push(faceUV[index].x, faceUV[index].y);
  37195. if (faceColors) {
  37196. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37197. }
  37198. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37199. positions.push(vertex.x, vertex.y, vertex.z);
  37200. normals.push(normal.x, normal.y, normal.z);
  37201. uvs.push(faceUV[index].z, faceUV[index].y);
  37202. if (faceColors) {
  37203. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37204. }
  37205. }
  37206. // sides
  37207. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37208. // Result
  37209. var vertexData = new VertexData();
  37210. vertexData.indices = indices;
  37211. vertexData.positions = positions;
  37212. vertexData.normals = normals;
  37213. vertexData.uvs = uvs;
  37214. if (faceColors) {
  37215. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37216. vertexData.colors = totalColors;
  37217. }
  37218. return vertexData;
  37219. };
  37220. /**
  37221. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37222. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37223. * * segments sets the number of horizontal strips optional, default 32
  37224. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37225. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37226. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37227. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37228. * * 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
  37229. * * 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
  37230. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37231. * * 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)
  37232. * * 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)
  37233. * @returns the VertexData of the ellipsoid
  37234. */
  37235. VertexData.CreateSphere = function (options) {
  37236. var segments = options.segments || 32;
  37237. var diameterX = options.diameterX || options.diameter || 1;
  37238. var diameterY = options.diameterY || options.diameter || 1;
  37239. var diameterZ = options.diameterZ || options.diameter || 1;
  37240. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37241. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37242. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37243. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37244. var totalZRotationSteps = 2 + segments;
  37245. var totalYRotationSteps = 2 * totalZRotationSteps;
  37246. var indices = [];
  37247. var positions = [];
  37248. var normals = [];
  37249. var uvs = [];
  37250. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37251. var normalizedZ = zRotationStep / totalZRotationSteps;
  37252. var angleZ = normalizedZ * Math.PI * slice;
  37253. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37254. var normalizedY = yRotationStep / totalYRotationSteps;
  37255. var angleY = normalizedY * Math.PI * 2 * arc;
  37256. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37257. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37258. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37259. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37260. var vertex = complete.multiply(radius);
  37261. var normal = complete.divide(radius).normalize();
  37262. positions.push(vertex.x, vertex.y, vertex.z);
  37263. normals.push(normal.x, normal.y, normal.z);
  37264. uvs.push(normalizedY, normalizedZ);
  37265. }
  37266. if (zRotationStep > 0) {
  37267. var verticesCount = positions.length / 3;
  37268. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37269. indices.push((firstIndex));
  37270. indices.push((firstIndex + 1));
  37271. indices.push(firstIndex + totalYRotationSteps + 1);
  37272. indices.push((firstIndex + totalYRotationSteps + 1));
  37273. indices.push((firstIndex + 1));
  37274. indices.push((firstIndex + totalYRotationSteps + 2));
  37275. }
  37276. }
  37277. }
  37278. // Sides
  37279. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37280. // Result
  37281. var vertexData = new VertexData();
  37282. vertexData.indices = indices;
  37283. vertexData.positions = positions;
  37284. vertexData.normals = normals;
  37285. vertexData.uvs = uvs;
  37286. return vertexData;
  37287. };
  37288. /**
  37289. * Creates the VertexData for a cylinder, cone or prism
  37290. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37291. * * height sets the height (y direction) of the cylinder, optional, default 2
  37292. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37293. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37294. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37295. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37296. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37297. * * 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
  37298. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37299. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37300. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37301. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37302. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37303. * * 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)
  37304. * * 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)
  37305. * @returns the VertexData of the cylinder, cone or prism
  37306. */
  37307. VertexData.CreateCylinder = function (options) {
  37308. var height = options.height || 2;
  37309. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37310. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37311. var tessellation = options.tessellation || 24;
  37312. var subdivisions = options.subdivisions || 1;
  37313. var hasRings = options.hasRings ? true : false;
  37314. var enclose = options.enclose ? true : false;
  37315. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37316. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37317. var faceUV = options.faceUV || new Array(3);
  37318. var faceColors = options.faceColors;
  37319. // default face colors and UV if undefined
  37320. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37321. var ringNb = (hasRings) ? subdivisions : 1;
  37322. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37323. var f;
  37324. for (f = 0; f < surfaceNb; f++) {
  37325. if (faceColors && faceColors[f] === undefined) {
  37326. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37327. }
  37328. }
  37329. for (f = 0; f < surfaceNb; f++) {
  37330. if (faceUV && faceUV[f] === undefined) {
  37331. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37332. }
  37333. }
  37334. var indices = new Array();
  37335. var positions = new Array();
  37336. var normals = new Array();
  37337. var uvs = new Array();
  37338. var colors = new Array();
  37339. var angle_step = Math.PI * 2 * arc / tessellation;
  37340. var angle;
  37341. var h;
  37342. var radius;
  37343. var tan = (diameterBottom - diameterTop) / 2 / height;
  37344. var ringVertex = BABYLON.Vector3.Zero();
  37345. var ringNormal = BABYLON.Vector3.Zero();
  37346. var ringFirstVertex = BABYLON.Vector3.Zero();
  37347. var ringFirstNormal = BABYLON.Vector3.Zero();
  37348. var quadNormal = BABYLON.Vector3.Zero();
  37349. var Y = BABYLON.Axis.Y;
  37350. // positions, normals, uvs
  37351. var i;
  37352. var j;
  37353. var r;
  37354. var ringIdx = 1;
  37355. var s = 1; // surface index
  37356. var cs = 0;
  37357. var v = 0;
  37358. for (i = 0; i <= subdivisions; i++) {
  37359. h = i / subdivisions;
  37360. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37361. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37362. for (r = 0; r < ringIdx; r++) {
  37363. if (hasRings) {
  37364. s += r;
  37365. }
  37366. if (enclose) {
  37367. s += 2 * r;
  37368. }
  37369. for (j = 0; j <= tessellation; j++) {
  37370. angle = j * angle_step;
  37371. // position
  37372. ringVertex.x = Math.cos(-angle) * radius;
  37373. ringVertex.y = -height / 2 + h * height;
  37374. ringVertex.z = Math.sin(-angle) * radius;
  37375. // normal
  37376. if (diameterTop === 0 && i === subdivisions) {
  37377. // if no top cap, reuse former normals
  37378. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37379. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37380. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37381. }
  37382. else {
  37383. ringNormal.x = ringVertex.x;
  37384. ringNormal.z = ringVertex.z;
  37385. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37386. ringNormal.normalize();
  37387. }
  37388. // keep first ring vertex values for enclose
  37389. if (j === 0) {
  37390. ringFirstVertex.copyFrom(ringVertex);
  37391. ringFirstNormal.copyFrom(ringNormal);
  37392. }
  37393. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37394. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37395. if (hasRings) {
  37396. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37397. }
  37398. else {
  37399. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37400. }
  37401. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37402. if (faceColors) {
  37403. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37404. }
  37405. }
  37406. // if enclose, add four vertices and their dedicated normals
  37407. if (arc !== 1 && enclose) {
  37408. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37409. positions.push(0, ringVertex.y, 0);
  37410. positions.push(0, ringVertex.y, 0);
  37411. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37412. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37413. quadNormal.normalize();
  37414. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37415. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37416. quadNormal.normalize();
  37417. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37418. if (hasRings) {
  37419. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37420. }
  37421. else {
  37422. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37423. }
  37424. uvs.push(faceUV[s + 1].x, v);
  37425. uvs.push(faceUV[s + 1].z, v);
  37426. if (hasRings) {
  37427. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37428. }
  37429. else {
  37430. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37431. }
  37432. uvs.push(faceUV[s + 2].x, v);
  37433. uvs.push(faceUV[s + 2].z, v);
  37434. if (faceColors) {
  37435. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37436. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37437. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37438. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37439. }
  37440. }
  37441. if (cs !== s) {
  37442. cs = s;
  37443. }
  37444. }
  37445. }
  37446. // indices
  37447. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37448. var s;
  37449. i = 0;
  37450. for (s = 0; s < subdivisions; s++) {
  37451. var i0 = 0;
  37452. var i1 = 0;
  37453. var i2 = 0;
  37454. var i3 = 0;
  37455. for (j = 0; j < tessellation; j++) {
  37456. i0 = i * (e + 1) + j;
  37457. i1 = (i + 1) * (e + 1) + j;
  37458. i2 = i * (e + 1) + (j + 1);
  37459. i3 = (i + 1) * (e + 1) + (j + 1);
  37460. indices.push(i0, i1, i2);
  37461. indices.push(i3, i2, i1);
  37462. }
  37463. if (arc !== 1 && enclose) { // if enclose, add two quads
  37464. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37465. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37466. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37467. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37468. }
  37469. i = (hasRings) ? (i + 2) : (i + 1);
  37470. }
  37471. // Caps
  37472. var createCylinderCap = function (isTop) {
  37473. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37474. if (radius === 0) {
  37475. return;
  37476. }
  37477. // Cap positions, normals & uvs
  37478. var angle;
  37479. var circleVector;
  37480. var i;
  37481. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37482. var c = null;
  37483. if (faceColors) {
  37484. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37485. }
  37486. // cap center
  37487. var vbase = positions.length / 3;
  37488. var offset = isTop ? height / 2 : -height / 2;
  37489. var center = new BABYLON.Vector3(0, offset, 0);
  37490. positions.push(center.x, center.y, center.z);
  37491. normals.push(0, isTop ? 1 : -1, 0);
  37492. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37493. if (c) {
  37494. colors.push(c.r, c.g, c.b, c.a);
  37495. }
  37496. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37497. for (i = 0; i <= tessellation; i++) {
  37498. angle = Math.PI * 2 * i * arc / tessellation;
  37499. var cos = Math.cos(-angle);
  37500. var sin = Math.sin(-angle);
  37501. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37502. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37503. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37504. normals.push(0, isTop ? 1 : -1, 0);
  37505. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37506. if (c) {
  37507. colors.push(c.r, c.g, c.b, c.a);
  37508. }
  37509. }
  37510. // Cap indices
  37511. for (i = 0; i < tessellation; i++) {
  37512. if (!isTop) {
  37513. indices.push(vbase);
  37514. indices.push(vbase + (i + 1));
  37515. indices.push(vbase + (i + 2));
  37516. }
  37517. else {
  37518. indices.push(vbase);
  37519. indices.push(vbase + (i + 2));
  37520. indices.push(vbase + (i + 1));
  37521. }
  37522. }
  37523. };
  37524. // add caps to geometry
  37525. createCylinderCap(false);
  37526. createCylinderCap(true);
  37527. // Sides
  37528. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37529. var vertexData = new VertexData();
  37530. vertexData.indices = indices;
  37531. vertexData.positions = positions;
  37532. vertexData.normals = normals;
  37533. vertexData.uvs = uvs;
  37534. if (faceColors) {
  37535. vertexData.colors = colors;
  37536. }
  37537. return vertexData;
  37538. };
  37539. /**
  37540. * Creates the VertexData for a torus
  37541. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37542. * * diameter the diameter of the torus, optional default 1
  37543. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37544. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37545. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37546. * * 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)
  37547. * * 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)
  37548. * @returns the VertexData of the torus
  37549. */
  37550. VertexData.CreateTorus = function (options) {
  37551. var indices = [];
  37552. var positions = [];
  37553. var normals = [];
  37554. var uvs = [];
  37555. var diameter = options.diameter || 1;
  37556. var thickness = options.thickness || 0.5;
  37557. var tessellation = options.tessellation || 16;
  37558. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37559. var stride = tessellation + 1;
  37560. for (var i = 0; i <= tessellation; i++) {
  37561. var u = i / tessellation;
  37562. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37563. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37564. for (var j = 0; j <= tessellation; j++) {
  37565. var v = 1 - j / tessellation;
  37566. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37567. var dx = Math.cos(innerAngle);
  37568. var dy = Math.sin(innerAngle);
  37569. // Create a vertex.
  37570. var normal = new BABYLON.Vector3(dx, dy, 0);
  37571. var position = normal.scale(thickness / 2);
  37572. var textureCoordinate = new BABYLON.Vector2(u, v);
  37573. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37574. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37575. positions.push(position.x, position.y, position.z);
  37576. normals.push(normal.x, normal.y, normal.z);
  37577. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37578. // And create indices for two triangles.
  37579. var nextI = (i + 1) % stride;
  37580. var nextJ = (j + 1) % stride;
  37581. indices.push(i * stride + j);
  37582. indices.push(i * stride + nextJ);
  37583. indices.push(nextI * stride + j);
  37584. indices.push(i * stride + nextJ);
  37585. indices.push(nextI * stride + nextJ);
  37586. indices.push(nextI * stride + j);
  37587. }
  37588. }
  37589. // Sides
  37590. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37591. // Result
  37592. var vertexData = new VertexData();
  37593. vertexData.indices = indices;
  37594. vertexData.positions = positions;
  37595. vertexData.normals = normals;
  37596. vertexData.uvs = uvs;
  37597. return vertexData;
  37598. };
  37599. /**
  37600. * Creates the VertexData of the LineSystem
  37601. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37602. * - lines an array of lines, each line being an array of successive Vector3
  37603. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37604. * @returns the VertexData of the LineSystem
  37605. */
  37606. VertexData.CreateLineSystem = function (options) {
  37607. var indices = [];
  37608. var positions = [];
  37609. var lines = options.lines;
  37610. var colors = options.colors;
  37611. var vertexColors = [];
  37612. var idx = 0;
  37613. for (var l = 0; l < lines.length; l++) {
  37614. var points = lines[l];
  37615. for (var index = 0; index < points.length; index++) {
  37616. positions.push(points[index].x, points[index].y, points[index].z);
  37617. if (colors) {
  37618. var color = colors[l];
  37619. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37620. }
  37621. if (index > 0) {
  37622. indices.push(idx - 1);
  37623. indices.push(idx);
  37624. }
  37625. idx++;
  37626. }
  37627. }
  37628. var vertexData = new VertexData();
  37629. vertexData.indices = indices;
  37630. vertexData.positions = positions;
  37631. if (colors) {
  37632. vertexData.colors = vertexColors;
  37633. }
  37634. return vertexData;
  37635. };
  37636. /**
  37637. * Create the VertexData for a DashedLines
  37638. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37639. * - points an array successive Vector3
  37640. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37641. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37642. * - dashNb the intended total number of dashes, optional, default 200
  37643. * @returns the VertexData for the DashedLines
  37644. */
  37645. VertexData.CreateDashedLines = function (options) {
  37646. var dashSize = options.dashSize || 3;
  37647. var gapSize = options.gapSize || 1;
  37648. var dashNb = options.dashNb || 200;
  37649. var points = options.points;
  37650. var positions = new Array();
  37651. var indices = new Array();
  37652. var curvect = BABYLON.Vector3.Zero();
  37653. var lg = 0;
  37654. var nb = 0;
  37655. var shft = 0;
  37656. var dashshft = 0;
  37657. var curshft = 0;
  37658. var idx = 0;
  37659. var i = 0;
  37660. for (i = 0; i < points.length - 1; i++) {
  37661. points[i + 1].subtractToRef(points[i], curvect);
  37662. lg += curvect.length();
  37663. }
  37664. shft = lg / dashNb;
  37665. dashshft = dashSize * shft / (dashSize + gapSize);
  37666. for (i = 0; i < points.length - 1; i++) {
  37667. points[i + 1].subtractToRef(points[i], curvect);
  37668. nb = Math.floor(curvect.length() / shft);
  37669. curvect.normalize();
  37670. for (var j = 0; j < nb; j++) {
  37671. curshft = shft * j;
  37672. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37673. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37674. indices.push(idx, idx + 1);
  37675. idx += 2;
  37676. }
  37677. }
  37678. // Result
  37679. var vertexData = new VertexData();
  37680. vertexData.positions = positions;
  37681. vertexData.indices = indices;
  37682. return vertexData;
  37683. };
  37684. /**
  37685. * Creates the VertexData for a Ground
  37686. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37687. * - width the width (x direction) of the ground, optional, default 1
  37688. * - height the height (z direction) of the ground, optional, default 1
  37689. * - subdivisions the number of subdivisions per side, optional, default 1
  37690. * @returns the VertexData of the Ground
  37691. */
  37692. VertexData.CreateGround = function (options) {
  37693. var indices = [];
  37694. var positions = [];
  37695. var normals = [];
  37696. var uvs = [];
  37697. var row, col;
  37698. var width = options.width || 1;
  37699. var height = options.height || 1;
  37700. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37701. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37702. for (row = 0; row <= subdivisionsY; row++) {
  37703. for (col = 0; col <= subdivisionsX; col++) {
  37704. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37705. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37706. positions.push(position.x, position.y, position.z);
  37707. normals.push(normal.x, normal.y, normal.z);
  37708. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37709. }
  37710. }
  37711. for (row = 0; row < subdivisionsY; row++) {
  37712. for (col = 0; col < subdivisionsX; col++) {
  37713. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37714. indices.push(col + 1 + row * (subdivisionsX + 1));
  37715. indices.push(col + row * (subdivisionsX + 1));
  37716. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37717. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37718. indices.push(col + row * (subdivisionsX + 1));
  37719. }
  37720. }
  37721. // Result
  37722. var vertexData = new VertexData();
  37723. vertexData.indices = indices;
  37724. vertexData.positions = positions;
  37725. vertexData.normals = normals;
  37726. vertexData.uvs = uvs;
  37727. return vertexData;
  37728. };
  37729. /**
  37730. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37731. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37732. * * xmin the ground minimum X coordinate, optional, default -1
  37733. * * zmin the ground minimum Z coordinate, optional, default -1
  37734. * * xmax the ground maximum X coordinate, optional, default 1
  37735. * * zmax the ground maximum Z coordinate, optional, default 1
  37736. * * 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}
  37737. * * 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}
  37738. * @returns the VertexData of the TiledGround
  37739. */
  37740. VertexData.CreateTiledGround = function (options) {
  37741. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37742. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37743. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37744. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37745. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37746. var precision = options.precision || { w: 1, h: 1 };
  37747. var indices = new Array();
  37748. var positions = new Array();
  37749. var normals = new Array();
  37750. var uvs = new Array();
  37751. var row, col, tileRow, tileCol;
  37752. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37753. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37754. precision.w = (precision.w < 1) ? 1 : precision.w;
  37755. precision.h = (precision.h < 1) ? 1 : precision.h;
  37756. var tileSize = {
  37757. 'w': (xmax - xmin) / subdivisions.w,
  37758. 'h': (zmax - zmin) / subdivisions.h
  37759. };
  37760. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37761. // Indices
  37762. var base = positions.length / 3;
  37763. var rowLength = precision.w + 1;
  37764. for (row = 0; row < precision.h; row++) {
  37765. for (col = 0; col < precision.w; col++) {
  37766. var square = [
  37767. base + col + row * rowLength,
  37768. base + (col + 1) + row * rowLength,
  37769. base + (col + 1) + (row + 1) * rowLength,
  37770. base + col + (row + 1) * rowLength
  37771. ];
  37772. indices.push(square[1]);
  37773. indices.push(square[2]);
  37774. indices.push(square[3]);
  37775. indices.push(square[0]);
  37776. indices.push(square[1]);
  37777. indices.push(square[3]);
  37778. }
  37779. }
  37780. // Position, normals and uvs
  37781. var position = BABYLON.Vector3.Zero();
  37782. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37783. for (row = 0; row <= precision.h; row++) {
  37784. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37785. for (col = 0; col <= precision.w; col++) {
  37786. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37787. position.y = 0;
  37788. positions.push(position.x, position.y, position.z);
  37789. normals.push(normal.x, normal.y, normal.z);
  37790. uvs.push(col / precision.w, row / precision.h);
  37791. }
  37792. }
  37793. }
  37794. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37795. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37796. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37797. }
  37798. }
  37799. // Result
  37800. var vertexData = new VertexData();
  37801. vertexData.indices = indices;
  37802. vertexData.positions = positions;
  37803. vertexData.normals = normals;
  37804. vertexData.uvs = uvs;
  37805. return vertexData;
  37806. };
  37807. /**
  37808. * Creates the VertexData of the Ground designed from a heightmap
  37809. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37810. * * width the width (x direction) of the ground
  37811. * * height the height (z direction) of the ground
  37812. * * subdivisions the number of subdivisions per side
  37813. * * minHeight the minimum altitude on the ground, optional, default 0
  37814. * * maxHeight the maximum altitude on the ground, optional default 1
  37815. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37816. * * buffer the array holding the image color data
  37817. * * bufferWidth the width of image
  37818. * * bufferHeight the height of image
  37819. * @returns the VertexData of the Ground designed from a heightmap
  37820. */
  37821. VertexData.CreateGroundFromHeightMap = function (options) {
  37822. var indices = [];
  37823. var positions = [];
  37824. var normals = [];
  37825. var uvs = [];
  37826. var row, col;
  37827. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37828. // Vertices
  37829. for (row = 0; row <= options.subdivisions; row++) {
  37830. for (col = 0; col <= options.subdivisions; col++) {
  37831. 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));
  37832. // Compute height
  37833. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37834. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37835. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37836. var r = options.buffer[pos] / 255.0;
  37837. var g = options.buffer[pos + 1] / 255.0;
  37838. var b = options.buffer[pos + 2] / 255.0;
  37839. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37840. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37841. // Add vertex
  37842. positions.push(position.x, position.y, position.z);
  37843. normals.push(0, 0, 0);
  37844. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37845. }
  37846. }
  37847. // Indices
  37848. for (row = 0; row < options.subdivisions; row++) {
  37849. for (col = 0; col < options.subdivisions; col++) {
  37850. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37851. indices.push(col + 1 + row * (options.subdivisions + 1));
  37852. indices.push(col + row * (options.subdivisions + 1));
  37853. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37854. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37855. indices.push(col + row * (options.subdivisions + 1));
  37856. }
  37857. }
  37858. // Normals
  37859. VertexData.ComputeNormals(positions, indices, normals);
  37860. // Result
  37861. var vertexData = new VertexData();
  37862. vertexData.indices = indices;
  37863. vertexData.positions = positions;
  37864. vertexData.normals = normals;
  37865. vertexData.uvs = uvs;
  37866. return vertexData;
  37867. };
  37868. /**
  37869. * Creates the VertexData for a Plane
  37870. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37871. * * size sets the width and height of the plane to the value of size, optional default 1
  37872. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37873. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37874. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37875. * * 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)
  37876. * * 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)
  37877. * @returns the VertexData of the box
  37878. */
  37879. VertexData.CreatePlane = function (options) {
  37880. var indices = [];
  37881. var positions = [];
  37882. var normals = [];
  37883. var uvs = [];
  37884. var width = options.width || options.size || 1;
  37885. var height = options.height || options.size || 1;
  37886. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37887. // Vertices
  37888. var halfWidth = width / 2.0;
  37889. var halfHeight = height / 2.0;
  37890. positions.push(-halfWidth, -halfHeight, 0);
  37891. normals.push(0, 0, -1.0);
  37892. uvs.push(0.0, 0.0);
  37893. positions.push(halfWidth, -halfHeight, 0);
  37894. normals.push(0, 0, -1.0);
  37895. uvs.push(1.0, 0.0);
  37896. positions.push(halfWidth, halfHeight, 0);
  37897. normals.push(0, 0, -1.0);
  37898. uvs.push(1.0, 1.0);
  37899. positions.push(-halfWidth, halfHeight, 0);
  37900. normals.push(0, 0, -1.0);
  37901. uvs.push(0.0, 1.0);
  37902. // Indices
  37903. indices.push(0);
  37904. indices.push(1);
  37905. indices.push(2);
  37906. indices.push(0);
  37907. indices.push(2);
  37908. indices.push(3);
  37909. // Sides
  37910. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37911. // Result
  37912. var vertexData = new VertexData();
  37913. vertexData.indices = indices;
  37914. vertexData.positions = positions;
  37915. vertexData.normals = normals;
  37916. vertexData.uvs = uvs;
  37917. return vertexData;
  37918. };
  37919. /**
  37920. * Creates the VertexData of the Disc or regular Polygon
  37921. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37922. * * radius the radius of the disc, optional default 0.5
  37923. * * tessellation the number of polygon sides, optional, default 64
  37924. * * 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
  37925. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37926. * * 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)
  37927. * * 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)
  37928. * @returns the VertexData of the box
  37929. */
  37930. VertexData.CreateDisc = function (options) {
  37931. var positions = new Array();
  37932. var indices = new Array();
  37933. var normals = new Array();
  37934. var uvs = new Array();
  37935. var radius = options.radius || 0.5;
  37936. var tessellation = options.tessellation || 64;
  37937. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37938. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37939. // positions and uvs
  37940. positions.push(0, 0, 0); // disc center first
  37941. uvs.push(0.5, 0.5);
  37942. var theta = Math.PI * 2 * arc;
  37943. var step = theta / tessellation;
  37944. for (var a = 0; a < theta; a += step) {
  37945. var x = Math.cos(a);
  37946. var y = Math.sin(a);
  37947. var u = (x + 1) / 2;
  37948. var v = (1 - y) / 2;
  37949. positions.push(radius * x, radius * y, 0);
  37950. uvs.push(u, v);
  37951. }
  37952. if (arc === 1) {
  37953. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37954. uvs.push(uvs[2], uvs[3]);
  37955. }
  37956. //indices
  37957. var vertexNb = positions.length / 3;
  37958. for (var i = 1; i < vertexNb - 1; i++) {
  37959. indices.push(i + 1, 0, i);
  37960. }
  37961. // result
  37962. VertexData.ComputeNormals(positions, indices, normals);
  37963. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37964. var vertexData = new VertexData();
  37965. vertexData.indices = indices;
  37966. vertexData.positions = positions;
  37967. vertexData.normals = normals;
  37968. vertexData.uvs = uvs;
  37969. return vertexData;
  37970. };
  37971. /**
  37972. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37973. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37974. * @param polygon a mesh built from polygonTriangulation.build()
  37975. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37976. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37977. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37978. * @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)
  37979. * @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)
  37980. * @returns the VertexData of the Polygon
  37981. */
  37982. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37983. var faceUV = fUV || new Array(3);
  37984. var faceColors = fColors;
  37985. var colors = [];
  37986. // default face colors and UV if undefined
  37987. for (var f = 0; f < 3; f++) {
  37988. if (faceUV[f] === undefined) {
  37989. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37990. }
  37991. if (faceColors && faceColors[f] === undefined) {
  37992. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37993. }
  37994. }
  37995. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37996. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37997. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37998. var indices = polygon.getIndices();
  37999. // set face colours and textures
  38000. var idx = 0;
  38001. var face = 0;
  38002. for (var index = 0; index < normals.length; index += 3) {
  38003. //Edge Face no. 1
  38004. if (Math.abs(normals[index + 1]) < 0.001) {
  38005. face = 1;
  38006. }
  38007. //Top Face no. 0
  38008. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38009. face = 0;
  38010. }
  38011. //Bottom Face no. 2
  38012. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38013. face = 2;
  38014. }
  38015. idx = index / 3;
  38016. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38017. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38018. if (faceColors) {
  38019. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38020. }
  38021. }
  38022. // sides
  38023. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38024. // Result
  38025. var vertexData = new VertexData();
  38026. vertexData.indices = indices;
  38027. vertexData.positions = positions;
  38028. vertexData.normals = normals;
  38029. vertexData.uvs = uvs;
  38030. if (faceColors) {
  38031. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38032. vertexData.colors = totalColors;
  38033. }
  38034. return vertexData;
  38035. };
  38036. /**
  38037. * Creates the VertexData of the IcoSphere
  38038. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38039. * * radius the radius of the IcoSphere, optional default 1
  38040. * * radiusX allows stretching in the x direction, optional, default radius
  38041. * * radiusY allows stretching in the y direction, optional, default radius
  38042. * * radiusZ allows stretching in the z direction, optional, default radius
  38043. * * flat when true creates a flat shaded mesh, optional, default true
  38044. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  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 IcoSphere
  38049. */
  38050. VertexData.CreateIcoSphere = function (options) {
  38051. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38052. var radius = options.radius || 1;
  38053. var flat = (options.flat === undefined) ? true : options.flat;
  38054. var subdivisions = options.subdivisions || 4;
  38055. var radiusX = options.radiusX || radius;
  38056. var radiusY = options.radiusY || radius;
  38057. var radiusZ = options.radiusZ || radius;
  38058. var t = (1 + Math.sqrt(5)) / 2;
  38059. // 12 vertex x,y,z
  38060. var ico_vertices = [
  38061. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38062. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38063. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38064. ];
  38065. // index of 3 vertex makes a face of icopshere
  38066. var ico_indices = [
  38067. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38068. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38069. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38070. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38071. ];
  38072. // vertex for uv have aliased position, not for UV
  38073. var vertices_unalias_id = [
  38074. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38075. // vertex alias
  38076. 0,
  38077. 2,
  38078. 3,
  38079. 3,
  38080. 3,
  38081. 4,
  38082. 7,
  38083. 8,
  38084. 9,
  38085. 9,
  38086. 10,
  38087. 11 // 23: B + 12
  38088. ];
  38089. // uv as integer step (not pixels !)
  38090. var ico_vertexuv = [
  38091. 5, 1, 3, 1, 6, 4, 0, 0,
  38092. 5, 3, 4, 2, 2, 2, 4, 0,
  38093. 2, 0, 1, 1, 6, 0, 6, 2,
  38094. // vertex alias (for same vertex on different faces)
  38095. 0, 4,
  38096. 3, 3,
  38097. 4, 4,
  38098. 3, 1,
  38099. 4, 2,
  38100. 4, 4,
  38101. 0, 2,
  38102. 1, 1,
  38103. 2, 2,
  38104. 3, 3,
  38105. 1, 3,
  38106. 2, 4 // 23: B + 12
  38107. ];
  38108. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38109. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38110. // First island of uv mapping
  38111. // v = 4h 3+ 2
  38112. // v = 3h 9+ 4
  38113. // v = 2h 9+ 5 B
  38114. // v = 1h 9 1 0
  38115. // v = 0h 3 8 7 A
  38116. // u = 0 1 2 3 4 5 6 *a
  38117. // Second island of uv mapping
  38118. // v = 4h 0+ B+ 4+
  38119. // v = 3h A+ 2+
  38120. // v = 2h 7+ 6 3+
  38121. // v = 1h 8+ 3+
  38122. // v = 0h
  38123. // u = 0 1 2 3 4 5 6 *a
  38124. // Face layout on texture UV mapping
  38125. // ============
  38126. // \ 4 /\ 16 / ======
  38127. // \ / \ / /\ 11 /
  38128. // \/ 7 \/ / \ /
  38129. // ======= / 10 \/
  38130. // /\ 17 /\ =======
  38131. // / \ / \ \ 15 /\
  38132. // / 8 \/ 12 \ \ / \
  38133. // ============ \/ 6 \
  38134. // \ 18 /\ ============
  38135. // \ / \ \ 5 /\ 0 /
  38136. // \/ 13 \ \ / \ /
  38137. // ======= \/ 1 \/
  38138. // =============
  38139. // /\ 19 /\ 2 /\
  38140. // / \ / \ / \
  38141. // / 14 \/ 9 \/ 3 \
  38142. // ===================
  38143. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38144. var ustep = 138 / 1024;
  38145. var vstep = 239 / 1024;
  38146. var uoffset = 60 / 1024;
  38147. var voffset = 26 / 1024;
  38148. // Second island should have margin, not to touch the first island
  38149. // avoid any borderline artefact in pixel rounding
  38150. var island_u_offset = -40 / 1024;
  38151. var island_v_offset = +20 / 1024;
  38152. // face is either island 0 or 1 :
  38153. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38154. var island = [
  38155. 0, 0, 0, 0, 1,
  38156. 0, 0, 1, 1, 0,
  38157. 0, 0, 1, 1, 0,
  38158. 0, 1, 1, 1, 0 // 15 - 19
  38159. ];
  38160. var indices = new Array();
  38161. var positions = new Array();
  38162. var normals = new Array();
  38163. var uvs = new Array();
  38164. var current_indice = 0;
  38165. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38166. var face_vertex_pos = new Array(3);
  38167. var face_vertex_uv = new Array(3);
  38168. var v012;
  38169. for (v012 = 0; v012 < 3; v012++) {
  38170. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38171. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38172. }
  38173. // create all with normals
  38174. for (var face = 0; face < 20; face++) {
  38175. // 3 vertex per face
  38176. for (v012 = 0; v012 < 3; v012++) {
  38177. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38178. var v_id = ico_indices[3 * face + v012];
  38179. // vertex have 3D position (x,y,z)
  38180. 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]);
  38181. // Normalize to get normal, then scale to radius
  38182. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38183. // uv Coordinates from vertex ID
  38184. 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);
  38185. }
  38186. // Subdivide the face (interpolate pos, norm, uv)
  38187. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38188. // - norm is linear interpolation of vertex corner normal
  38189. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38190. // - uv is linear interpolation
  38191. //
  38192. // Topology is as below for sub-divide by 2
  38193. // vertex shown as v0,v1,v2
  38194. // interp index is i1 to progress in range [v0,v1[
  38195. // interp index is i2 to progress in range [v0,v2[
  38196. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38197. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38198. //
  38199. //
  38200. // i2 v2
  38201. // ^ ^
  38202. // / / \
  38203. // / / \
  38204. // / / \
  38205. // / / (0,1) \
  38206. // / #---------\
  38207. // / / \ (0,0)'/ \
  38208. // / / \ / \
  38209. // / / \ / \
  38210. // / / (0,0) \ / (1,0) \
  38211. // / #---------#---------\
  38212. // v0 v1
  38213. //
  38214. // --------------------> i1
  38215. //
  38216. // interp of (i1,i2):
  38217. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38218. // along i1 : lerp(x0,x1, i1/(S-i2))
  38219. //
  38220. // centroid of triangle is needed to get help normal computation
  38221. // (c1,c2) are used for centroid location
  38222. var interp_vertex = function (i1, i2, c1, c2) {
  38223. // vertex is interpolated from
  38224. // - face_vertex_pos[0..2]
  38225. // - face_vertex_uv[0..2]
  38226. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38227. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38228. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38229. pos_interp.normalize();
  38230. var vertex_normal;
  38231. if (flat) {
  38232. // in flat mode, recalculate normal as face centroid normal
  38233. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38234. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38235. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38236. }
  38237. else {
  38238. // in smooth mode, recalculate normal from each single vertex position
  38239. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38240. }
  38241. // Vertex normal need correction due to X,Y,Z radius scaling
  38242. vertex_normal.x /= radiusX;
  38243. vertex_normal.y /= radiusY;
  38244. vertex_normal.z /= radiusZ;
  38245. vertex_normal.normalize();
  38246. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38247. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38248. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38249. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38250. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38251. uvs.push(uv_interp.x, uv_interp.y);
  38252. // push each vertex has member of a face
  38253. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38254. indices.push(current_indice);
  38255. current_indice++;
  38256. };
  38257. for (var i2 = 0; i2 < subdivisions; i2++) {
  38258. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38259. // face : (i1,i2) for /\ :
  38260. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38261. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38262. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38263. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38264. if (i1 + i2 + 1 < subdivisions) {
  38265. // face : (i1,i2)' for \/ :
  38266. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38267. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38268. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38269. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38270. }
  38271. }
  38272. }
  38273. }
  38274. // Sides
  38275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38276. // Result
  38277. var vertexData = new VertexData();
  38278. vertexData.indices = indices;
  38279. vertexData.positions = positions;
  38280. vertexData.normals = normals;
  38281. vertexData.uvs = uvs;
  38282. return vertexData;
  38283. };
  38284. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38285. /**
  38286. * Creates the VertexData for a Polyhedron
  38287. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38288. * * type provided types are:
  38289. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38290. * * 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)
  38291. * * size the size of the IcoSphere, optional default 1
  38292. * * sizeX allows stretching in the x direction, optional, default size
  38293. * * sizeY allows stretching in the y direction, optional, default size
  38294. * * sizeZ allows stretching in the z direction, optional, default size
  38295. * * 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
  38296. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38297. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38298. * * flat when true creates a flat shaded mesh, optional, default true
  38299. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38300. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38301. * * 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)
  38302. * * 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)
  38303. * @returns the VertexData of the Polyhedron
  38304. */
  38305. VertexData.CreatePolyhedron = function (options) {
  38306. // provided polyhedron types :
  38307. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38308. // 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)
  38309. var polyhedra = [];
  38310. 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]] };
  38311. 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]] };
  38312. polyhedra[2] = {
  38313. 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]],
  38314. 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]]
  38315. };
  38316. polyhedra[3] = {
  38317. 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]],
  38318. 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]]
  38319. };
  38320. polyhedra[4] = {
  38321. 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]],
  38322. 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]]
  38323. };
  38324. 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]] };
  38325. 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]] };
  38326. 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]] };
  38327. 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]] };
  38328. 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]] };
  38329. 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]] };
  38330. 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]] };
  38331. 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]] };
  38332. 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]] };
  38333. polyhedra[14] = {
  38334. 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]],
  38335. 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]]
  38336. };
  38337. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38338. var size = options.size;
  38339. var sizeX = options.sizeX || size || 1;
  38340. var sizeY = options.sizeY || size || 1;
  38341. var sizeZ = options.sizeZ || size || 1;
  38342. var data = options.custom || polyhedra[type];
  38343. var nbfaces = data.face.length;
  38344. var faceUV = options.faceUV || new Array(nbfaces);
  38345. var faceColors = options.faceColors;
  38346. var flat = (options.flat === undefined) ? true : options.flat;
  38347. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38348. var positions = new Array();
  38349. var indices = new Array();
  38350. var normals = new Array();
  38351. var uvs = new Array();
  38352. var colors = new Array();
  38353. var index = 0;
  38354. var faceIdx = 0; // face cursor in the array "indexes"
  38355. var indexes = new Array();
  38356. var i = 0;
  38357. var f = 0;
  38358. var u, v, ang, x, y, tmp;
  38359. // default face colors and UV if undefined
  38360. if (flat) {
  38361. for (f = 0; f < nbfaces; f++) {
  38362. if (faceColors && faceColors[f] === undefined) {
  38363. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38364. }
  38365. if (faceUV && faceUV[f] === undefined) {
  38366. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38367. }
  38368. }
  38369. }
  38370. if (!flat) {
  38371. for (i = 0; i < data.vertex.length; i++) {
  38372. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38373. uvs.push(0, 0);
  38374. }
  38375. for (f = 0; f < nbfaces; f++) {
  38376. for (i = 0; i < data.face[f].length - 2; i++) {
  38377. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38378. }
  38379. }
  38380. }
  38381. else {
  38382. for (f = 0; f < nbfaces; f++) {
  38383. var fl = data.face[f].length; // number of vertices of the current face
  38384. ang = 2 * Math.PI / fl;
  38385. x = 0.5 * Math.tan(ang / 2);
  38386. y = 0.5;
  38387. // positions, uvs, colors
  38388. for (i = 0; i < fl; i++) {
  38389. // positions
  38390. 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);
  38391. indexes.push(index);
  38392. index++;
  38393. // uvs
  38394. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38395. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38396. uvs.push(u, v);
  38397. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38398. y = x * Math.sin(ang) + y * Math.cos(ang);
  38399. x = tmp;
  38400. // colors
  38401. if (faceColors) {
  38402. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38403. }
  38404. }
  38405. // indices from indexes
  38406. for (i = 0; i < fl - 2; i++) {
  38407. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38408. }
  38409. faceIdx += fl;
  38410. }
  38411. }
  38412. VertexData.ComputeNormals(positions, indices, normals);
  38413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38414. var vertexData = new VertexData();
  38415. vertexData.positions = positions;
  38416. vertexData.indices = indices;
  38417. vertexData.normals = normals;
  38418. vertexData.uvs = uvs;
  38419. if (faceColors && flat) {
  38420. vertexData.colors = colors;
  38421. }
  38422. return vertexData;
  38423. };
  38424. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38425. /**
  38426. * Creates the VertexData for a TorusKnot
  38427. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38428. * * radius the radius of the torus knot, optional, default 2
  38429. * * tube the thickness of the tube, optional, default 0.5
  38430. * * radialSegments the number of sides on each tube segments, optional, default 32
  38431. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38432. * * p the number of windings around the z axis, optional, default 2
  38433. * * q the number of windings around the x axis, optional, default 3
  38434. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38435. * * 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)
  38436. * * 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)
  38437. * @returns the VertexData of the Torus Knot
  38438. */
  38439. VertexData.CreateTorusKnot = function (options) {
  38440. var indices = new Array();
  38441. var positions = new Array();
  38442. var normals = new Array();
  38443. var uvs = new Array();
  38444. var radius = options.radius || 2;
  38445. var tube = options.tube || 0.5;
  38446. var radialSegments = options.radialSegments || 32;
  38447. var tubularSegments = options.tubularSegments || 32;
  38448. var p = options.p || 2;
  38449. var q = options.q || 3;
  38450. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38451. // Helper
  38452. var getPos = function (angle) {
  38453. var cu = Math.cos(angle);
  38454. var su = Math.sin(angle);
  38455. var quOverP = q / p * angle;
  38456. var cs = Math.cos(quOverP);
  38457. var tx = radius * (2 + cs) * 0.5 * cu;
  38458. var ty = radius * (2 + cs) * su * 0.5;
  38459. var tz = radius * Math.sin(quOverP) * 0.5;
  38460. return new BABYLON.Vector3(tx, ty, tz);
  38461. };
  38462. // Vertices
  38463. var i;
  38464. var j;
  38465. for (i = 0; i <= radialSegments; i++) {
  38466. var modI = i % radialSegments;
  38467. var u = modI / radialSegments * 2 * p * Math.PI;
  38468. var p1 = getPos(u);
  38469. var p2 = getPos(u + 0.01);
  38470. var tang = p2.subtract(p1);
  38471. var n = p2.add(p1);
  38472. var bitan = BABYLON.Vector3.Cross(tang, n);
  38473. n = BABYLON.Vector3.Cross(bitan, tang);
  38474. bitan.normalize();
  38475. n.normalize();
  38476. for (j = 0; j < tubularSegments; j++) {
  38477. var modJ = j % tubularSegments;
  38478. var v = modJ / tubularSegments * 2 * Math.PI;
  38479. var cx = -tube * Math.cos(v);
  38480. var cy = tube * Math.sin(v);
  38481. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38482. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38483. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38484. uvs.push(i / radialSegments);
  38485. uvs.push(j / tubularSegments);
  38486. }
  38487. }
  38488. for (i = 0; i < radialSegments; i++) {
  38489. for (j = 0; j < tubularSegments; j++) {
  38490. var jNext = (j + 1) % tubularSegments;
  38491. var a = i * tubularSegments + j;
  38492. var b = (i + 1) * tubularSegments + j;
  38493. var c = (i + 1) * tubularSegments + jNext;
  38494. var d = i * tubularSegments + jNext;
  38495. indices.push(d);
  38496. indices.push(b);
  38497. indices.push(a);
  38498. indices.push(d);
  38499. indices.push(c);
  38500. indices.push(b);
  38501. }
  38502. }
  38503. // Normals
  38504. VertexData.ComputeNormals(positions, indices, normals);
  38505. // Sides
  38506. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38507. // Result
  38508. var vertexData = new VertexData();
  38509. vertexData.indices = indices;
  38510. vertexData.positions = positions;
  38511. vertexData.normals = normals;
  38512. vertexData.uvs = uvs;
  38513. return vertexData;
  38514. };
  38515. // Tools
  38516. /**
  38517. * Compute normals for given positions and indices
  38518. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38519. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38520. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38521. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38522. * * facetNormals : optional array of facet normals (vector3)
  38523. * * facetPositions : optional array of facet positions (vector3)
  38524. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38525. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38526. * * bInfo : optional bounding info, required for facetPartitioning computation
  38527. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38528. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38529. * * useRightHandedSystem: optional boolean to for right handed system computation
  38530. * * depthSort : optional boolean to enable the facet depth sort computation
  38531. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38532. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38533. */
  38534. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38535. // temporary scalar variables
  38536. var index = 0; // facet index
  38537. var p1p2x = 0.0; // p1p2 vector x coordinate
  38538. var p1p2y = 0.0; // p1p2 vector y coordinate
  38539. var p1p2z = 0.0; // p1p2 vector z coordinate
  38540. var p3p2x = 0.0; // p3p2 vector x coordinate
  38541. var p3p2y = 0.0; // p3p2 vector y coordinate
  38542. var p3p2z = 0.0; // p3p2 vector z coordinate
  38543. var faceNormalx = 0.0; // facet normal x coordinate
  38544. var faceNormaly = 0.0; // facet normal y coordinate
  38545. var faceNormalz = 0.0; // facet normal z coordinate
  38546. var length = 0.0; // facet normal length before normalization
  38547. var v1x = 0; // vector1 x index in the positions array
  38548. var v1y = 0; // vector1 y index in the positions array
  38549. var v1z = 0; // vector1 z index in the positions array
  38550. var v2x = 0; // vector2 x index in the positions array
  38551. var v2y = 0; // vector2 y index in the positions array
  38552. var v2z = 0; // vector2 z index in the positions array
  38553. var v3x = 0; // vector3 x index in the positions array
  38554. var v3y = 0; // vector3 y index in the positions array
  38555. var v3z = 0; // vector3 z index in the positions array
  38556. var computeFacetNormals = false;
  38557. var computeFacetPositions = false;
  38558. var computeFacetPartitioning = false;
  38559. var computeDepthSort = false;
  38560. var faceNormalSign = 1;
  38561. var ratio = 0;
  38562. var distanceTo = null;
  38563. if (options) {
  38564. computeFacetNormals = (options.facetNormals) ? true : false;
  38565. computeFacetPositions = (options.facetPositions) ? true : false;
  38566. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38567. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38568. ratio = options.ratio || 0;
  38569. computeDepthSort = (options.depthSort) ? true : false;
  38570. distanceTo = (options.distanceTo);
  38571. if (computeDepthSort) {
  38572. if (distanceTo === undefined) {
  38573. distanceTo = BABYLON.Vector3.Zero();
  38574. }
  38575. var depthSortedFacets = options.depthSortedFacets;
  38576. }
  38577. }
  38578. // facetPartitioning reinit if needed
  38579. var xSubRatio = 0;
  38580. var ySubRatio = 0;
  38581. var zSubRatio = 0;
  38582. var subSq = 0;
  38583. if (computeFacetPartitioning && options && options.bbSize) {
  38584. var ox = 0; // X partitioning index for facet position
  38585. var oy = 0; // Y partinioning index for facet position
  38586. var oz = 0; // Z partinioning index for facet position
  38587. var b1x = 0; // X partitioning index for facet v1 vertex
  38588. var b1y = 0; // Y partitioning index for facet v1 vertex
  38589. var b1z = 0; // z partitioning index for facet v1 vertex
  38590. var b2x = 0; // X partitioning index for facet v2 vertex
  38591. var b2y = 0; // Y partitioning index for facet v2 vertex
  38592. var b2z = 0; // Z partitioning index for facet v2 vertex
  38593. var b3x = 0; // X partitioning index for facet v3 vertex
  38594. var b3y = 0; // Y partitioning index for facet v3 vertex
  38595. var b3z = 0; // Z partitioning index for facet v3 vertex
  38596. var block_idx_o = 0; // facet barycenter block index
  38597. var block_idx_v1 = 0; // v1 vertex block index
  38598. var block_idx_v2 = 0; // v2 vertex block index
  38599. var block_idx_v3 = 0; // v3 vertex block index
  38600. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38601. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38602. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38603. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38604. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38605. subSq = options.subDiv.max * options.subDiv.max;
  38606. options.facetPartitioning.length = 0;
  38607. }
  38608. // reset the normals
  38609. for (index = 0; index < positions.length; index++) {
  38610. normals[index] = 0.0;
  38611. }
  38612. // Loop : 1 indice triplet = 1 facet
  38613. var nbFaces = (indices.length / 3) | 0;
  38614. for (index = 0; index < nbFaces; index++) {
  38615. // get the indexes of the coordinates of each vertex of the facet
  38616. v1x = indices[index * 3] * 3;
  38617. v1y = v1x + 1;
  38618. v1z = v1x + 2;
  38619. v2x = indices[index * 3 + 1] * 3;
  38620. v2y = v2x + 1;
  38621. v2z = v2x + 2;
  38622. v3x = indices[index * 3 + 2] * 3;
  38623. v3y = v3x + 1;
  38624. v3z = v3x + 2;
  38625. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38626. p1p2y = positions[v1y] - positions[v2y];
  38627. p1p2z = positions[v1z] - positions[v2z];
  38628. p3p2x = positions[v3x] - positions[v2x];
  38629. p3p2y = positions[v3y] - positions[v2y];
  38630. p3p2z = positions[v3z] - positions[v2z];
  38631. // compute the face normal with the cross product
  38632. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38633. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38634. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38635. // normalize this normal and store it in the array facetData
  38636. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38637. length = (length === 0) ? 1.0 : length;
  38638. faceNormalx /= length;
  38639. faceNormaly /= length;
  38640. faceNormalz /= length;
  38641. if (computeFacetNormals && options) {
  38642. options.facetNormals[index].x = faceNormalx;
  38643. options.facetNormals[index].y = faceNormaly;
  38644. options.facetNormals[index].z = faceNormalz;
  38645. }
  38646. if (computeFacetPositions && options) {
  38647. // compute and the facet barycenter coordinates in the array facetPositions
  38648. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38649. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38650. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38651. }
  38652. if (computeFacetPartitioning && options) {
  38653. // store the facet indexes in arrays in the main facetPartitioning array :
  38654. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38655. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38656. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38657. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38658. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38659. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38660. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38661. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38662. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38663. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38664. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38665. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38666. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38667. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38668. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38669. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38670. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38671. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38672. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38673. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38674. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38675. // push each facet index in each block containing the vertex
  38676. options.facetPartitioning[block_idx_v1].push(index);
  38677. if (block_idx_v2 != block_idx_v1) {
  38678. options.facetPartitioning[block_idx_v2].push(index);
  38679. }
  38680. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38681. options.facetPartitioning[block_idx_v3].push(index);
  38682. }
  38683. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38684. options.facetPartitioning[block_idx_o].push(index);
  38685. }
  38686. }
  38687. if (computeDepthSort && options && options.facetPositions) {
  38688. var dsf = depthSortedFacets[index];
  38689. dsf.ind = index * 3;
  38690. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38691. }
  38692. // compute the normals anyway
  38693. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38694. normals[v1y] += faceNormaly;
  38695. normals[v1z] += faceNormalz;
  38696. normals[v2x] += faceNormalx;
  38697. normals[v2y] += faceNormaly;
  38698. normals[v2z] += faceNormalz;
  38699. normals[v3x] += faceNormalx;
  38700. normals[v3y] += faceNormaly;
  38701. normals[v3z] += faceNormalz;
  38702. }
  38703. // last normalization of each normal
  38704. for (index = 0; index < normals.length / 3; index++) {
  38705. faceNormalx = normals[index * 3];
  38706. faceNormaly = normals[index * 3 + 1];
  38707. faceNormalz = normals[index * 3 + 2];
  38708. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38709. length = (length === 0) ? 1.0 : length;
  38710. faceNormalx /= length;
  38711. faceNormaly /= length;
  38712. faceNormalz /= length;
  38713. normals[index * 3] = faceNormalx;
  38714. normals[index * 3 + 1] = faceNormaly;
  38715. normals[index * 3 + 2] = faceNormalz;
  38716. }
  38717. };
  38718. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38719. var li = indices.length;
  38720. var ln = normals.length;
  38721. var i;
  38722. var n;
  38723. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38724. switch (sideOrientation) {
  38725. case BABYLON.Mesh.FRONTSIDE:
  38726. // nothing changed
  38727. break;
  38728. case BABYLON.Mesh.BACKSIDE:
  38729. var tmp;
  38730. // indices
  38731. for (i = 0; i < li; i += 3) {
  38732. tmp = indices[i];
  38733. indices[i] = indices[i + 2];
  38734. indices[i + 2] = tmp;
  38735. }
  38736. // normals
  38737. for (n = 0; n < ln; n++) {
  38738. normals[n] = -normals[n];
  38739. }
  38740. break;
  38741. case BABYLON.Mesh.DOUBLESIDE:
  38742. // positions
  38743. var lp = positions.length;
  38744. var l = lp / 3;
  38745. for (var p = 0; p < lp; p++) {
  38746. positions[lp + p] = positions[p];
  38747. }
  38748. // indices
  38749. for (i = 0; i < li; i += 3) {
  38750. indices[i + li] = indices[i + 2] + l;
  38751. indices[i + 1 + li] = indices[i + 1] + l;
  38752. indices[i + 2 + li] = indices[i] + l;
  38753. }
  38754. // normals
  38755. for (n = 0; n < ln; n++) {
  38756. normals[ln + n] = -normals[n];
  38757. }
  38758. // uvs
  38759. var lu = uvs.length;
  38760. var u = 0;
  38761. for (u = 0; u < lu; u++) {
  38762. uvs[u + lu] = uvs[u];
  38763. }
  38764. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38765. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38766. u = 0;
  38767. for (i = 0; i < lu / 2; i++) {
  38768. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38769. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38770. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38771. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38772. u += 2;
  38773. }
  38774. break;
  38775. }
  38776. };
  38777. /**
  38778. * Applies VertexData created from the imported parameters to the geometry
  38779. * @param parsedVertexData the parsed data from an imported file
  38780. * @param geometry the geometry to apply the VertexData to
  38781. */
  38782. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38783. var vertexData = new VertexData();
  38784. // positions
  38785. var positions = parsedVertexData.positions;
  38786. if (positions) {
  38787. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38788. }
  38789. // normals
  38790. var normals = parsedVertexData.normals;
  38791. if (normals) {
  38792. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38793. }
  38794. // tangents
  38795. var tangents = parsedVertexData.tangents;
  38796. if (tangents) {
  38797. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38798. }
  38799. // uvs
  38800. var uvs = parsedVertexData.uvs;
  38801. if (uvs) {
  38802. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38803. }
  38804. // uv2s
  38805. var uv2s = parsedVertexData.uv2s;
  38806. if (uv2s) {
  38807. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38808. }
  38809. // uv3s
  38810. var uv3s = parsedVertexData.uv3s;
  38811. if (uv3s) {
  38812. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38813. }
  38814. // uv4s
  38815. var uv4s = parsedVertexData.uv4s;
  38816. if (uv4s) {
  38817. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38818. }
  38819. // uv5s
  38820. var uv5s = parsedVertexData.uv5s;
  38821. if (uv5s) {
  38822. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38823. }
  38824. // uv6s
  38825. var uv6s = parsedVertexData.uv6s;
  38826. if (uv6s) {
  38827. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38828. }
  38829. // colors
  38830. var colors = parsedVertexData.colors;
  38831. if (colors) {
  38832. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38833. }
  38834. // matricesIndices
  38835. var matricesIndices = parsedVertexData.matricesIndices;
  38836. if (matricesIndices) {
  38837. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38838. }
  38839. // matricesWeights
  38840. var matricesWeights = parsedVertexData.matricesWeights;
  38841. if (matricesWeights) {
  38842. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38843. }
  38844. // indices
  38845. var indices = parsedVertexData.indices;
  38846. if (indices) {
  38847. vertexData.indices = indices;
  38848. }
  38849. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38850. };
  38851. return VertexData;
  38852. }());
  38853. BABYLON.VertexData = VertexData;
  38854. })(BABYLON || (BABYLON = {}));
  38855. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38856. var BABYLON;
  38857. (function (BABYLON) {
  38858. /**
  38859. * Class used to store geometry data (vertex buffers + index buffer)
  38860. */
  38861. var Geometry = /** @class */ (function () {
  38862. /**
  38863. * Creates a new geometry
  38864. * @param id defines the unique ID
  38865. * @param scene defines the hosting scene
  38866. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38867. * @param updatable defines if geometry must be updatable (false by default)
  38868. * @param mesh defines the mesh that will be associated with the geometry
  38869. */
  38870. function Geometry(id, scene, vertexData, updatable, mesh) {
  38871. if (updatable === void 0) { updatable = false; }
  38872. if (mesh === void 0) { mesh = null; }
  38873. /**
  38874. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38875. */
  38876. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38877. this._totalVertices = 0;
  38878. this._isDisposed = false;
  38879. this._indexBufferIsUpdatable = false;
  38880. this.id = id;
  38881. this._engine = scene.getEngine();
  38882. this._meshes = [];
  38883. this._scene = scene;
  38884. //Init vertex buffer cache
  38885. this._vertexBuffers = {};
  38886. this._indices = [];
  38887. this._updatable = updatable;
  38888. // vertexData
  38889. if (vertexData) {
  38890. this.setAllVerticesData(vertexData, updatable);
  38891. }
  38892. else {
  38893. this._totalVertices = 0;
  38894. this._indices = [];
  38895. }
  38896. if (this._engine.getCaps().vertexArrayObject) {
  38897. this._vertexArrayObjects = {};
  38898. }
  38899. // applyToMesh
  38900. if (mesh) {
  38901. if (mesh.getClassName() === "LinesMesh") {
  38902. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38903. this._updateExtend();
  38904. }
  38905. this.applyToMesh(mesh);
  38906. mesh.computeWorldMatrix(true);
  38907. }
  38908. }
  38909. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38910. /**
  38911. * 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
  38912. */
  38913. get: function () {
  38914. return this._boundingBias;
  38915. },
  38916. /**
  38917. * 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
  38918. */
  38919. set: function (value) {
  38920. if (this._boundingBias && this._boundingBias.equals(value)) {
  38921. return;
  38922. }
  38923. this._boundingBias = value.clone();
  38924. this._updateBoundingInfo(true, null);
  38925. },
  38926. enumerable: true,
  38927. configurable: true
  38928. });
  38929. /**
  38930. * Static function used to attach a new empty geometry to a mesh
  38931. * @param mesh defines the mesh to attach the geometry to
  38932. * @returns the new {BABYLON.Geometry}
  38933. */
  38934. Geometry.CreateGeometryForMesh = function (mesh) {
  38935. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38936. geometry.applyToMesh(mesh);
  38937. return geometry;
  38938. };
  38939. Object.defineProperty(Geometry.prototype, "extend", {
  38940. /**
  38941. * Gets the current extend of the geometry
  38942. */
  38943. get: function () {
  38944. return this._extend;
  38945. },
  38946. enumerable: true,
  38947. configurable: true
  38948. });
  38949. /**
  38950. * Gets the hosting scene
  38951. * @returns the hosting {BABYLON.Scene}
  38952. */
  38953. Geometry.prototype.getScene = function () {
  38954. return this._scene;
  38955. };
  38956. /**
  38957. * Gets the hosting engine
  38958. * @returns the hosting {BABYLON.Engine}
  38959. */
  38960. Geometry.prototype.getEngine = function () {
  38961. return this._engine;
  38962. };
  38963. /**
  38964. * Defines if the geometry is ready to use
  38965. * @returns true if the geometry is ready to be used
  38966. */
  38967. Geometry.prototype.isReady = function () {
  38968. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38969. };
  38970. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38971. /**
  38972. * Gets a value indicating that the geometry should not be serialized
  38973. */
  38974. get: function () {
  38975. for (var index = 0; index < this._meshes.length; index++) {
  38976. if (!this._meshes[index].doNotSerialize) {
  38977. return false;
  38978. }
  38979. }
  38980. return true;
  38981. },
  38982. enumerable: true,
  38983. configurable: true
  38984. });
  38985. /** @hidden */
  38986. Geometry.prototype._rebuild = function () {
  38987. if (this._vertexArrayObjects) {
  38988. this._vertexArrayObjects = {};
  38989. }
  38990. // Index buffer
  38991. if (this._meshes.length !== 0 && this._indices) {
  38992. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38993. }
  38994. // Vertex buffers
  38995. for (var key in this._vertexBuffers) {
  38996. var vertexBuffer = this._vertexBuffers[key];
  38997. vertexBuffer._rebuild();
  38998. }
  38999. };
  39000. /**
  39001. * Affects all gemetry data in one call
  39002. * @param vertexData defines the geometry data
  39003. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39004. */
  39005. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39006. vertexData.applyToGeometry(this, updatable);
  39007. this.notifyUpdate();
  39008. };
  39009. /**
  39010. * Set specific vertex data
  39011. * @param kind defines the data kind (Position, normal, etc...)
  39012. * @param data defines the vertex data to use
  39013. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39014. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39015. */
  39016. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39017. if (updatable === void 0) { updatable = false; }
  39018. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39019. this.setVerticesBuffer(buffer);
  39020. };
  39021. /**
  39022. * Removes a specific vertex data
  39023. * @param kind defines the data kind (Position, normal, etc...)
  39024. */
  39025. Geometry.prototype.removeVerticesData = function (kind) {
  39026. if (this._vertexBuffers[kind]) {
  39027. this._vertexBuffers[kind].dispose();
  39028. delete this._vertexBuffers[kind];
  39029. }
  39030. };
  39031. /**
  39032. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39033. * @param buffer defines the vertex buffer to use
  39034. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39035. */
  39036. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39037. if (totalVertices === void 0) { totalVertices = null; }
  39038. var kind = buffer.getKind();
  39039. if (this._vertexBuffers[kind]) {
  39040. this._vertexBuffers[kind].dispose();
  39041. }
  39042. this._vertexBuffers[kind] = buffer;
  39043. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39044. var data = buffer.getData();
  39045. if (totalVertices != null) {
  39046. this._totalVertices = totalVertices;
  39047. }
  39048. else {
  39049. if (data != null) {
  39050. this._totalVertices = data.length / (buffer.byteStride / 4);
  39051. }
  39052. }
  39053. this._updateExtend(data);
  39054. this._resetPointsArrayCache();
  39055. var meshes = this._meshes;
  39056. var numOfMeshes = meshes.length;
  39057. for (var index = 0; index < numOfMeshes; index++) {
  39058. var mesh = meshes[index];
  39059. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39060. mesh._createGlobalSubMesh(false);
  39061. mesh.computeWorldMatrix(true);
  39062. }
  39063. }
  39064. this.notifyUpdate(kind);
  39065. if (this._vertexArrayObjects) {
  39066. this._disposeVertexArrayObjects();
  39067. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39068. }
  39069. };
  39070. /**
  39071. * Update a specific vertex buffer
  39072. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39073. * It will do nothing if the buffer is not updatable
  39074. * @param kind defines the data kind (Position, normal, etc...)
  39075. * @param data defines the data to use
  39076. * @param offset defines the offset in the target buffer where to store the data
  39077. * @param useBytes set to true if the offset is in bytes
  39078. */
  39079. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39080. if (useBytes === void 0) { useBytes = false; }
  39081. var vertexBuffer = this.getVertexBuffer(kind);
  39082. if (!vertexBuffer) {
  39083. return;
  39084. }
  39085. vertexBuffer.updateDirectly(data, offset, useBytes);
  39086. this.notifyUpdate(kind);
  39087. };
  39088. /**
  39089. * Update a specific vertex buffer
  39090. * This function will create a new buffer if the current one is not updatable
  39091. * @param kind defines the data kind (Position, normal, etc...)
  39092. * @param data defines the data to use
  39093. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39094. */
  39095. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39096. if (updateExtends === void 0) { updateExtends = false; }
  39097. var vertexBuffer = this.getVertexBuffer(kind);
  39098. if (!vertexBuffer) {
  39099. return;
  39100. }
  39101. vertexBuffer.update(data);
  39102. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39103. this._updateBoundingInfo(updateExtends, data);
  39104. }
  39105. this.notifyUpdate(kind);
  39106. };
  39107. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39108. if (updateExtends) {
  39109. this._updateExtend(data);
  39110. }
  39111. var meshes = this._meshes;
  39112. var numOfMeshes = meshes.length;
  39113. this._resetPointsArrayCache();
  39114. for (var index = 0; index < numOfMeshes; index++) {
  39115. var mesh = meshes[index];
  39116. if (updateExtends) {
  39117. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39118. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39119. var subMesh = mesh.subMeshes[subIndex];
  39120. subMesh.refreshBoundingInfo();
  39121. }
  39122. }
  39123. }
  39124. };
  39125. /** @hidden */
  39126. Geometry.prototype._bind = function (effect, indexToBind) {
  39127. if (!effect) {
  39128. return;
  39129. }
  39130. if (indexToBind === undefined) {
  39131. indexToBind = this._indexBuffer;
  39132. }
  39133. var vbs = this.getVertexBuffers();
  39134. if (!vbs) {
  39135. return;
  39136. }
  39137. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39138. this._engine.bindBuffers(vbs, indexToBind, effect);
  39139. return;
  39140. }
  39141. // Using VAO
  39142. if (!this._vertexArrayObjects[effect.key]) {
  39143. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39144. }
  39145. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39146. };
  39147. /**
  39148. * Gets total number of vertices
  39149. * @returns the total number of vertices
  39150. */
  39151. Geometry.prototype.getTotalVertices = function () {
  39152. if (!this.isReady()) {
  39153. return 0;
  39154. }
  39155. return this._totalVertices;
  39156. };
  39157. /**
  39158. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39159. * @param kind defines the data kind (Position, normal, etc...)
  39160. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39161. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39162. * @returns a float array containing vertex data
  39163. */
  39164. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39165. var vertexBuffer = this.getVertexBuffer(kind);
  39166. if (!vertexBuffer) {
  39167. return null;
  39168. }
  39169. var data = vertexBuffer.getData();
  39170. if (!data) {
  39171. return null;
  39172. }
  39173. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39174. var count = this._totalVertices * vertexBuffer.getSize();
  39175. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39176. var copy_1 = new Array(count);
  39177. vertexBuffer.forEach(count, function (value, index) {
  39178. copy_1[index] = value;
  39179. });
  39180. return copy_1;
  39181. }
  39182. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39183. if (data instanceof Array) {
  39184. var offset = vertexBuffer.byteOffset / 4;
  39185. return BABYLON.Tools.Slice(data, offset, offset + count);
  39186. }
  39187. else if (data instanceof ArrayBuffer) {
  39188. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39189. }
  39190. else {
  39191. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39192. }
  39193. }
  39194. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39195. return BABYLON.Tools.Slice(data);
  39196. }
  39197. return data;
  39198. };
  39199. /**
  39200. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39201. * @param kind defines the data kind (Position, normal, etc...)
  39202. * @returns true if the vertex buffer with the specified kind is updatable
  39203. */
  39204. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39205. var vb = this._vertexBuffers[kind];
  39206. if (!vb) {
  39207. return false;
  39208. }
  39209. return vb.isUpdatable();
  39210. };
  39211. /**
  39212. * Gets a specific vertex buffer
  39213. * @param kind defines the data kind (Position, normal, etc...)
  39214. * @returns a {BABYLON.VertexBuffer}
  39215. */
  39216. Geometry.prototype.getVertexBuffer = function (kind) {
  39217. if (!this.isReady()) {
  39218. return null;
  39219. }
  39220. return this._vertexBuffers[kind];
  39221. };
  39222. /**
  39223. * Returns all vertex buffers
  39224. * @return an object holding all vertex buffers indexed by kind
  39225. */
  39226. Geometry.prototype.getVertexBuffers = function () {
  39227. if (!this.isReady()) {
  39228. return null;
  39229. }
  39230. return this._vertexBuffers;
  39231. };
  39232. /**
  39233. * Gets a boolean indicating if specific vertex buffer is present
  39234. * @param kind defines the data kind (Position, normal, etc...)
  39235. * @returns true if data is present
  39236. */
  39237. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39238. if (!this._vertexBuffers) {
  39239. if (this._delayInfo) {
  39240. return this._delayInfo.indexOf(kind) !== -1;
  39241. }
  39242. return false;
  39243. }
  39244. return this._vertexBuffers[kind] !== undefined;
  39245. };
  39246. /**
  39247. * Gets a list of all attached data kinds (Position, normal, etc...)
  39248. * @returns a list of string containing all kinds
  39249. */
  39250. Geometry.prototype.getVerticesDataKinds = function () {
  39251. var result = [];
  39252. var kind;
  39253. if (!this._vertexBuffers && this._delayInfo) {
  39254. for (kind in this._delayInfo) {
  39255. result.push(kind);
  39256. }
  39257. }
  39258. else {
  39259. for (kind in this._vertexBuffers) {
  39260. result.push(kind);
  39261. }
  39262. }
  39263. return result;
  39264. };
  39265. /**
  39266. * Update index buffer
  39267. * @param indices defines the indices to store in the index buffer
  39268. * @param offset defines the offset in the target buffer where to store the data
  39269. */
  39270. Geometry.prototype.updateIndices = function (indices, offset) {
  39271. if (!this._indexBuffer) {
  39272. return;
  39273. }
  39274. if (!this._indexBufferIsUpdatable) {
  39275. this.setIndices(indices, null, true);
  39276. }
  39277. else {
  39278. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39279. }
  39280. };
  39281. /**
  39282. * Creates a new index buffer
  39283. * @param indices defines the indices to store in the index buffer
  39284. * @param totalVertices defines the total number of vertices (could be null)
  39285. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39286. */
  39287. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39288. if (totalVertices === void 0) { totalVertices = null; }
  39289. if (updatable === void 0) { updatable = false; }
  39290. if (this._indexBuffer) {
  39291. this._engine._releaseBuffer(this._indexBuffer);
  39292. }
  39293. this._disposeVertexArrayObjects();
  39294. this._indices = indices;
  39295. this._indexBufferIsUpdatable = updatable;
  39296. if (this._meshes.length !== 0 && this._indices) {
  39297. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39298. }
  39299. if (totalVertices != undefined) { // including null and undefined
  39300. this._totalVertices = totalVertices;
  39301. }
  39302. var meshes = this._meshes;
  39303. var numOfMeshes = meshes.length;
  39304. for (var index = 0; index < numOfMeshes; index++) {
  39305. meshes[index]._createGlobalSubMesh(true);
  39306. }
  39307. this.notifyUpdate();
  39308. };
  39309. /**
  39310. * Return the total number of indices
  39311. * @returns the total number of indices
  39312. */
  39313. Geometry.prototype.getTotalIndices = function () {
  39314. if (!this.isReady()) {
  39315. return 0;
  39316. }
  39317. return this._indices.length;
  39318. };
  39319. /**
  39320. * Gets the index buffer array
  39321. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39322. * @returns the index buffer array
  39323. */
  39324. Geometry.prototype.getIndices = function (copyWhenShared) {
  39325. if (!this.isReady()) {
  39326. return null;
  39327. }
  39328. var orig = this._indices;
  39329. if (!copyWhenShared || this._meshes.length === 1) {
  39330. return orig;
  39331. }
  39332. else {
  39333. var len = orig.length;
  39334. var copy = [];
  39335. for (var i = 0; i < len; i++) {
  39336. copy.push(orig[i]);
  39337. }
  39338. return copy;
  39339. }
  39340. };
  39341. /**
  39342. * Gets the index buffer
  39343. * @return the index buffer
  39344. */
  39345. Geometry.prototype.getIndexBuffer = function () {
  39346. if (!this.isReady()) {
  39347. return null;
  39348. }
  39349. return this._indexBuffer;
  39350. };
  39351. /** @hidden */
  39352. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39353. if (effect === void 0) { effect = null; }
  39354. if (!effect || !this._vertexArrayObjects) {
  39355. return;
  39356. }
  39357. if (this._vertexArrayObjects[effect.key]) {
  39358. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39359. delete this._vertexArrayObjects[effect.key];
  39360. }
  39361. };
  39362. /**
  39363. * Release the associated resources for a specific mesh
  39364. * @param mesh defines the source mesh
  39365. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39366. */
  39367. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39368. var meshes = this._meshes;
  39369. var index = meshes.indexOf(mesh);
  39370. if (index === -1) {
  39371. return;
  39372. }
  39373. meshes.splice(index, 1);
  39374. mesh._geometry = null;
  39375. if (meshes.length === 0 && shouldDispose) {
  39376. this.dispose();
  39377. }
  39378. };
  39379. /**
  39380. * Apply current geometry to a given mesh
  39381. * @param mesh defines the mesh to apply geometry to
  39382. */
  39383. Geometry.prototype.applyToMesh = function (mesh) {
  39384. if (mesh._geometry === this) {
  39385. return;
  39386. }
  39387. var previousGeometry = mesh._geometry;
  39388. if (previousGeometry) {
  39389. previousGeometry.releaseForMesh(mesh);
  39390. }
  39391. var meshes = this._meshes;
  39392. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39393. mesh._geometry = this;
  39394. this._scene.pushGeometry(this);
  39395. meshes.push(mesh);
  39396. if (this.isReady()) {
  39397. this._applyToMesh(mesh);
  39398. }
  39399. else {
  39400. mesh._boundingInfo = this._boundingInfo;
  39401. }
  39402. };
  39403. Geometry.prototype._updateExtend = function (data) {
  39404. if (data === void 0) { data = null; }
  39405. if (!data) {
  39406. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39407. }
  39408. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39409. };
  39410. Geometry.prototype._applyToMesh = function (mesh) {
  39411. var numOfMeshes = this._meshes.length;
  39412. // vertexBuffers
  39413. for (var kind in this._vertexBuffers) {
  39414. if (numOfMeshes === 1) {
  39415. this._vertexBuffers[kind].create();
  39416. }
  39417. var buffer = this._vertexBuffers[kind].getBuffer();
  39418. if (buffer)
  39419. buffer.references = numOfMeshes;
  39420. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39421. if (!this._extend) {
  39422. this._updateExtend();
  39423. }
  39424. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39425. mesh._createGlobalSubMesh(false);
  39426. //bounding info was just created again, world matrix should be applied again.
  39427. mesh._updateBoundingInfo();
  39428. }
  39429. }
  39430. // indexBuffer
  39431. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39432. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39433. }
  39434. if (this._indexBuffer) {
  39435. this._indexBuffer.references = numOfMeshes;
  39436. }
  39437. };
  39438. Geometry.prototype.notifyUpdate = function (kind) {
  39439. if (this.onGeometryUpdated) {
  39440. this.onGeometryUpdated(this, kind);
  39441. }
  39442. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39443. var mesh = _a[_i];
  39444. mesh._markSubMeshesAsAttributesDirty();
  39445. }
  39446. };
  39447. /**
  39448. * Load the geometry if it was flagged as delay loaded
  39449. * @param scene defines the hosting scene
  39450. * @param onLoaded defines a callback called when the geometry is loaded
  39451. */
  39452. Geometry.prototype.load = function (scene, onLoaded) {
  39453. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39454. return;
  39455. }
  39456. if (this.isReady()) {
  39457. if (onLoaded) {
  39458. onLoaded();
  39459. }
  39460. return;
  39461. }
  39462. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39463. this._queueLoad(scene, onLoaded);
  39464. };
  39465. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39466. var _this = this;
  39467. if (!this.delayLoadingFile) {
  39468. return;
  39469. }
  39470. scene._addPendingData(this);
  39471. scene._loadFile(this.delayLoadingFile, function (data) {
  39472. if (!_this._delayLoadingFunction) {
  39473. return;
  39474. }
  39475. _this._delayLoadingFunction(JSON.parse(data), _this);
  39476. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39477. _this._delayInfo = [];
  39478. scene._removePendingData(_this);
  39479. var meshes = _this._meshes;
  39480. var numOfMeshes = meshes.length;
  39481. for (var index = 0; index < numOfMeshes; index++) {
  39482. _this._applyToMesh(meshes[index]);
  39483. }
  39484. if (onLoaded) {
  39485. onLoaded();
  39486. }
  39487. }, undefined, true);
  39488. };
  39489. /**
  39490. * Invert the geometry to move from a right handed system to a left handed one.
  39491. */
  39492. Geometry.prototype.toLeftHanded = function () {
  39493. // Flip faces
  39494. var tIndices = this.getIndices(false);
  39495. if (tIndices != null && tIndices.length > 0) {
  39496. for (var i = 0; i < tIndices.length; i += 3) {
  39497. var tTemp = tIndices[i + 0];
  39498. tIndices[i + 0] = tIndices[i + 2];
  39499. tIndices[i + 2] = tTemp;
  39500. }
  39501. this.setIndices(tIndices);
  39502. }
  39503. // Negate position.z
  39504. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39505. if (tPositions != null && tPositions.length > 0) {
  39506. for (var i = 0; i < tPositions.length; i += 3) {
  39507. tPositions[i + 2] = -tPositions[i + 2];
  39508. }
  39509. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39510. }
  39511. // Negate normal.z
  39512. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39513. if (tNormals != null && tNormals.length > 0) {
  39514. for (var i = 0; i < tNormals.length; i += 3) {
  39515. tNormals[i + 2] = -tNormals[i + 2];
  39516. }
  39517. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39518. }
  39519. };
  39520. // Cache
  39521. /** @hidden */
  39522. Geometry.prototype._resetPointsArrayCache = function () {
  39523. this._positions = null;
  39524. };
  39525. /** @hidden */
  39526. Geometry.prototype._generatePointsArray = function () {
  39527. if (this._positions)
  39528. return true;
  39529. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39530. if (!data || data.length === 0) {
  39531. return false;
  39532. }
  39533. this._positions = [];
  39534. for (var index = 0; index < data.length; index += 3) {
  39535. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39536. }
  39537. return true;
  39538. };
  39539. /**
  39540. * Gets a value indicating if the geometry is disposed
  39541. * @returns true if the geometry was disposed
  39542. */
  39543. Geometry.prototype.isDisposed = function () {
  39544. return this._isDisposed;
  39545. };
  39546. Geometry.prototype._disposeVertexArrayObjects = function () {
  39547. if (this._vertexArrayObjects) {
  39548. for (var kind in this._vertexArrayObjects) {
  39549. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39550. }
  39551. this._vertexArrayObjects = {};
  39552. }
  39553. };
  39554. /**
  39555. * Free all associated resources
  39556. */
  39557. Geometry.prototype.dispose = function () {
  39558. var meshes = this._meshes;
  39559. var numOfMeshes = meshes.length;
  39560. var index;
  39561. for (index = 0; index < numOfMeshes; index++) {
  39562. this.releaseForMesh(meshes[index]);
  39563. }
  39564. this._meshes = [];
  39565. this._disposeVertexArrayObjects();
  39566. for (var kind in this._vertexBuffers) {
  39567. this._vertexBuffers[kind].dispose();
  39568. }
  39569. this._vertexBuffers = {};
  39570. this._totalVertices = 0;
  39571. if (this._indexBuffer) {
  39572. this._engine._releaseBuffer(this._indexBuffer);
  39573. }
  39574. this._indexBuffer = null;
  39575. this._indices = [];
  39576. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39577. this.delayLoadingFile = null;
  39578. this._delayLoadingFunction = null;
  39579. this._delayInfo = [];
  39580. this._boundingInfo = null;
  39581. this._scene.removeGeometry(this);
  39582. this._isDisposed = true;
  39583. };
  39584. /**
  39585. * Clone the current geometry into a new geometry
  39586. * @param id defines the unique ID of the new geometry
  39587. * @returns a new geometry object
  39588. */
  39589. Geometry.prototype.copy = function (id) {
  39590. var vertexData = new BABYLON.VertexData();
  39591. vertexData.indices = [];
  39592. var indices = this.getIndices();
  39593. if (indices) {
  39594. for (var index = 0; index < indices.length; index++) {
  39595. vertexData.indices.push(indices[index]);
  39596. }
  39597. }
  39598. var updatable = false;
  39599. var stopChecking = false;
  39600. var kind;
  39601. for (kind in this._vertexBuffers) {
  39602. // using slice() to make a copy of the array and not just reference it
  39603. var data = this.getVerticesData(kind);
  39604. if (data instanceof Float32Array) {
  39605. vertexData.set(new Float32Array(data), kind);
  39606. }
  39607. else {
  39608. vertexData.set(data.slice(0), kind);
  39609. }
  39610. if (!stopChecking) {
  39611. var vb = this.getVertexBuffer(kind);
  39612. if (vb) {
  39613. updatable = vb.isUpdatable();
  39614. stopChecking = !updatable;
  39615. }
  39616. }
  39617. }
  39618. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39619. geometry.delayLoadState = this.delayLoadState;
  39620. geometry.delayLoadingFile = this.delayLoadingFile;
  39621. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39622. for (kind in this._delayInfo) {
  39623. geometry._delayInfo = geometry._delayInfo || [];
  39624. geometry._delayInfo.push(kind);
  39625. }
  39626. // Bounding info
  39627. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39628. return geometry;
  39629. };
  39630. /**
  39631. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39632. * @return a JSON representation of the current geometry data (without the vertices data)
  39633. */
  39634. Geometry.prototype.serialize = function () {
  39635. var serializationObject = {};
  39636. serializationObject.id = this.id;
  39637. serializationObject.updatable = this._updatable;
  39638. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39639. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39640. }
  39641. return serializationObject;
  39642. };
  39643. Geometry.prototype.toNumberArray = function (origin) {
  39644. if (Array.isArray(origin)) {
  39645. return origin;
  39646. }
  39647. else {
  39648. return Array.prototype.slice.call(origin);
  39649. }
  39650. };
  39651. /**
  39652. * Serialize all vertices data into a JSON oject
  39653. * @returns a JSON representation of the current geometry data
  39654. */
  39655. Geometry.prototype.serializeVerticeData = function () {
  39656. var serializationObject = this.serialize();
  39657. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39658. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39659. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39660. serializationObject.positions._updatable = true;
  39661. }
  39662. }
  39663. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39664. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39665. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39666. serializationObject.normals._updatable = true;
  39667. }
  39668. }
  39669. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39670. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39671. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39672. serializationObject.tangets._updatable = true;
  39673. }
  39674. }
  39675. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39676. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39677. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39678. serializationObject.uvs._updatable = true;
  39679. }
  39680. }
  39681. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39682. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39683. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39684. serializationObject.uv2s._updatable = true;
  39685. }
  39686. }
  39687. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39688. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39689. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39690. serializationObject.uv3s._updatable = true;
  39691. }
  39692. }
  39693. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39694. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39695. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39696. serializationObject.uv4s._updatable = true;
  39697. }
  39698. }
  39699. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39700. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39701. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39702. serializationObject.uv5s._updatable = true;
  39703. }
  39704. }
  39705. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39706. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39707. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39708. serializationObject.uv6s._updatable = true;
  39709. }
  39710. }
  39711. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39712. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39713. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39714. serializationObject.colors._updatable = true;
  39715. }
  39716. }
  39717. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39718. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39719. serializationObject.matricesIndices._isExpanded = true;
  39720. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39721. serializationObject.matricesIndices._updatable = true;
  39722. }
  39723. }
  39724. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39725. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39726. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39727. serializationObject.matricesWeights._updatable = true;
  39728. }
  39729. }
  39730. serializationObject.indices = this.toNumberArray(this.getIndices());
  39731. return serializationObject;
  39732. };
  39733. // Statics
  39734. /**
  39735. * Extracts a clone of a mesh geometry
  39736. * @param mesh defines the source mesh
  39737. * @param id defines the unique ID of the new geometry object
  39738. * @returns the new geometry object
  39739. */
  39740. Geometry.ExtractFromMesh = function (mesh, id) {
  39741. var geometry = mesh._geometry;
  39742. if (!geometry) {
  39743. return null;
  39744. }
  39745. return geometry.copy(id);
  39746. };
  39747. /**
  39748. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39749. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39750. * Be aware Math.random() could cause collisions, but:
  39751. * "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"
  39752. * @returns a string containing a new GUID
  39753. */
  39754. Geometry.RandomId = function () {
  39755. return BABYLON.Tools.RandomId();
  39756. };
  39757. /** @hidden */
  39758. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39759. var scene = mesh.getScene();
  39760. // Geometry
  39761. var geometryId = parsedGeometry.geometryId;
  39762. if (geometryId) {
  39763. var geometry = scene.getGeometryByID(geometryId);
  39764. if (geometry) {
  39765. geometry.applyToMesh(mesh);
  39766. }
  39767. }
  39768. else if (parsedGeometry instanceof ArrayBuffer) {
  39769. var binaryInfo = mesh._binaryInfo;
  39770. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39771. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39772. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39773. }
  39774. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39775. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39776. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39777. }
  39778. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39779. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39780. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39781. }
  39782. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39783. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39784. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39785. }
  39786. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39787. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39788. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39789. }
  39790. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39791. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39792. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39793. }
  39794. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39795. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39796. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39797. }
  39798. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39799. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39800. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39801. }
  39802. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39803. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39804. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39805. }
  39806. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39807. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39808. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39809. }
  39810. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39811. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39812. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39813. }
  39814. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39815. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39816. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39817. }
  39818. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39819. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39820. mesh.setIndices(indicesData, null);
  39821. }
  39822. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39823. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39824. mesh.subMeshes = [];
  39825. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39826. var materialIndex = subMeshesData[(i * 5) + 0];
  39827. var verticesStart = subMeshesData[(i * 5) + 1];
  39828. var verticesCount = subMeshesData[(i * 5) + 2];
  39829. var indexStart = subMeshesData[(i * 5) + 3];
  39830. var indexCount = subMeshesData[(i * 5) + 4];
  39831. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39832. }
  39833. }
  39834. }
  39835. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39836. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39837. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39838. if (parsedGeometry.tangents) {
  39839. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39840. }
  39841. if (parsedGeometry.uvs) {
  39842. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39843. }
  39844. if (parsedGeometry.uvs2) {
  39845. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39846. }
  39847. if (parsedGeometry.uvs3) {
  39848. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39849. }
  39850. if (parsedGeometry.uvs4) {
  39851. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39852. }
  39853. if (parsedGeometry.uvs5) {
  39854. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39855. }
  39856. if (parsedGeometry.uvs6) {
  39857. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39858. }
  39859. if (parsedGeometry.colors) {
  39860. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39861. }
  39862. if (parsedGeometry.matricesIndices) {
  39863. if (!parsedGeometry.matricesIndices._isExpanded) {
  39864. var floatIndices = [];
  39865. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39866. var matricesIndex = parsedGeometry.matricesIndices[i];
  39867. floatIndices.push(matricesIndex & 0x000000FF);
  39868. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39869. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39870. floatIndices.push(matricesIndex >> 24);
  39871. }
  39872. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39873. }
  39874. else {
  39875. delete parsedGeometry.matricesIndices._isExpanded;
  39876. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39877. }
  39878. }
  39879. if (parsedGeometry.matricesIndicesExtra) {
  39880. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39881. var floatIndices = [];
  39882. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39883. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39884. floatIndices.push(matricesIndex & 0x000000FF);
  39885. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39886. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39887. floatIndices.push(matricesIndex >> 24);
  39888. }
  39889. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39890. }
  39891. else {
  39892. delete parsedGeometry.matricesIndices._isExpanded;
  39893. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39894. }
  39895. }
  39896. if (parsedGeometry.matricesWeights) {
  39897. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39898. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39899. }
  39900. if (parsedGeometry.matricesWeightsExtra) {
  39901. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39902. }
  39903. mesh.setIndices(parsedGeometry.indices, null);
  39904. }
  39905. // SubMeshes
  39906. if (parsedGeometry.subMeshes) {
  39907. mesh.subMeshes = [];
  39908. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39909. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39910. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39911. }
  39912. }
  39913. // Flat shading
  39914. if (mesh._shouldGenerateFlatShading) {
  39915. mesh.convertToFlatShadedMesh();
  39916. delete mesh._shouldGenerateFlatShading;
  39917. }
  39918. // Update
  39919. mesh.computeWorldMatrix(true);
  39920. // Octree
  39921. var sceneOctree = scene.selectionOctree;
  39922. if (sceneOctree !== undefined && sceneOctree !== null) {
  39923. sceneOctree.addMesh(mesh);
  39924. }
  39925. };
  39926. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39927. var epsilon = 1e-3;
  39928. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39929. return;
  39930. }
  39931. var noInfluenceBoneIndex = 0.0;
  39932. if (parsedGeometry.skeletonId > -1) {
  39933. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39934. if (!skeleton) {
  39935. return;
  39936. }
  39937. noInfluenceBoneIndex = skeleton.bones.length;
  39938. }
  39939. else {
  39940. return;
  39941. }
  39942. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39943. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39944. var matricesWeights = parsedGeometry.matricesWeights;
  39945. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39946. var influencers = parsedGeometry.numBoneInfluencer;
  39947. var size = matricesWeights.length;
  39948. for (var i = 0; i < size; i += 4) {
  39949. var weight = 0.0;
  39950. var firstZeroWeight = -1;
  39951. for (var j = 0; j < 4; j++) {
  39952. var w = matricesWeights[i + j];
  39953. weight += w;
  39954. if (w < epsilon && firstZeroWeight < 0) {
  39955. firstZeroWeight = j;
  39956. }
  39957. }
  39958. if (matricesWeightsExtra) {
  39959. for (var j = 0; j < 4; j++) {
  39960. var w = matricesWeightsExtra[i + j];
  39961. weight += w;
  39962. if (w < epsilon && firstZeroWeight < 0) {
  39963. firstZeroWeight = j + 4;
  39964. }
  39965. }
  39966. }
  39967. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39968. firstZeroWeight = influencers - 1;
  39969. }
  39970. if (weight > epsilon) {
  39971. var mweight = 1.0 / weight;
  39972. for (var j = 0; j < 4; j++) {
  39973. matricesWeights[i + j] *= mweight;
  39974. }
  39975. if (matricesWeightsExtra) {
  39976. for (var j = 0; j < 4; j++) {
  39977. matricesWeightsExtra[i + j] *= mweight;
  39978. }
  39979. }
  39980. }
  39981. else {
  39982. if (firstZeroWeight >= 4) {
  39983. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39984. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39985. }
  39986. else {
  39987. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39988. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39989. }
  39990. }
  39991. }
  39992. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39993. if (parsedGeometry.matricesWeightsExtra) {
  39994. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39995. }
  39996. };
  39997. /**
  39998. * Create a new geometry from persisted data (Using .babylon file format)
  39999. * @param parsedVertexData defines the persisted data
  40000. * @param scene defines the hosting scene
  40001. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40002. * @returns the new geometry object
  40003. */
  40004. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40005. if (scene.getGeometryByID(parsedVertexData.id)) {
  40006. return null; // null since geometry could be something else than a box...
  40007. }
  40008. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40009. if (BABYLON.Tags) {
  40010. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40011. }
  40012. if (parsedVertexData.delayLoadingFile) {
  40013. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40014. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40015. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40016. geometry._delayInfo = [];
  40017. if (parsedVertexData.hasUVs) {
  40018. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40019. }
  40020. if (parsedVertexData.hasUVs2) {
  40021. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40022. }
  40023. if (parsedVertexData.hasUVs3) {
  40024. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40025. }
  40026. if (parsedVertexData.hasUVs4) {
  40027. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40028. }
  40029. if (parsedVertexData.hasUVs5) {
  40030. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40031. }
  40032. if (parsedVertexData.hasUVs6) {
  40033. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40034. }
  40035. if (parsedVertexData.hasColors) {
  40036. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40037. }
  40038. if (parsedVertexData.hasMatricesIndices) {
  40039. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40040. }
  40041. if (parsedVertexData.hasMatricesWeights) {
  40042. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40043. }
  40044. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40045. }
  40046. else {
  40047. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40048. }
  40049. scene.pushGeometry(geometry, true);
  40050. return geometry;
  40051. };
  40052. return Geometry;
  40053. }());
  40054. BABYLON.Geometry = Geometry;
  40055. // Primitives
  40056. /// Abstract class
  40057. /**
  40058. * Abstract class used to provide common services for all typed geometries
  40059. * @hidden
  40060. */
  40061. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40062. __extends(_PrimitiveGeometry, _super);
  40063. /**
  40064. * Creates a new typed geometry
  40065. * @param id defines the unique ID of the geometry
  40066. * @param scene defines the hosting scene
  40067. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40068. * @param mesh defines the hosting mesh (can be null)
  40069. */
  40070. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40071. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40072. if (mesh === void 0) { mesh = null; }
  40073. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40074. _this._canBeRegenerated = _canBeRegenerated;
  40075. _this._beingRegenerated = true;
  40076. _this.regenerate();
  40077. _this._beingRegenerated = false;
  40078. return _this;
  40079. }
  40080. /**
  40081. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40082. * @returns true if the geometry can be regenerated
  40083. */
  40084. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40085. return this._canBeRegenerated;
  40086. };
  40087. /**
  40088. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40089. */
  40090. _PrimitiveGeometry.prototype.regenerate = function () {
  40091. if (!this._canBeRegenerated) {
  40092. return;
  40093. }
  40094. this._beingRegenerated = true;
  40095. this.setAllVerticesData(this._regenerateVertexData(), false);
  40096. this._beingRegenerated = false;
  40097. };
  40098. /**
  40099. * Clone the geometry
  40100. * @param id defines the unique ID of the new geometry
  40101. * @returns the new geometry
  40102. */
  40103. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40104. return _super.prototype.copy.call(this, id);
  40105. };
  40106. // overrides
  40107. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40108. if (!this._beingRegenerated) {
  40109. return;
  40110. }
  40111. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40112. };
  40113. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40114. if (!this._beingRegenerated) {
  40115. return;
  40116. }
  40117. _super.prototype.setVerticesData.call(this, kind, data, false);
  40118. };
  40119. // to override
  40120. /** @hidden */
  40121. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40122. throw new Error("Abstract method");
  40123. };
  40124. _PrimitiveGeometry.prototype.copy = function (id) {
  40125. throw new Error("Must be overriden in sub-classes.");
  40126. };
  40127. _PrimitiveGeometry.prototype.serialize = function () {
  40128. var serializationObject = _super.prototype.serialize.call(this);
  40129. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40130. return serializationObject;
  40131. };
  40132. return _PrimitiveGeometry;
  40133. }(Geometry));
  40134. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40135. /**
  40136. * Creates a ribbon geometry
  40137. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40138. */
  40139. var RibbonGeometry = /** @class */ (function (_super) {
  40140. __extends(RibbonGeometry, _super);
  40141. /**
  40142. * Creates a ribbon geometry
  40143. * @param id defines the unique ID of the geometry
  40144. * @param scene defines the hosting scene
  40145. * @param pathArray defines the array of paths to use
  40146. * @param closeArray defines if the last path and the first path must be joined
  40147. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40148. * @param offset defines the offset between points
  40149. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40150. * @param mesh defines the hosting mesh (can be null)
  40151. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40152. */
  40153. function RibbonGeometry(id, scene,
  40154. /**
  40155. * Defines the array of paths to use
  40156. */
  40157. pathArray,
  40158. /**
  40159. * Defines if the last and first points of each path in your pathArray must be joined
  40160. */
  40161. closeArray,
  40162. /**
  40163. * Defines if the last and first points of each path in your pathArray must be joined
  40164. */
  40165. closePath,
  40166. /**
  40167. * Defines the offset between points
  40168. */
  40169. offset, canBeRegenerated, mesh,
  40170. /**
  40171. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40172. */
  40173. side) {
  40174. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40175. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40176. _this.pathArray = pathArray;
  40177. _this.closeArray = closeArray;
  40178. _this.closePath = closePath;
  40179. _this.offset = offset;
  40180. _this.side = side;
  40181. return _this;
  40182. }
  40183. /** @hidden */
  40184. RibbonGeometry.prototype._regenerateVertexData = function () {
  40185. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40186. };
  40187. RibbonGeometry.prototype.copy = function (id) {
  40188. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40189. };
  40190. return RibbonGeometry;
  40191. }(_PrimitiveGeometry));
  40192. BABYLON.RibbonGeometry = RibbonGeometry;
  40193. /**
  40194. * Creates a box geometry
  40195. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40196. */
  40197. var BoxGeometry = /** @class */ (function (_super) {
  40198. __extends(BoxGeometry, _super);
  40199. /**
  40200. * Creates a box geometry
  40201. * @param id defines the unique ID of the geometry
  40202. * @param scene defines the hosting scene
  40203. * @param size defines the zise of the box (width, height and depth are the same)
  40204. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40205. * @param mesh defines the hosting mesh (can be null)
  40206. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40207. */
  40208. function BoxGeometry(id, scene,
  40209. /**
  40210. * Defines the zise of the box (width, height and depth are the same)
  40211. */
  40212. size, canBeRegenerated, mesh,
  40213. /**
  40214. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40215. */
  40216. side) {
  40217. if (mesh === void 0) { mesh = null; }
  40218. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40219. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40220. _this.size = size;
  40221. _this.side = side;
  40222. return _this;
  40223. }
  40224. BoxGeometry.prototype._regenerateVertexData = function () {
  40225. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40226. };
  40227. BoxGeometry.prototype.copy = function (id) {
  40228. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40229. };
  40230. BoxGeometry.prototype.serialize = function () {
  40231. var serializationObject = _super.prototype.serialize.call(this);
  40232. serializationObject.size = this.size;
  40233. return serializationObject;
  40234. };
  40235. BoxGeometry.Parse = function (parsedBox, scene) {
  40236. if (scene.getGeometryByID(parsedBox.id)) {
  40237. return null; // null since geometry could be something else than a box...
  40238. }
  40239. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40240. if (BABYLON.Tags) {
  40241. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40242. }
  40243. scene.pushGeometry(box, true);
  40244. return box;
  40245. };
  40246. return BoxGeometry;
  40247. }(_PrimitiveGeometry));
  40248. BABYLON.BoxGeometry = BoxGeometry;
  40249. /**
  40250. * Creates a sphere geometry
  40251. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40252. */
  40253. var SphereGeometry = /** @class */ (function (_super) {
  40254. __extends(SphereGeometry, _super);
  40255. /**
  40256. * Create a new sphere geometry
  40257. * @param id defines the unique ID of the geometry
  40258. * @param scene defines the hosting scene
  40259. * @param segments defines the number of segments to use to create the sphere
  40260. * @param diameter defines the diameter of the sphere
  40261. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40262. * @param mesh defines the hosting mesh (can be null)
  40263. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40264. */
  40265. function SphereGeometry(id, scene,
  40266. /**
  40267. * Defines the number of segments to use to create the sphere
  40268. */
  40269. segments,
  40270. /**
  40271. * Defines the diameter of the sphere
  40272. */
  40273. diameter, canBeRegenerated, mesh,
  40274. /**
  40275. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40276. */
  40277. side) {
  40278. if (mesh === void 0) { mesh = null; }
  40279. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40280. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40281. _this.segments = segments;
  40282. _this.diameter = diameter;
  40283. _this.side = side;
  40284. return _this;
  40285. }
  40286. SphereGeometry.prototype._regenerateVertexData = function () {
  40287. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40288. };
  40289. SphereGeometry.prototype.copy = function (id) {
  40290. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40291. };
  40292. SphereGeometry.prototype.serialize = function () {
  40293. var serializationObject = _super.prototype.serialize.call(this);
  40294. serializationObject.segments = this.segments;
  40295. serializationObject.diameter = this.diameter;
  40296. return serializationObject;
  40297. };
  40298. SphereGeometry.Parse = function (parsedSphere, scene) {
  40299. if (scene.getGeometryByID(parsedSphere.id)) {
  40300. return null; // null since geometry could be something else than a sphere...
  40301. }
  40302. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40303. if (BABYLON.Tags) {
  40304. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40305. }
  40306. scene.pushGeometry(sphere, true);
  40307. return sphere;
  40308. };
  40309. return SphereGeometry;
  40310. }(_PrimitiveGeometry));
  40311. BABYLON.SphereGeometry = SphereGeometry;
  40312. /**
  40313. * Creates a disc geometry
  40314. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40315. */
  40316. var DiscGeometry = /** @class */ (function (_super) {
  40317. __extends(DiscGeometry, _super);
  40318. /**
  40319. * Creates a new disc geometry
  40320. * @param id defines the unique ID of the geometry
  40321. * @param scene defines the hosting scene
  40322. * @param radius defines the radius of the disc
  40323. * @param tessellation defines the tesselation factor to apply to the disc
  40324. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40325. * @param mesh defines the hosting mesh (can be null)
  40326. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40327. */
  40328. function DiscGeometry(id, scene,
  40329. /**
  40330. * Defines the radius of the disc
  40331. */
  40332. radius,
  40333. /**
  40334. * Defines the tesselation factor to apply to the disc
  40335. */
  40336. tessellation, canBeRegenerated, mesh,
  40337. /**
  40338. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40339. */
  40340. side) {
  40341. if (mesh === void 0) { mesh = null; }
  40342. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40343. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40344. _this.radius = radius;
  40345. _this.tessellation = tessellation;
  40346. _this.side = side;
  40347. return _this;
  40348. }
  40349. DiscGeometry.prototype._regenerateVertexData = function () {
  40350. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40351. };
  40352. DiscGeometry.prototype.copy = function (id) {
  40353. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40354. };
  40355. return DiscGeometry;
  40356. }(_PrimitiveGeometry));
  40357. BABYLON.DiscGeometry = DiscGeometry;
  40358. /**
  40359. * Creates a new cylinder geometry
  40360. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40361. */
  40362. var CylinderGeometry = /** @class */ (function (_super) {
  40363. __extends(CylinderGeometry, _super);
  40364. /**
  40365. * Creates a new cylinder geometry
  40366. * @param id defines the unique ID of the geometry
  40367. * @param scene defines the hosting scene
  40368. * @param height defines the height of the cylinder
  40369. * @param diameterTop defines the diameter of the cylinder's top cap
  40370. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40371. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40372. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40373. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40374. * @param mesh defines the hosting mesh (can be null)
  40375. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40376. */
  40377. function CylinderGeometry(id, scene,
  40378. /**
  40379. * Defines the height of the cylinder
  40380. */
  40381. height,
  40382. /**
  40383. * Defines the diameter of the cylinder's top cap
  40384. */
  40385. diameterTop,
  40386. /**
  40387. * Defines the diameter of the cylinder's bottom cap
  40388. */
  40389. diameterBottom,
  40390. /**
  40391. * Defines the tessellation factor to apply to the cylinder
  40392. */
  40393. tessellation,
  40394. /**
  40395. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40396. */
  40397. subdivisions, canBeRegenerated, mesh,
  40398. /**
  40399. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40400. */
  40401. side) {
  40402. if (subdivisions === void 0) { subdivisions = 1; }
  40403. if (mesh === void 0) { mesh = null; }
  40404. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40405. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40406. _this.height = height;
  40407. _this.diameterTop = diameterTop;
  40408. _this.diameterBottom = diameterBottom;
  40409. _this.tessellation = tessellation;
  40410. _this.subdivisions = subdivisions;
  40411. _this.side = side;
  40412. return _this;
  40413. }
  40414. CylinderGeometry.prototype._regenerateVertexData = function () {
  40415. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40416. };
  40417. CylinderGeometry.prototype.copy = function (id) {
  40418. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40419. };
  40420. CylinderGeometry.prototype.serialize = function () {
  40421. var serializationObject = _super.prototype.serialize.call(this);
  40422. serializationObject.height = this.height;
  40423. serializationObject.diameterTop = this.diameterTop;
  40424. serializationObject.diameterBottom = this.diameterBottom;
  40425. serializationObject.tessellation = this.tessellation;
  40426. return serializationObject;
  40427. };
  40428. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40429. if (scene.getGeometryByID(parsedCylinder.id)) {
  40430. return null; // null since geometry could be something else than a cylinder...
  40431. }
  40432. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40433. if (BABYLON.Tags) {
  40434. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40435. }
  40436. scene.pushGeometry(cylinder, true);
  40437. return cylinder;
  40438. };
  40439. return CylinderGeometry;
  40440. }(_PrimitiveGeometry));
  40441. BABYLON.CylinderGeometry = CylinderGeometry;
  40442. /**
  40443. * Creates a new torus geometry
  40444. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40445. */
  40446. var TorusGeometry = /** @class */ (function (_super) {
  40447. __extends(TorusGeometry, _super);
  40448. /**
  40449. * Creates a new torus geometry
  40450. * @param id defines the unique ID of the geometry
  40451. * @param scene defines the hosting scene
  40452. * @param diameter defines the diameter of the torus
  40453. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40454. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40455. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40456. * @param mesh defines the hosting mesh (can be null)
  40457. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40458. */
  40459. function TorusGeometry(id, scene,
  40460. /**
  40461. * Defines the diameter of the torus
  40462. */
  40463. diameter,
  40464. /**
  40465. * Defines the thickness of the torus (ie. internal diameter)
  40466. */
  40467. thickness,
  40468. /**
  40469. * Defines the tesselation factor to apply to the torus
  40470. */
  40471. tessellation, canBeRegenerated, mesh,
  40472. /**
  40473. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40474. */
  40475. side) {
  40476. if (mesh === void 0) { mesh = null; }
  40477. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40478. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40479. _this.diameter = diameter;
  40480. _this.thickness = thickness;
  40481. _this.tessellation = tessellation;
  40482. _this.side = side;
  40483. return _this;
  40484. }
  40485. TorusGeometry.prototype._regenerateVertexData = function () {
  40486. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40487. };
  40488. TorusGeometry.prototype.copy = function (id) {
  40489. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40490. };
  40491. TorusGeometry.prototype.serialize = function () {
  40492. var serializationObject = _super.prototype.serialize.call(this);
  40493. serializationObject.diameter = this.diameter;
  40494. serializationObject.thickness = this.thickness;
  40495. serializationObject.tessellation = this.tessellation;
  40496. return serializationObject;
  40497. };
  40498. TorusGeometry.Parse = function (parsedTorus, scene) {
  40499. if (scene.getGeometryByID(parsedTorus.id)) {
  40500. return null; // null since geometry could be something else than a torus...
  40501. }
  40502. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40503. if (BABYLON.Tags) {
  40504. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40505. }
  40506. scene.pushGeometry(torus, true);
  40507. return torus;
  40508. };
  40509. return TorusGeometry;
  40510. }(_PrimitiveGeometry));
  40511. BABYLON.TorusGeometry = TorusGeometry;
  40512. /**
  40513. * Creates a new ground geometry
  40514. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40515. */
  40516. var GroundGeometry = /** @class */ (function (_super) {
  40517. __extends(GroundGeometry, _super);
  40518. /**
  40519. * Creates a new ground geometry
  40520. * @param id defines the unique ID of the geometry
  40521. * @param scene defines the hosting scene
  40522. * @param width defines the width of the ground
  40523. * @param height defines the height of the ground
  40524. * @param subdivisions defines the subdivisions to apply to the ground
  40525. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40526. * @param mesh defines the hosting mesh (can be null)
  40527. */
  40528. function GroundGeometry(id, scene,
  40529. /**
  40530. * Defines the width of the ground
  40531. */
  40532. width,
  40533. /**
  40534. * Defines the height of the ground
  40535. */
  40536. height,
  40537. /**
  40538. * Defines the subdivisions to apply to the ground
  40539. */
  40540. subdivisions, canBeRegenerated, mesh) {
  40541. if (mesh === void 0) { mesh = null; }
  40542. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40543. _this.width = width;
  40544. _this.height = height;
  40545. _this.subdivisions = subdivisions;
  40546. return _this;
  40547. }
  40548. GroundGeometry.prototype._regenerateVertexData = function () {
  40549. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40550. };
  40551. GroundGeometry.prototype.copy = function (id) {
  40552. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40553. };
  40554. GroundGeometry.prototype.serialize = function () {
  40555. var serializationObject = _super.prototype.serialize.call(this);
  40556. serializationObject.width = this.width;
  40557. serializationObject.height = this.height;
  40558. serializationObject.subdivisions = this.subdivisions;
  40559. return serializationObject;
  40560. };
  40561. GroundGeometry.Parse = function (parsedGround, scene) {
  40562. if (scene.getGeometryByID(parsedGround.id)) {
  40563. return null; // null since geometry could be something else than a ground...
  40564. }
  40565. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40566. if (BABYLON.Tags) {
  40567. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40568. }
  40569. scene.pushGeometry(ground, true);
  40570. return ground;
  40571. };
  40572. return GroundGeometry;
  40573. }(_PrimitiveGeometry));
  40574. BABYLON.GroundGeometry = GroundGeometry;
  40575. /**
  40576. * Creates a tiled ground geometry
  40577. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40578. */
  40579. var TiledGroundGeometry = /** @class */ (function (_super) {
  40580. __extends(TiledGroundGeometry, _super);
  40581. /**
  40582. * Creates a tiled ground geometry
  40583. * @param id defines the unique ID of the geometry
  40584. * @param scene defines the hosting scene
  40585. * @param xmin defines the minimum value on X axis
  40586. * @param zmin defines the minimum value on Z axis
  40587. * @param xmax defines the maximum value on X axis
  40588. * @param zmax defines the maximum value on Z axis
  40589. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40590. * @param precision defines the precision to use when computing the tiles
  40591. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40592. * @param mesh defines the hosting mesh (can be null)
  40593. */
  40594. function TiledGroundGeometry(id, scene,
  40595. /**
  40596. * Defines the minimum value on X axis
  40597. */
  40598. xmin,
  40599. /**
  40600. * Defines the minimum value on Z axis
  40601. */
  40602. zmin,
  40603. /**
  40604. * Defines the maximum value on X axis
  40605. */
  40606. xmax,
  40607. /**
  40608. * Defines the maximum value on Z axis
  40609. */
  40610. zmax,
  40611. /**
  40612. * Defines the subdivisions to apply to the ground
  40613. */
  40614. subdivisions,
  40615. /**
  40616. * Defines the precision to use when computing the tiles
  40617. */
  40618. precision, canBeRegenerated, mesh) {
  40619. if (mesh === void 0) { mesh = null; }
  40620. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40621. _this.xmin = xmin;
  40622. _this.zmin = zmin;
  40623. _this.xmax = xmax;
  40624. _this.zmax = zmax;
  40625. _this.subdivisions = subdivisions;
  40626. _this.precision = precision;
  40627. return _this;
  40628. }
  40629. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40630. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40631. };
  40632. TiledGroundGeometry.prototype.copy = function (id) {
  40633. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40634. };
  40635. return TiledGroundGeometry;
  40636. }(_PrimitiveGeometry));
  40637. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40638. /**
  40639. * Creates a plane geometry
  40640. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40641. */
  40642. var PlaneGeometry = /** @class */ (function (_super) {
  40643. __extends(PlaneGeometry, _super);
  40644. /**
  40645. * Creates a plane geometry
  40646. * @param id defines the unique ID of the geometry
  40647. * @param scene defines the hosting scene
  40648. * @param size defines the size of the plane (width === height)
  40649. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40650. * @param mesh defines the hosting mesh (can be null)
  40651. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40652. */
  40653. function PlaneGeometry(id, scene,
  40654. /**
  40655. * Defines the size of the plane (width === height)
  40656. */
  40657. size, canBeRegenerated, mesh,
  40658. /**
  40659. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40660. */
  40661. side) {
  40662. if (mesh === void 0) { mesh = null; }
  40663. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40664. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40665. _this.size = size;
  40666. _this.side = side;
  40667. return _this;
  40668. }
  40669. PlaneGeometry.prototype._regenerateVertexData = function () {
  40670. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40671. };
  40672. PlaneGeometry.prototype.copy = function (id) {
  40673. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40674. };
  40675. PlaneGeometry.prototype.serialize = function () {
  40676. var serializationObject = _super.prototype.serialize.call(this);
  40677. serializationObject.size = this.size;
  40678. return serializationObject;
  40679. };
  40680. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40681. if (scene.getGeometryByID(parsedPlane.id)) {
  40682. return null; // null since geometry could be something else than a ground...
  40683. }
  40684. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40685. if (BABYLON.Tags) {
  40686. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40687. }
  40688. scene.pushGeometry(plane, true);
  40689. return plane;
  40690. };
  40691. return PlaneGeometry;
  40692. }(_PrimitiveGeometry));
  40693. BABYLON.PlaneGeometry = PlaneGeometry;
  40694. /**
  40695. * Creates a torus knot geometry
  40696. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40697. */
  40698. var TorusKnotGeometry = /** @class */ (function (_super) {
  40699. __extends(TorusKnotGeometry, _super);
  40700. /**
  40701. * Creates a torus knot geometry
  40702. * @param id defines the unique ID of the geometry
  40703. * @param scene defines the hosting scene
  40704. * @param radius defines the radius of the torus knot
  40705. * @param tube defines the thickness of the torus knot tube
  40706. * @param radialSegments defines the number of radial segments
  40707. * @param tubularSegments defines the number of tubular segments
  40708. * @param p defines the first number of windings
  40709. * @param q defines the second number of windings
  40710. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40711. * @param mesh defines the hosting mesh (can be null)
  40712. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40713. */
  40714. function TorusKnotGeometry(id, scene,
  40715. /**
  40716. * Defines the radius of the torus knot
  40717. */
  40718. radius,
  40719. /**
  40720. * Defines the thickness of the torus knot tube
  40721. */
  40722. tube,
  40723. /**
  40724. * Defines the number of radial segments
  40725. */
  40726. radialSegments,
  40727. /**
  40728. * Defines the number of tubular segments
  40729. */
  40730. tubularSegments,
  40731. /**
  40732. * Defines the first number of windings
  40733. */
  40734. p,
  40735. /**
  40736. * Defines the second number of windings
  40737. */
  40738. q, canBeRegenerated, mesh,
  40739. /**
  40740. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40741. */
  40742. side) {
  40743. if (mesh === void 0) { mesh = null; }
  40744. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40745. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40746. _this.radius = radius;
  40747. _this.tube = tube;
  40748. _this.radialSegments = radialSegments;
  40749. _this.tubularSegments = tubularSegments;
  40750. _this.p = p;
  40751. _this.q = q;
  40752. _this.side = side;
  40753. return _this;
  40754. }
  40755. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40756. 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 });
  40757. };
  40758. TorusKnotGeometry.prototype.copy = function (id) {
  40759. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40760. };
  40761. TorusKnotGeometry.prototype.serialize = function () {
  40762. var serializationObject = _super.prototype.serialize.call(this);
  40763. serializationObject.radius = this.radius;
  40764. serializationObject.tube = this.tube;
  40765. serializationObject.radialSegments = this.radialSegments;
  40766. serializationObject.tubularSegments = this.tubularSegments;
  40767. serializationObject.p = this.p;
  40768. serializationObject.q = this.q;
  40769. return serializationObject;
  40770. };
  40771. ;
  40772. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40773. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40774. return null; // null since geometry could be something else than a ground...
  40775. }
  40776. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40777. if (BABYLON.Tags) {
  40778. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40779. }
  40780. scene.pushGeometry(torusKnot, true);
  40781. return torusKnot;
  40782. };
  40783. return TorusKnotGeometry;
  40784. }(_PrimitiveGeometry));
  40785. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40786. //}
  40787. })(BABYLON || (BABYLON = {}));
  40788. //# sourceMappingURL=babylon.geometry.js.map
  40789. var BABYLON;
  40790. (function (BABYLON) {
  40791. /**
  40792. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40793. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40794. */
  40795. var PostProcessManager = /** @class */ (function () {
  40796. /**
  40797. * Creates a new instance PostProcess
  40798. * @param scene The scene that the post process is associated with.
  40799. */
  40800. function PostProcessManager(scene) {
  40801. this._vertexBuffers = {};
  40802. this._scene = scene;
  40803. }
  40804. PostProcessManager.prototype._prepareBuffers = function () {
  40805. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40806. return;
  40807. }
  40808. // VBO
  40809. var vertices = [];
  40810. vertices.push(1, 1);
  40811. vertices.push(-1, 1);
  40812. vertices.push(-1, -1);
  40813. vertices.push(1, -1);
  40814. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40815. this._buildIndexBuffer();
  40816. };
  40817. PostProcessManager.prototype._buildIndexBuffer = function () {
  40818. // Indices
  40819. var indices = [];
  40820. indices.push(0);
  40821. indices.push(1);
  40822. indices.push(2);
  40823. indices.push(0);
  40824. indices.push(2);
  40825. indices.push(3);
  40826. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40827. };
  40828. /**
  40829. * Rebuilds the vertex buffers of the manager.
  40830. */
  40831. PostProcessManager.prototype._rebuild = function () {
  40832. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40833. if (!vb) {
  40834. return;
  40835. }
  40836. vb._rebuild();
  40837. this._buildIndexBuffer();
  40838. };
  40839. // Methods
  40840. /**
  40841. * Prepares a frame to be run through a post process.
  40842. * @param sourceTexture The input texture to the post procesess. (default: null)
  40843. * @param postProcesses An array of post processes to be run. (default: null)
  40844. * @returns True if the post processes were able to be run.
  40845. */
  40846. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40847. if (sourceTexture === void 0) { sourceTexture = null; }
  40848. if (postProcesses === void 0) { postProcesses = null; }
  40849. var camera = this._scene.activeCamera;
  40850. if (!camera) {
  40851. return false;
  40852. }
  40853. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40854. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40855. return false;
  40856. }
  40857. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40858. return true;
  40859. };
  40860. /**
  40861. * Manually render a set of post processes to a texture.
  40862. * @param postProcesses An array of post processes to be run.
  40863. * @param targetTexture The target texture to render to.
  40864. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40865. */
  40866. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40867. if (targetTexture === void 0) { targetTexture = null; }
  40868. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40869. var engine = this._scene.getEngine();
  40870. for (var index = 0; index < postProcesses.length; index++) {
  40871. if (index < postProcesses.length - 1) {
  40872. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40873. }
  40874. else {
  40875. if (targetTexture) {
  40876. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40877. }
  40878. else {
  40879. engine.restoreDefaultFramebuffer();
  40880. }
  40881. }
  40882. var pp = postProcesses[index];
  40883. var effect = pp.apply();
  40884. if (effect) {
  40885. pp.onBeforeRenderObservable.notifyObservers(effect);
  40886. // VBOs
  40887. this._prepareBuffers();
  40888. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40889. // Draw order
  40890. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40891. pp.onAfterRenderObservable.notifyObservers(effect);
  40892. }
  40893. }
  40894. // Restore depth buffer
  40895. engine.setDepthBuffer(true);
  40896. engine.setDepthWrite(true);
  40897. };
  40898. /**
  40899. * Finalize the result of the output of the postprocesses.
  40900. * @param doNotPresent If true the result will not be displayed to the screen.
  40901. * @param targetTexture The target texture to render to.
  40902. * @param faceIndex The index of the face to bind the target texture to.
  40903. * @param postProcesses The array of post processes to render.
  40904. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40905. */
  40906. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40907. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40908. var camera = this._scene.activeCamera;
  40909. if (!camera) {
  40910. return;
  40911. }
  40912. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40913. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40914. return;
  40915. }
  40916. var engine = this._scene.getEngine();
  40917. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40918. var pp = postProcesses[index];
  40919. if (index < len - 1) {
  40920. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40921. }
  40922. else {
  40923. if (targetTexture) {
  40924. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40925. pp._outputTexture = targetTexture;
  40926. }
  40927. else {
  40928. engine.restoreDefaultFramebuffer();
  40929. pp._outputTexture = null;
  40930. }
  40931. }
  40932. if (doNotPresent) {
  40933. break;
  40934. }
  40935. var effect = pp.apply();
  40936. if (effect) {
  40937. pp.onBeforeRenderObservable.notifyObservers(effect);
  40938. // VBOs
  40939. this._prepareBuffers();
  40940. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40941. // Draw order
  40942. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40943. pp.onAfterRenderObservable.notifyObservers(effect);
  40944. }
  40945. }
  40946. // Restore states
  40947. engine.setDepthBuffer(true);
  40948. engine.setDepthWrite(true);
  40949. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40950. };
  40951. /**
  40952. * Disposes of the post process manager.
  40953. */
  40954. PostProcessManager.prototype.dispose = function () {
  40955. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40956. if (buffer) {
  40957. buffer.dispose();
  40958. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40959. }
  40960. if (this._indexBuffer) {
  40961. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40962. this._indexBuffer = null;
  40963. }
  40964. };
  40965. return PostProcessManager;
  40966. }());
  40967. BABYLON.PostProcessManager = PostProcessManager;
  40968. })(BABYLON || (BABYLON = {}));
  40969. //# sourceMappingURL=babylon.postProcessManager.js.map
  40970. var BABYLON;
  40971. (function (BABYLON) {
  40972. /**
  40973. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40974. */
  40975. var PerformanceMonitor = /** @class */ (function () {
  40976. /**
  40977. * constructor
  40978. * @param frameSampleSize The number of samples required to saturate the sliding window
  40979. */
  40980. function PerformanceMonitor(frameSampleSize) {
  40981. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40982. this._enabled = true;
  40983. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40984. }
  40985. /**
  40986. * Samples current frame
  40987. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40988. */
  40989. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40990. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40991. if (!this._enabled)
  40992. return;
  40993. if (this._lastFrameTimeMs != null) {
  40994. var dt = timeMs - this._lastFrameTimeMs;
  40995. this._rollingFrameTime.add(dt);
  40996. }
  40997. this._lastFrameTimeMs = timeMs;
  40998. };
  40999. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41000. /**
  41001. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41002. * @return Average frame time in milliseconds
  41003. */
  41004. get: function () {
  41005. return this._rollingFrameTime.average;
  41006. },
  41007. enumerable: true,
  41008. configurable: true
  41009. });
  41010. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41011. /**
  41012. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41013. * @return Frame time variance in milliseconds squared
  41014. */
  41015. get: function () {
  41016. return this._rollingFrameTime.variance;
  41017. },
  41018. enumerable: true,
  41019. configurable: true
  41020. });
  41021. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41022. /**
  41023. * Returns the frame time of the most recent frame
  41024. * @return Frame time in milliseconds
  41025. */
  41026. get: function () {
  41027. return this._rollingFrameTime.history(0);
  41028. },
  41029. enumerable: true,
  41030. configurable: true
  41031. });
  41032. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41033. /**
  41034. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41035. * @return Framerate in frames per second
  41036. */
  41037. get: function () {
  41038. return 1000.0 / this._rollingFrameTime.average;
  41039. },
  41040. enumerable: true,
  41041. configurable: true
  41042. });
  41043. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41044. /**
  41045. * Returns the average framerate in frames per second using the most recent frame time
  41046. * @return Framerate in frames per second
  41047. */
  41048. get: function () {
  41049. var history = this._rollingFrameTime.history(0);
  41050. if (history === 0) {
  41051. return 0;
  41052. }
  41053. return 1000.0 / history;
  41054. },
  41055. enumerable: true,
  41056. configurable: true
  41057. });
  41058. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41059. /**
  41060. * Returns true if enough samples have been taken to completely fill the sliding window
  41061. * @return true if saturated
  41062. */
  41063. get: function () {
  41064. return this._rollingFrameTime.isSaturated();
  41065. },
  41066. enumerable: true,
  41067. configurable: true
  41068. });
  41069. /**
  41070. * Enables contributions to the sliding window sample set
  41071. */
  41072. PerformanceMonitor.prototype.enable = function () {
  41073. this._enabled = true;
  41074. };
  41075. /**
  41076. * Disables contributions to the sliding window sample set
  41077. * Samples will not be interpolated over the disabled period
  41078. */
  41079. PerformanceMonitor.prototype.disable = function () {
  41080. this._enabled = false;
  41081. //clear last sample to avoid interpolating over the disabled period when next enabled
  41082. this._lastFrameTimeMs = null;
  41083. };
  41084. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41085. /**
  41086. * Returns true if sampling is enabled
  41087. * @return true if enabled
  41088. */
  41089. get: function () {
  41090. return this._enabled;
  41091. },
  41092. enumerable: true,
  41093. configurable: true
  41094. });
  41095. /**
  41096. * Resets performance monitor
  41097. */
  41098. PerformanceMonitor.prototype.reset = function () {
  41099. //clear last sample to avoid interpolating over the disabled period when next enabled
  41100. this._lastFrameTimeMs = null;
  41101. //wipe record
  41102. this._rollingFrameTime.reset();
  41103. };
  41104. return PerformanceMonitor;
  41105. }());
  41106. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41107. /**
  41108. * RollingAverage
  41109. *
  41110. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41111. */
  41112. var RollingAverage = /** @class */ (function () {
  41113. /**
  41114. * constructor
  41115. * @param length The number of samples required to saturate the sliding window
  41116. */
  41117. function RollingAverage(length) {
  41118. this._samples = new Array(length);
  41119. this.reset();
  41120. }
  41121. /**
  41122. * Adds a sample to the sample set
  41123. * @param v The sample value
  41124. */
  41125. RollingAverage.prototype.add = function (v) {
  41126. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41127. var delta;
  41128. //we need to check if we've already wrapped round
  41129. if (this.isSaturated()) {
  41130. //remove bottom of stack from mean
  41131. var bottomValue = this._samples[this._pos];
  41132. delta = bottomValue - this.average;
  41133. this.average -= delta / (this._sampleCount - 1);
  41134. this._m2 -= delta * (bottomValue - this.average);
  41135. }
  41136. else {
  41137. this._sampleCount++;
  41138. }
  41139. //add new value to mean
  41140. delta = v - this.average;
  41141. this.average += delta / (this._sampleCount);
  41142. this._m2 += delta * (v - this.average);
  41143. //set the new variance
  41144. this.variance = this._m2 / (this._sampleCount - 1);
  41145. this._samples[this._pos] = v;
  41146. this._pos++;
  41147. this._pos %= this._samples.length; //positive wrap around
  41148. };
  41149. /**
  41150. * Returns previously added values or null if outside of history or outside the sliding window domain
  41151. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41152. * @return Value previously recorded with add() or null if outside of range
  41153. */
  41154. RollingAverage.prototype.history = function (i) {
  41155. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41156. return 0;
  41157. }
  41158. var i0 = this._wrapPosition(this._pos - 1.0);
  41159. return this._samples[this._wrapPosition(i0 - i)];
  41160. };
  41161. /**
  41162. * Returns true if enough samples have been taken to completely fill the sliding window
  41163. * @return true if sample-set saturated
  41164. */
  41165. RollingAverage.prototype.isSaturated = function () {
  41166. return this._sampleCount >= this._samples.length;
  41167. };
  41168. /**
  41169. * Resets the rolling average (equivalent to 0 samples taken so far)
  41170. */
  41171. RollingAverage.prototype.reset = function () {
  41172. this.average = 0;
  41173. this.variance = 0;
  41174. this._sampleCount = 0;
  41175. this._pos = 0;
  41176. this._m2 = 0;
  41177. };
  41178. /**
  41179. * Wraps a value around the sample range boundaries
  41180. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41181. * @return Wrapped position in sample range
  41182. */
  41183. RollingAverage.prototype._wrapPosition = function (i) {
  41184. var max = this._samples.length;
  41185. return ((i % max) + max) % max;
  41186. };
  41187. return RollingAverage;
  41188. }());
  41189. BABYLON.RollingAverage = RollingAverage;
  41190. })(BABYLON || (BABYLON = {}));
  41191. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41192. var BABYLON;
  41193. (function (BABYLON) {
  41194. /**
  41195. * This groups together the common properties used for image processing either in direct forward pass
  41196. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41197. * or not.
  41198. */
  41199. var ImageProcessingConfiguration = /** @class */ (function () {
  41200. function ImageProcessingConfiguration() {
  41201. /**
  41202. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41203. */
  41204. this.colorCurves = new BABYLON.ColorCurves();
  41205. this._colorCurvesEnabled = false;
  41206. this._colorGradingEnabled = false;
  41207. this._colorGradingWithGreenDepth = true;
  41208. this._colorGradingBGR = true;
  41209. this._exposure = 1.0;
  41210. this._toneMappingEnabled = false;
  41211. this._contrast = 1.0;
  41212. /**
  41213. * Vignette stretch size.
  41214. */
  41215. this.vignetteStretch = 0;
  41216. /**
  41217. * Vignette centre X Offset.
  41218. */
  41219. this.vignetteCentreX = 0;
  41220. /**
  41221. * Vignette centre Y Offset.
  41222. */
  41223. this.vignetteCentreY = 0;
  41224. /**
  41225. * Vignette weight or intensity of the vignette effect.
  41226. */
  41227. this.vignetteWeight = 1.5;
  41228. /**
  41229. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41230. * if vignetteEnabled is set to true.
  41231. */
  41232. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41233. /**
  41234. * Camera field of view used by the Vignette effect.
  41235. */
  41236. this.vignetteCameraFov = 0.5;
  41237. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41238. this._vignetteEnabled = false;
  41239. this._applyByPostProcess = false;
  41240. this._isEnabled = true;
  41241. /**
  41242. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41243. */
  41244. this.onUpdateParameters = new BABYLON.Observable();
  41245. }
  41246. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41247. /**
  41248. * Gets wether the color curves effect is enabled.
  41249. */
  41250. get: function () {
  41251. return this._colorCurvesEnabled;
  41252. },
  41253. /**
  41254. * Sets wether the color curves effect is enabled.
  41255. */
  41256. set: function (value) {
  41257. if (this._colorCurvesEnabled === value) {
  41258. return;
  41259. }
  41260. this._colorCurvesEnabled = value;
  41261. this._updateParameters();
  41262. },
  41263. enumerable: true,
  41264. configurable: true
  41265. });
  41266. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41267. /**
  41268. * Gets wether the color grading effect is enabled.
  41269. */
  41270. get: function () {
  41271. return this._colorGradingEnabled;
  41272. },
  41273. /**
  41274. * Sets wether the color grading effect is enabled.
  41275. */
  41276. set: function (value) {
  41277. if (this._colorGradingEnabled === value) {
  41278. return;
  41279. }
  41280. this._colorGradingEnabled = value;
  41281. this._updateParameters();
  41282. },
  41283. enumerable: true,
  41284. configurable: true
  41285. });
  41286. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41287. /**
  41288. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41289. */
  41290. get: function () {
  41291. return this._colorGradingWithGreenDepth;
  41292. },
  41293. /**
  41294. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41295. */
  41296. set: function (value) {
  41297. if (this._colorGradingWithGreenDepth === value) {
  41298. return;
  41299. }
  41300. this._colorGradingWithGreenDepth = value;
  41301. this._updateParameters();
  41302. },
  41303. enumerable: true,
  41304. configurable: true
  41305. });
  41306. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41307. /**
  41308. * Gets wether the color grading texture contains BGR values.
  41309. */
  41310. get: function () {
  41311. return this._colorGradingBGR;
  41312. },
  41313. /**
  41314. * Sets wether the color grading texture contains BGR values.
  41315. */
  41316. set: function (value) {
  41317. if (this._colorGradingBGR === value) {
  41318. return;
  41319. }
  41320. this._colorGradingBGR = value;
  41321. this._updateParameters();
  41322. },
  41323. enumerable: true,
  41324. configurable: true
  41325. });
  41326. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41327. /**
  41328. * Gets the Exposure used in the effect.
  41329. */
  41330. get: function () {
  41331. return this._exposure;
  41332. },
  41333. /**
  41334. * Sets the Exposure used in the effect.
  41335. */
  41336. set: function (value) {
  41337. if (this._exposure === value) {
  41338. return;
  41339. }
  41340. this._exposure = value;
  41341. this._updateParameters();
  41342. },
  41343. enumerable: true,
  41344. configurable: true
  41345. });
  41346. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41347. /**
  41348. * Gets wether the tone mapping effect is enabled.
  41349. */
  41350. get: function () {
  41351. return this._toneMappingEnabled;
  41352. },
  41353. /**
  41354. * Sets wether the tone mapping effect is enabled.
  41355. */
  41356. set: function (value) {
  41357. if (this._toneMappingEnabled === value) {
  41358. return;
  41359. }
  41360. this._toneMappingEnabled = value;
  41361. this._updateParameters();
  41362. },
  41363. enumerable: true,
  41364. configurable: true
  41365. });
  41366. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41367. /**
  41368. * Gets the contrast used in the effect.
  41369. */
  41370. get: function () {
  41371. return this._contrast;
  41372. },
  41373. /**
  41374. * Sets the contrast used in the effect.
  41375. */
  41376. set: function (value) {
  41377. if (this._contrast === value) {
  41378. return;
  41379. }
  41380. this._contrast = value;
  41381. this._updateParameters();
  41382. },
  41383. enumerable: true,
  41384. configurable: true
  41385. });
  41386. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41387. /**
  41388. * Gets the vignette blend mode allowing different kind of effect.
  41389. */
  41390. get: function () {
  41391. return this._vignetteBlendMode;
  41392. },
  41393. /**
  41394. * Sets the vignette blend mode allowing different kind of effect.
  41395. */
  41396. set: function (value) {
  41397. if (this._vignetteBlendMode === value) {
  41398. return;
  41399. }
  41400. this._vignetteBlendMode = value;
  41401. this._updateParameters();
  41402. },
  41403. enumerable: true,
  41404. configurable: true
  41405. });
  41406. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41407. /**
  41408. * Gets wether the vignette effect is enabled.
  41409. */
  41410. get: function () {
  41411. return this._vignetteEnabled;
  41412. },
  41413. /**
  41414. * Sets wether the vignette effect is enabled.
  41415. */
  41416. set: function (value) {
  41417. if (this._vignetteEnabled === value) {
  41418. return;
  41419. }
  41420. this._vignetteEnabled = value;
  41421. this._updateParameters();
  41422. },
  41423. enumerable: true,
  41424. configurable: true
  41425. });
  41426. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41427. /**
  41428. * Gets wether the image processing is applied through a post process or not.
  41429. */
  41430. get: function () {
  41431. return this._applyByPostProcess;
  41432. },
  41433. /**
  41434. * Sets wether the image processing is applied through a post process or not.
  41435. */
  41436. set: function (value) {
  41437. if (this._applyByPostProcess === value) {
  41438. return;
  41439. }
  41440. this._applyByPostProcess = value;
  41441. this._updateParameters();
  41442. },
  41443. enumerable: true,
  41444. configurable: true
  41445. });
  41446. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41447. /**
  41448. * Gets wether the image processing is enabled or not.
  41449. */
  41450. get: function () {
  41451. return this._isEnabled;
  41452. },
  41453. /**
  41454. * Sets wether the image processing is enabled or not.
  41455. */
  41456. set: function (value) {
  41457. if (this._isEnabled === value) {
  41458. return;
  41459. }
  41460. this._isEnabled = value;
  41461. this._updateParameters();
  41462. },
  41463. enumerable: true,
  41464. configurable: true
  41465. });
  41466. /**
  41467. * Method called each time the image processing information changes requires to recompile the effect.
  41468. */
  41469. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41470. this.onUpdateParameters.notifyObservers(this);
  41471. };
  41472. ImageProcessingConfiguration.prototype.getClassName = function () {
  41473. return "ImageProcessingConfiguration";
  41474. };
  41475. /**
  41476. * Prepare the list of uniforms associated with the Image Processing effects.
  41477. * @param uniformsList The list of uniforms used in the effect
  41478. * @param defines the list of defines currently in use
  41479. */
  41480. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41481. if (defines.EXPOSURE) {
  41482. uniforms.push("exposureLinear");
  41483. }
  41484. if (defines.CONTRAST) {
  41485. uniforms.push("contrast");
  41486. }
  41487. if (defines.COLORGRADING) {
  41488. uniforms.push("colorTransformSettings");
  41489. }
  41490. if (defines.VIGNETTE) {
  41491. uniforms.push("vInverseScreenSize");
  41492. uniforms.push("vignetteSettings1");
  41493. uniforms.push("vignetteSettings2");
  41494. }
  41495. if (defines.COLORCURVES) {
  41496. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41497. }
  41498. };
  41499. /**
  41500. * Prepare the list of samplers associated with the Image Processing effects.
  41501. * @param uniformsList The list of uniforms used in the effect
  41502. * @param defines the list of defines currently in use
  41503. */
  41504. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41505. if (defines.COLORGRADING) {
  41506. samplersList.push("txColorTransform");
  41507. }
  41508. };
  41509. /**
  41510. * Prepare the list of defines associated to the shader.
  41511. * @param defines the list of defines to complete
  41512. */
  41513. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41514. if (forPostProcess === void 0) { forPostProcess = false; }
  41515. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41516. defines.VIGNETTE = false;
  41517. defines.TONEMAPPING = false;
  41518. defines.CONTRAST = false;
  41519. defines.EXPOSURE = false;
  41520. defines.COLORCURVES = false;
  41521. defines.COLORGRADING = false;
  41522. defines.COLORGRADING3D = false;
  41523. defines.IMAGEPROCESSING = false;
  41524. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41525. return;
  41526. }
  41527. defines.VIGNETTE = this.vignetteEnabled;
  41528. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41529. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41530. defines.TONEMAPPING = this.toneMappingEnabled;
  41531. defines.CONTRAST = (this.contrast !== 1.0);
  41532. defines.EXPOSURE = (this.exposure !== 1.0);
  41533. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41534. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41535. if (defines.COLORGRADING) {
  41536. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41537. }
  41538. else {
  41539. defines.COLORGRADING3D = false;
  41540. }
  41541. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41542. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41543. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41544. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41545. };
  41546. /**
  41547. * Returns true if all the image processing information are ready.
  41548. */
  41549. ImageProcessingConfiguration.prototype.isReady = function () {
  41550. // Color Grading texure can not be none blocking.
  41551. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41552. };
  41553. /**
  41554. * Binds the image processing to the shader.
  41555. * @param effect The effect to bind to
  41556. */
  41557. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41558. if (aspectRatio === void 0) { aspectRatio = 1; }
  41559. // Color Curves
  41560. if (this._colorCurvesEnabled && this.colorCurves) {
  41561. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41562. }
  41563. // Vignette
  41564. if (this._vignetteEnabled) {
  41565. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41566. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41567. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41568. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41569. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41570. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41571. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41572. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41573. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41574. var vignettePower = -2.0 * this.vignetteWeight;
  41575. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41576. }
  41577. // Exposure
  41578. effect.setFloat("exposureLinear", this.exposure);
  41579. // Contrast
  41580. effect.setFloat("contrast", this.contrast);
  41581. // Color transform settings
  41582. if (this.colorGradingTexture) {
  41583. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41584. var textureSize = this.colorGradingTexture.getSize().height;
  41585. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41586. 0.5 / textureSize, // textureOffset
  41587. textureSize, // textureSize
  41588. this.colorGradingTexture.level // weight
  41589. );
  41590. }
  41591. };
  41592. /**
  41593. * Clones the current image processing instance.
  41594. * @return The cloned image processing
  41595. */
  41596. ImageProcessingConfiguration.prototype.clone = function () {
  41597. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41598. };
  41599. /**
  41600. * Serializes the current image processing instance to a json representation.
  41601. * @return a JSON representation
  41602. */
  41603. ImageProcessingConfiguration.prototype.serialize = function () {
  41604. return BABYLON.SerializationHelper.Serialize(this);
  41605. };
  41606. /**
  41607. * Parses the image processing from a json representation.
  41608. * @param source the JSON source to parse
  41609. * @return The parsed image processing
  41610. */
  41611. ImageProcessingConfiguration.Parse = function (source) {
  41612. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41613. };
  41614. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41615. /**
  41616. * Used to apply the vignette as a mix with the pixel color.
  41617. */
  41618. get: function () {
  41619. return this._VIGNETTEMODE_MULTIPLY;
  41620. },
  41621. enumerable: true,
  41622. configurable: true
  41623. });
  41624. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41625. /**
  41626. * Used to apply the vignette as a replacement of the pixel color.
  41627. */
  41628. get: function () {
  41629. return this._VIGNETTEMODE_OPAQUE;
  41630. },
  41631. enumerable: true,
  41632. configurable: true
  41633. });
  41634. // Static constants associated to the image processing.
  41635. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41636. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41637. __decorate([
  41638. BABYLON.serializeAsColorCurves()
  41639. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41640. __decorate([
  41641. BABYLON.serialize()
  41642. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41643. __decorate([
  41644. BABYLON.serializeAsTexture()
  41645. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41646. __decorate([
  41647. BABYLON.serialize()
  41648. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41649. __decorate([
  41650. BABYLON.serialize()
  41651. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41652. __decorate([
  41653. BABYLON.serialize()
  41654. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41655. __decorate([
  41656. BABYLON.serialize()
  41657. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41658. __decorate([
  41659. BABYLON.serialize()
  41660. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41661. __decorate([
  41662. BABYLON.serialize()
  41663. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41664. __decorate([
  41665. BABYLON.serialize()
  41666. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41667. __decorate([
  41668. BABYLON.serialize()
  41669. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41670. __decorate([
  41671. BABYLON.serialize()
  41672. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41673. __decorate([
  41674. BABYLON.serialize()
  41675. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41676. __decorate([
  41677. BABYLON.serializeAsColor4()
  41678. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41679. __decorate([
  41680. BABYLON.serialize()
  41681. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41682. __decorate([
  41683. BABYLON.serialize()
  41684. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41685. __decorate([
  41686. BABYLON.serialize()
  41687. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41688. __decorate([
  41689. BABYLON.serialize()
  41690. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41691. __decorate([
  41692. BABYLON.serialize()
  41693. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41694. return ImageProcessingConfiguration;
  41695. }());
  41696. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41697. })(BABYLON || (BABYLON = {}));
  41698. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41699. var BABYLON;
  41700. (function (BABYLON) {
  41701. /**
  41702. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41703. * It can help converting any input color in a desired output one. This can then be used to create effects
  41704. * from sepia, black and white to sixties or futuristic rendering...
  41705. *
  41706. * The only supported format is currently 3dl.
  41707. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41708. */
  41709. var ColorGradingTexture = /** @class */ (function (_super) {
  41710. __extends(ColorGradingTexture, _super);
  41711. /**
  41712. * Instantiates a ColorGradingTexture from the following parameters.
  41713. *
  41714. * @param url The location of the color gradind data (currently only supporting 3dl)
  41715. * @param scene The scene the texture will be used in
  41716. */
  41717. function ColorGradingTexture(url, scene) {
  41718. var _this = _super.call(this, scene) || this;
  41719. if (!url) {
  41720. return _this;
  41721. }
  41722. _this._engine = scene.getEngine();
  41723. _this._textureMatrix = BABYLON.Matrix.Identity();
  41724. _this.name = url;
  41725. _this.url = url;
  41726. _this.hasAlpha = false;
  41727. _this.isCube = false;
  41728. _this.is3D = _this._engine.webGLVersion > 1;
  41729. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41730. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41731. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41732. _this.anisotropicFilteringLevel = 1;
  41733. _this._texture = _this._getFromCache(url, true);
  41734. if (!_this._texture) {
  41735. if (!scene.useDelayedTextureLoading) {
  41736. _this.loadTexture();
  41737. }
  41738. else {
  41739. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41740. }
  41741. }
  41742. return _this;
  41743. }
  41744. /**
  41745. * Returns the texture matrix used in most of the material.
  41746. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41747. */
  41748. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41749. return this._textureMatrix;
  41750. };
  41751. /**
  41752. * Occurs when the file being loaded is a .3dl LUT file.
  41753. */
  41754. ColorGradingTexture.prototype.load3dlTexture = function () {
  41755. var engine = this._engine;
  41756. var texture;
  41757. if (engine.webGLVersion === 1) {
  41758. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41759. }
  41760. else {
  41761. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41762. }
  41763. this._texture = texture;
  41764. var callback = function (text) {
  41765. if (typeof text !== "string") {
  41766. return;
  41767. }
  41768. var data = null;
  41769. var tempData = null;
  41770. var line;
  41771. var lines = text.split('\n');
  41772. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41773. var maxColor = 0;
  41774. for (var i = 0; i < lines.length; i++) {
  41775. line = lines[i];
  41776. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41777. continue;
  41778. if (line.indexOf('#') === 0)
  41779. continue;
  41780. var words = line.split(" ");
  41781. if (size === 0) {
  41782. // Number of space + one
  41783. size = words.length;
  41784. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41785. tempData = new Float32Array(size * size * size * 4);
  41786. continue;
  41787. }
  41788. if (size != 0) {
  41789. var r = Math.max(parseInt(words[0]), 0);
  41790. var g = Math.max(parseInt(words[1]), 0);
  41791. var b = Math.max(parseInt(words[2]), 0);
  41792. maxColor = Math.max(r, maxColor);
  41793. maxColor = Math.max(g, maxColor);
  41794. maxColor = Math.max(b, maxColor);
  41795. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41796. if (tempData) {
  41797. tempData[pixelStorageIndex + 0] = r;
  41798. tempData[pixelStorageIndex + 1] = g;
  41799. tempData[pixelStorageIndex + 2] = b;
  41800. }
  41801. pixelIndexSlice++;
  41802. if (pixelIndexSlice % size == 0) {
  41803. pixelIndexH++;
  41804. pixelIndexSlice = 0;
  41805. if (pixelIndexH % size == 0) {
  41806. pixelIndexW++;
  41807. pixelIndexH = 0;
  41808. }
  41809. }
  41810. }
  41811. }
  41812. if (tempData && data) {
  41813. for (var i = 0; i < tempData.length; i++) {
  41814. if (i > 0 && (i + 1) % 4 === 0) {
  41815. data[i] = 255;
  41816. }
  41817. else {
  41818. var value = tempData[i];
  41819. data[i] = (value / maxColor * 255);
  41820. }
  41821. }
  41822. }
  41823. if (texture.is3D) {
  41824. texture.updateSize(size, size, size);
  41825. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41826. }
  41827. else {
  41828. texture.updateSize(size * size, size);
  41829. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41830. }
  41831. };
  41832. var scene = this.getScene();
  41833. if (scene) {
  41834. scene._loadFile(this.url, callback);
  41835. }
  41836. else {
  41837. this._engine._loadFile(this.url, callback);
  41838. }
  41839. return this._texture;
  41840. };
  41841. /**
  41842. * Starts the loading process of the texture.
  41843. */
  41844. ColorGradingTexture.prototype.loadTexture = function () {
  41845. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41846. this.load3dlTexture();
  41847. }
  41848. };
  41849. /**
  41850. * Clones the color gradind texture.
  41851. */
  41852. ColorGradingTexture.prototype.clone = function () {
  41853. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41854. // Base texture
  41855. newTexture.level = this.level;
  41856. return newTexture;
  41857. };
  41858. /**
  41859. * Called during delayed load for textures.
  41860. */
  41861. ColorGradingTexture.prototype.delayLoad = function () {
  41862. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41863. return;
  41864. }
  41865. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41866. this._texture = this._getFromCache(this.url, true);
  41867. if (!this._texture) {
  41868. this.loadTexture();
  41869. }
  41870. };
  41871. /**
  41872. * Parses a color grading texture serialized by Babylon.
  41873. * @param parsedTexture The texture information being parsedTexture
  41874. * @param scene The scene to load the texture in
  41875. * @param rootUrl The root url of the data assets to load
  41876. * @return A color gradind texture
  41877. */
  41878. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41879. var texture = null;
  41880. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41881. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41882. texture.name = parsedTexture.name;
  41883. texture.level = parsedTexture.level;
  41884. }
  41885. return texture;
  41886. };
  41887. /**
  41888. * Serializes the LUT texture to json format.
  41889. */
  41890. ColorGradingTexture.prototype.serialize = function () {
  41891. if (!this.name) {
  41892. return null;
  41893. }
  41894. var serializationObject = {};
  41895. serializationObject.name = this.name;
  41896. serializationObject.level = this.level;
  41897. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41898. return serializationObject;
  41899. };
  41900. /**
  41901. * Empty line regex stored for GC.
  41902. */
  41903. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41904. return ColorGradingTexture;
  41905. }(BABYLON.BaseTexture));
  41906. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41907. })(BABYLON || (BABYLON = {}));
  41908. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41909. var BABYLON;
  41910. (function (BABYLON) {
  41911. /**
  41912. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41913. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41914. * 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;
  41915. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41916. */
  41917. var ColorCurves = /** @class */ (function () {
  41918. function ColorCurves() {
  41919. this._dirty = true;
  41920. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41921. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41922. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41923. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41924. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41925. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41926. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41927. this._globalHue = 30;
  41928. this._globalDensity = 0;
  41929. this._globalSaturation = 0;
  41930. this._globalExposure = 0;
  41931. this._highlightsHue = 30;
  41932. this._highlightsDensity = 0;
  41933. this._highlightsSaturation = 0;
  41934. this._highlightsExposure = 0;
  41935. this._midtonesHue = 30;
  41936. this._midtonesDensity = 0;
  41937. this._midtonesSaturation = 0;
  41938. this._midtonesExposure = 0;
  41939. this._shadowsHue = 30;
  41940. this._shadowsDensity = 0;
  41941. this._shadowsSaturation = 0;
  41942. this._shadowsExposure = 0;
  41943. }
  41944. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41945. /**
  41946. * Gets the global Hue value.
  41947. * 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).
  41948. */
  41949. get: function () {
  41950. return this._globalHue;
  41951. },
  41952. /**
  41953. * Sets the global Hue value.
  41954. * 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).
  41955. */
  41956. set: function (value) {
  41957. this._globalHue = value;
  41958. this._dirty = true;
  41959. },
  41960. enumerable: true,
  41961. configurable: true
  41962. });
  41963. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41964. /**
  41965. * Gets the global Density value.
  41966. * 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.
  41967. * Values less than zero provide a filter of opposite hue.
  41968. */
  41969. get: function () {
  41970. return this._globalDensity;
  41971. },
  41972. /**
  41973. * Sets the global Density value.
  41974. * 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.
  41975. * Values less than zero provide a filter of opposite hue.
  41976. */
  41977. set: function (value) {
  41978. this._globalDensity = value;
  41979. this._dirty = true;
  41980. },
  41981. enumerable: true,
  41982. configurable: true
  41983. });
  41984. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41985. /**
  41986. * Gets the global Saturation value.
  41987. * 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.
  41988. */
  41989. get: function () {
  41990. return this._globalSaturation;
  41991. },
  41992. /**
  41993. * Sets the global Saturation value.
  41994. * 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.
  41995. */
  41996. set: function (value) {
  41997. this._globalSaturation = value;
  41998. this._dirty = true;
  41999. },
  42000. enumerable: true,
  42001. configurable: true
  42002. });
  42003. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  42004. /**
  42005. * Gets the global Exposure value.
  42006. * 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.
  42007. */
  42008. get: function () {
  42009. return this._globalExposure;
  42010. },
  42011. /**
  42012. * Sets the global Exposure value.
  42013. * 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.
  42014. */
  42015. set: function (value) {
  42016. this._globalExposure = value;
  42017. this._dirty = true;
  42018. },
  42019. enumerable: true,
  42020. configurable: true
  42021. });
  42022. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  42023. /**
  42024. * Gets the highlights Hue value.
  42025. * 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).
  42026. */
  42027. get: function () {
  42028. return this._highlightsHue;
  42029. },
  42030. /**
  42031. * Sets the highlights Hue value.
  42032. * 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).
  42033. */
  42034. set: function (value) {
  42035. this._highlightsHue = value;
  42036. this._dirty = true;
  42037. },
  42038. enumerable: true,
  42039. configurable: true
  42040. });
  42041. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42042. /**
  42043. * Gets the highlights Density value.
  42044. * 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.
  42045. * Values less than zero provide a filter of opposite hue.
  42046. */
  42047. get: function () {
  42048. return this._highlightsDensity;
  42049. },
  42050. /**
  42051. * Sets the highlights Density value.
  42052. * 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.
  42053. * Values less than zero provide a filter of opposite hue.
  42054. */
  42055. set: function (value) {
  42056. this._highlightsDensity = value;
  42057. this._dirty = true;
  42058. },
  42059. enumerable: true,
  42060. configurable: true
  42061. });
  42062. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42063. /**
  42064. * Gets the highlights Saturation value.
  42065. * 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.
  42066. */
  42067. get: function () {
  42068. return this._highlightsSaturation;
  42069. },
  42070. /**
  42071. * Sets the highlights Saturation value.
  42072. * 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.
  42073. */
  42074. set: function (value) {
  42075. this._highlightsSaturation = value;
  42076. this._dirty = true;
  42077. },
  42078. enumerable: true,
  42079. configurable: true
  42080. });
  42081. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42082. /**
  42083. * Gets the highlights Exposure value.
  42084. * 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.
  42085. */
  42086. get: function () {
  42087. return this._highlightsExposure;
  42088. },
  42089. /**
  42090. * Sets the highlights Exposure value.
  42091. * 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.
  42092. */
  42093. set: function (value) {
  42094. this._highlightsExposure = value;
  42095. this._dirty = true;
  42096. },
  42097. enumerable: true,
  42098. configurable: true
  42099. });
  42100. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42101. /**
  42102. * Gets the midtones Hue value.
  42103. * 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).
  42104. */
  42105. get: function () {
  42106. return this._midtonesHue;
  42107. },
  42108. /**
  42109. * Sets the midtones Hue value.
  42110. * 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).
  42111. */
  42112. set: function (value) {
  42113. this._midtonesHue = value;
  42114. this._dirty = true;
  42115. },
  42116. enumerable: true,
  42117. configurable: true
  42118. });
  42119. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42120. /**
  42121. * Gets the midtones Density value.
  42122. * 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.
  42123. * Values less than zero provide a filter of opposite hue.
  42124. */
  42125. get: function () {
  42126. return this._midtonesDensity;
  42127. },
  42128. /**
  42129. * Sets the midtones Density value.
  42130. * 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.
  42131. * Values less than zero provide a filter of opposite hue.
  42132. */
  42133. set: function (value) {
  42134. this._midtonesDensity = value;
  42135. this._dirty = true;
  42136. },
  42137. enumerable: true,
  42138. configurable: true
  42139. });
  42140. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42141. /**
  42142. * Gets the midtones Saturation value.
  42143. * 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.
  42144. */
  42145. get: function () {
  42146. return this._midtonesSaturation;
  42147. },
  42148. /**
  42149. * Sets the midtones Saturation value.
  42150. * 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.
  42151. */
  42152. set: function (value) {
  42153. this._midtonesSaturation = value;
  42154. this._dirty = true;
  42155. },
  42156. enumerable: true,
  42157. configurable: true
  42158. });
  42159. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42160. /**
  42161. * Gets the midtones Exposure value.
  42162. * 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.
  42163. */
  42164. get: function () {
  42165. return this._midtonesExposure;
  42166. },
  42167. /**
  42168. * Sets the midtones Exposure value.
  42169. * 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.
  42170. */
  42171. set: function (value) {
  42172. this._midtonesExposure = value;
  42173. this._dirty = true;
  42174. },
  42175. enumerable: true,
  42176. configurable: true
  42177. });
  42178. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42179. /**
  42180. * Gets the shadows Hue value.
  42181. * 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).
  42182. */
  42183. get: function () {
  42184. return this._shadowsHue;
  42185. },
  42186. /**
  42187. * Sets the shadows Hue value.
  42188. * 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).
  42189. */
  42190. set: function (value) {
  42191. this._shadowsHue = value;
  42192. this._dirty = true;
  42193. },
  42194. enumerable: true,
  42195. configurable: true
  42196. });
  42197. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42198. /**
  42199. * Gets the shadows Density value.
  42200. * 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.
  42201. * Values less than zero provide a filter of opposite hue.
  42202. */
  42203. get: function () {
  42204. return this._shadowsDensity;
  42205. },
  42206. /**
  42207. * Sets the shadows Density value.
  42208. * 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.
  42209. * Values less than zero provide a filter of opposite hue.
  42210. */
  42211. set: function (value) {
  42212. this._shadowsDensity = value;
  42213. this._dirty = true;
  42214. },
  42215. enumerable: true,
  42216. configurable: true
  42217. });
  42218. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42219. /**
  42220. * Gets the shadows Saturation value.
  42221. * 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.
  42222. */
  42223. get: function () {
  42224. return this._shadowsSaturation;
  42225. },
  42226. /**
  42227. * Sets the shadows Saturation value.
  42228. * 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.
  42229. */
  42230. set: function (value) {
  42231. this._shadowsSaturation = value;
  42232. this._dirty = true;
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42238. /**
  42239. * Gets the shadows Exposure value.
  42240. * 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.
  42241. */
  42242. get: function () {
  42243. return this._shadowsExposure;
  42244. },
  42245. /**
  42246. * Sets the shadows Exposure value.
  42247. * 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.
  42248. */
  42249. set: function (value) {
  42250. this._shadowsExposure = value;
  42251. this._dirty = true;
  42252. },
  42253. enumerable: true,
  42254. configurable: true
  42255. });
  42256. ColorCurves.prototype.getClassName = function () {
  42257. return "ColorCurves";
  42258. };
  42259. /**
  42260. * Binds the color curves to the shader.
  42261. * @param colorCurves The color curve to bind
  42262. * @param effect The effect to bind to
  42263. */
  42264. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42265. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42266. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42267. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42268. if (colorCurves._dirty) {
  42269. colorCurves._dirty = false;
  42270. // Fill in global info.
  42271. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42272. // Compute highlights info.
  42273. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42274. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42275. // Compute midtones info.
  42276. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42277. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42278. // Compute shadows info.
  42279. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42280. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42281. // Compute deltas (neutral is midtones).
  42282. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42283. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42284. }
  42285. if (effect) {
  42286. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42287. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42288. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42289. }
  42290. };
  42291. /**
  42292. * Prepare the list of uniforms associated with the ColorCurves effects.
  42293. * @param uniformsList The list of uniforms used in the effect
  42294. */
  42295. ColorCurves.PrepareUniforms = function (uniformsList) {
  42296. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42297. };
  42298. /**
  42299. * Returns color grading data based on a hue, density, saturation and exposure value.
  42300. * @param filterHue The hue of the color filter.
  42301. * @param filterDensity The density of the color filter.
  42302. * @param saturation The saturation.
  42303. * @param exposure The exposure.
  42304. * @param result The result data container.
  42305. */
  42306. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42307. if (hue == null) {
  42308. return;
  42309. }
  42310. hue = ColorCurves.clamp(hue, 0, 360);
  42311. density = ColorCurves.clamp(density, -100, 100);
  42312. saturation = ColorCurves.clamp(saturation, -100, 100);
  42313. exposure = ColorCurves.clamp(exposure, -100, 100);
  42314. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42315. // so that the maximum filter density is only 50% control. This provides fine control
  42316. // for small values and reasonable range.
  42317. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42318. density *= 0.5;
  42319. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42320. if (density < 0) {
  42321. density *= -1;
  42322. hue = (hue + 180) % 360;
  42323. }
  42324. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42325. result.scaleToRef(2, result);
  42326. result.a = 1 + 0.01 * saturation;
  42327. };
  42328. /**
  42329. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42330. * @param value The input slider value in range [-100,100].
  42331. * @returns Adjusted value.
  42332. */
  42333. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42334. value /= 100;
  42335. var x = Math.abs(value);
  42336. x = Math.pow(x, 2);
  42337. if (value < 0) {
  42338. x *= -1;
  42339. }
  42340. x *= 100;
  42341. return x;
  42342. };
  42343. /**
  42344. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42345. * @param hue The hue (H) input.
  42346. * @param saturation The saturation (S) input.
  42347. * @param brightness The brightness (B) input.
  42348. * @result An RGBA color represented as Vector4.
  42349. */
  42350. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42351. var h = ColorCurves.clamp(hue, 0, 360);
  42352. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42353. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42354. if (s === 0) {
  42355. result.r = v;
  42356. result.g = v;
  42357. result.b = v;
  42358. }
  42359. else {
  42360. // sector 0 to 5
  42361. h /= 60;
  42362. var i = Math.floor(h);
  42363. // fractional part of h
  42364. var f = h - i;
  42365. var p = v * (1 - s);
  42366. var q = v * (1 - s * f);
  42367. var t = v * (1 - s * (1 - f));
  42368. switch (i) {
  42369. case 0:
  42370. result.r = v;
  42371. result.g = t;
  42372. result.b = p;
  42373. break;
  42374. case 1:
  42375. result.r = q;
  42376. result.g = v;
  42377. result.b = p;
  42378. break;
  42379. case 2:
  42380. result.r = p;
  42381. result.g = v;
  42382. result.b = t;
  42383. break;
  42384. case 3:
  42385. result.r = p;
  42386. result.g = q;
  42387. result.b = v;
  42388. break;
  42389. case 4:
  42390. result.r = t;
  42391. result.g = p;
  42392. result.b = v;
  42393. break;
  42394. default: // case 5:
  42395. result.r = v;
  42396. result.g = p;
  42397. result.b = q;
  42398. break;
  42399. }
  42400. }
  42401. result.a = 1;
  42402. };
  42403. /**
  42404. * Returns a value clamped between min and max
  42405. * @param value The value to clamp
  42406. * @param min The minimum of value
  42407. * @param max The maximum of value
  42408. * @returns The clamped value.
  42409. */
  42410. ColorCurves.clamp = function (value, min, max) {
  42411. return Math.min(Math.max(value, min), max);
  42412. };
  42413. /**
  42414. * Clones the current color curve instance.
  42415. * @return The cloned curves
  42416. */
  42417. ColorCurves.prototype.clone = function () {
  42418. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42419. };
  42420. /**
  42421. * Serializes the current color curve instance to a json representation.
  42422. * @return a JSON representation
  42423. */
  42424. ColorCurves.prototype.serialize = function () {
  42425. return BABYLON.SerializationHelper.Serialize(this);
  42426. };
  42427. /**
  42428. * Parses the color curve from a json representation.
  42429. * @param source the JSON source to parse
  42430. * @return The parsed curves
  42431. */
  42432. ColorCurves.Parse = function (source) {
  42433. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42434. };
  42435. __decorate([
  42436. BABYLON.serialize()
  42437. ], ColorCurves.prototype, "_globalHue", void 0);
  42438. __decorate([
  42439. BABYLON.serialize()
  42440. ], ColorCurves.prototype, "_globalDensity", void 0);
  42441. __decorate([
  42442. BABYLON.serialize()
  42443. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42444. __decorate([
  42445. BABYLON.serialize()
  42446. ], ColorCurves.prototype, "_globalExposure", void 0);
  42447. __decorate([
  42448. BABYLON.serialize()
  42449. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42450. __decorate([
  42451. BABYLON.serialize()
  42452. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42453. __decorate([
  42454. BABYLON.serialize()
  42455. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42456. __decorate([
  42457. BABYLON.serialize()
  42458. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42459. __decorate([
  42460. BABYLON.serialize()
  42461. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42462. __decorate([
  42463. BABYLON.serialize()
  42464. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42465. __decorate([
  42466. BABYLON.serialize()
  42467. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42468. __decorate([
  42469. BABYLON.serialize()
  42470. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42471. return ColorCurves;
  42472. }());
  42473. BABYLON.ColorCurves = ColorCurves;
  42474. })(BABYLON || (BABYLON = {}));
  42475. //# sourceMappingURL=babylon.colorCurves.js.map
  42476. //# sourceMappingURL=babylon.behavior.js.map
  42477. var BABYLON;
  42478. (function (BABYLON) {
  42479. /**
  42480. * "Static Class" containing the most commonly used helper while dealing with material for
  42481. * rendering purpose.
  42482. *
  42483. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42484. *
  42485. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42486. */
  42487. var MaterialHelper = /** @class */ (function () {
  42488. function MaterialHelper() {
  42489. }
  42490. /**
  42491. * Bind the current view position to an effect.
  42492. * @param effect The effect to be bound
  42493. * @param scene The scene the eyes position is used from
  42494. */
  42495. MaterialHelper.BindEyePosition = function (effect, scene) {
  42496. if (scene._forcedViewPosition) {
  42497. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42498. return;
  42499. }
  42500. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42501. };
  42502. /**
  42503. * Helps preparing the defines values about the UVs in used in the effect.
  42504. * UVs are shared as much as we can accross chanels in the shaders.
  42505. * @param texture The texture we are preparing the UVs for
  42506. * @param defines The defines to update
  42507. * @param key The chanel key "diffuse", "specular"... used in the shader
  42508. */
  42509. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42510. defines._needUVs = true;
  42511. defines[key] = true;
  42512. if (texture.getTextureMatrix().isIdentity(true)) {
  42513. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42514. if (texture.coordinatesIndex === 0) {
  42515. defines["MAINUV1"] = true;
  42516. }
  42517. else {
  42518. defines["MAINUV2"] = true;
  42519. }
  42520. }
  42521. else {
  42522. defines[key + "DIRECTUV"] = 0;
  42523. }
  42524. };
  42525. /**
  42526. * Binds a texture matrix value to its corrsponding uniform
  42527. * @param texture The texture to bind the matrix for
  42528. * @param uniformBuffer The uniform buffer receivin the data
  42529. * @param key The chanel key "diffuse", "specular"... used in the shader
  42530. */
  42531. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42532. var matrix = texture.getTextureMatrix();
  42533. if (!matrix.isIdentity(true)) {
  42534. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42535. }
  42536. };
  42537. /**
  42538. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42539. * @param mesh defines the current mesh
  42540. * @param scene defines the current scene
  42541. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42542. * @param pointsCloud defines if point cloud rendering has to be turned on
  42543. * @param fogEnabled defines if fog has to be turned on
  42544. * @param alphaTest defines if alpha testing has to be turned on
  42545. * @param defines defines the current list of defines
  42546. */
  42547. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42548. if (defines._areMiscDirty) {
  42549. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42550. defines["POINTSIZE"] = pointsCloud;
  42551. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42552. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42553. defines["ALPHATEST"] = alphaTest;
  42554. }
  42555. };
  42556. /**
  42557. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42558. * @param scene defines the current scene
  42559. * @param engine defines the current engine
  42560. * @param defines specifies the list of active defines
  42561. * @param useInstances defines if instances have to be turned on
  42562. * @param useClipPlane defines if clip plane have to be turned on
  42563. */
  42564. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42565. if (useClipPlane === void 0) { useClipPlane = null; }
  42566. var changed = false;
  42567. if (useClipPlane == null) {
  42568. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42569. }
  42570. if (defines["CLIPPLANE"] !== useClipPlane) {
  42571. defines["CLIPPLANE"] = useClipPlane;
  42572. changed = true;
  42573. }
  42574. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42575. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42576. changed = true;
  42577. }
  42578. if (defines["INSTANCES"] !== useInstances) {
  42579. defines["INSTANCES"] = useInstances;
  42580. changed = true;
  42581. }
  42582. if (changed) {
  42583. defines.markAsUnprocessed();
  42584. }
  42585. };
  42586. /**
  42587. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42588. * @param mesh The mesh containing the geometry data we will draw
  42589. * @param defines The defines to update
  42590. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42591. * @param useBones Precise whether bones should be used or not (override mesh info)
  42592. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42593. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42594. * @returns false if defines are considered not dirty and have not been checked
  42595. */
  42596. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42597. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42598. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42599. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42600. return false;
  42601. }
  42602. defines._normals = defines._needNormals;
  42603. defines._uvs = defines._needUVs;
  42604. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42605. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42606. defines["TANGENT"] = true;
  42607. }
  42608. if (defines._needUVs) {
  42609. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42610. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42611. }
  42612. else {
  42613. defines["UV1"] = false;
  42614. defines["UV2"] = false;
  42615. }
  42616. if (useVertexColor) {
  42617. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42618. defines["VERTEXCOLOR"] = hasVertexColors;
  42619. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42620. }
  42621. if (useBones) {
  42622. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42623. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42624. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42625. }
  42626. else {
  42627. defines["NUM_BONE_INFLUENCERS"] = 0;
  42628. defines["BonesPerMesh"] = 0;
  42629. }
  42630. }
  42631. if (useMorphTargets) {
  42632. var manager = mesh.morphTargetManager;
  42633. if (manager) {
  42634. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42635. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42636. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42637. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42638. }
  42639. else {
  42640. defines["MORPHTARGETS_TANGENT"] = false;
  42641. defines["MORPHTARGETS_NORMAL"] = false;
  42642. defines["MORPHTARGETS"] = false;
  42643. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42644. }
  42645. }
  42646. return true;
  42647. };
  42648. /**
  42649. * Prepares the defines related to the light information passed in parameter
  42650. * @param scene The scene we are intending to draw
  42651. * @param mesh The mesh the effect is compiling for
  42652. * @param defines The defines to update
  42653. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42654. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42655. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42656. * @returns true if normals will be required for the rest of the effect
  42657. */
  42658. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42659. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42660. if (disableLighting === void 0) { disableLighting = false; }
  42661. if (!defines._areLightsDirty) {
  42662. return defines._needNormals;
  42663. }
  42664. var lightIndex = 0;
  42665. var needNormals = false;
  42666. var needRebuild = false;
  42667. var lightmapMode = false;
  42668. var shadowEnabled = false;
  42669. var specularEnabled = false;
  42670. if (scene.lightsEnabled && !disableLighting) {
  42671. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42672. var light = _a[_i];
  42673. needNormals = true;
  42674. if (defines["LIGHT" + lightIndex] === undefined) {
  42675. needRebuild = true;
  42676. }
  42677. defines["LIGHT" + lightIndex] = true;
  42678. defines["SPOTLIGHT" + lightIndex] = false;
  42679. defines["HEMILIGHT" + lightIndex] = false;
  42680. defines["POINTLIGHT" + lightIndex] = false;
  42681. defines["DIRLIGHT" + lightIndex] = false;
  42682. var type;
  42683. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42684. type = "SPOTLIGHT" + lightIndex;
  42685. var spotLight = light;
  42686. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42687. }
  42688. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42689. type = "HEMILIGHT" + lightIndex;
  42690. }
  42691. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42692. type = "POINTLIGHT" + lightIndex;
  42693. }
  42694. else {
  42695. type = "DIRLIGHT" + lightIndex;
  42696. }
  42697. defines[type] = true;
  42698. // Specular
  42699. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42700. specularEnabled = true;
  42701. }
  42702. // Shadows
  42703. defines["SHADOW" + lightIndex] = false;
  42704. defines["SHADOWPCF" + lightIndex] = false;
  42705. defines["SHADOWPCSS" + lightIndex] = false;
  42706. defines["SHADOWPOISSON" + lightIndex] = false;
  42707. defines["SHADOWESM" + lightIndex] = false;
  42708. defines["SHADOWCUBE" + lightIndex] = false;
  42709. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42710. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42711. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42712. var shadowGenerator = light.getShadowGenerator();
  42713. if (shadowGenerator) {
  42714. shadowEnabled = true;
  42715. shadowGenerator.prepareDefines(defines, lightIndex);
  42716. }
  42717. }
  42718. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42719. lightmapMode = true;
  42720. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42721. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42722. }
  42723. else {
  42724. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42725. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42726. }
  42727. lightIndex++;
  42728. if (lightIndex === maxSimultaneousLights)
  42729. break;
  42730. }
  42731. }
  42732. defines["SPECULARTERM"] = specularEnabled;
  42733. defines["SHADOWS"] = shadowEnabled;
  42734. // Resetting all other lights if any
  42735. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42736. if (defines["LIGHT" + index] !== undefined) {
  42737. defines["LIGHT" + index] = false;
  42738. defines["HEMILIGHT" + lightIndex] = false;
  42739. defines["POINTLIGHT" + lightIndex] = false;
  42740. defines["DIRLIGHT" + lightIndex] = false;
  42741. defines["SPOTLIGHT" + lightIndex] = false;
  42742. defines["SHADOW" + lightIndex] = false;
  42743. }
  42744. }
  42745. var caps = scene.getEngine().getCaps();
  42746. if (defines["SHADOWFLOAT"] === undefined) {
  42747. needRebuild = true;
  42748. }
  42749. defines["SHADOWFLOAT"] = shadowEnabled &&
  42750. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42751. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42752. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42753. if (needRebuild) {
  42754. defines.rebuild();
  42755. }
  42756. return needNormals;
  42757. };
  42758. /**
  42759. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42760. * that won t be acctive due to defines being turned off.
  42761. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42762. * @param samplersList The samplers list
  42763. * @param defines The defines helping in the list generation
  42764. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42765. */
  42766. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42767. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42768. var uniformsList;
  42769. var uniformBuffersList = null;
  42770. if (uniformsListOrOptions.uniformsNames) {
  42771. var options = uniformsListOrOptions;
  42772. uniformsList = options.uniformsNames;
  42773. uniformBuffersList = options.uniformBuffersNames;
  42774. samplersList = options.samplers;
  42775. defines = options.defines;
  42776. maxSimultaneousLights = options.maxSimultaneousLights;
  42777. }
  42778. else {
  42779. uniformsList = uniformsListOrOptions;
  42780. if (!samplersList) {
  42781. samplersList = [];
  42782. }
  42783. }
  42784. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42785. if (!defines["LIGHT" + lightIndex]) {
  42786. break;
  42787. }
  42788. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42789. if (uniformBuffersList) {
  42790. uniformBuffersList.push("Light" + lightIndex);
  42791. }
  42792. samplersList.push("shadowSampler" + lightIndex);
  42793. samplersList.push("depthSampler" + lightIndex);
  42794. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42795. samplersList.push("projectionLightSampler" + lightIndex);
  42796. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42797. }
  42798. }
  42799. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42800. uniformsList.push("morphTargetInfluences");
  42801. }
  42802. };
  42803. /**
  42804. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42805. * @param defines The defines to update while falling back
  42806. * @param fallbacks The authorized effect fallbacks
  42807. * @param maxSimultaneousLights The maximum number of lights allowed
  42808. * @param rank the current rank of the Effect
  42809. * @returns The newly affected rank
  42810. */
  42811. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42812. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42813. if (rank === void 0) { rank = 0; }
  42814. var lightFallbackRank = 0;
  42815. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42816. if (!defines["LIGHT" + lightIndex]) {
  42817. break;
  42818. }
  42819. if (lightIndex > 0) {
  42820. lightFallbackRank = rank + lightIndex;
  42821. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42822. }
  42823. if (!defines["SHADOWS"]) {
  42824. if (defines["SHADOW" + lightIndex]) {
  42825. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42826. }
  42827. if (defines["SHADOWPCF" + lightIndex]) {
  42828. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42829. }
  42830. if (defines["SHADOWPCSS" + lightIndex]) {
  42831. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42832. }
  42833. if (defines["SHADOWPOISSON" + lightIndex]) {
  42834. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42835. }
  42836. if (defines["SHADOWESM" + lightIndex]) {
  42837. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42838. }
  42839. }
  42840. }
  42841. return lightFallbackRank++;
  42842. };
  42843. /**
  42844. * Prepares the list of attributes required for morph targets according to the effect defines.
  42845. * @param attribs The current list of supported attribs
  42846. * @param mesh The mesh to prepare the morph targets attributes for
  42847. * @param defines The current Defines of the effect
  42848. */
  42849. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42850. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42851. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42852. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42853. var manager = mesh.morphTargetManager;
  42854. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42855. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42856. for (var index = 0; index < influencers; index++) {
  42857. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42858. if (normal) {
  42859. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42860. }
  42861. if (tangent) {
  42862. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42863. }
  42864. if (attribs.length > maxAttributesCount) {
  42865. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42866. }
  42867. }
  42868. }
  42869. };
  42870. /**
  42871. * Prepares the list of attributes required for bones according to the effect defines.
  42872. * @param attribs The current list of supported attribs
  42873. * @param mesh The mesh to prepare the bones attributes for
  42874. * @param defines The current Defines of the effect
  42875. * @param fallbacks The current efffect fallback strategy
  42876. */
  42877. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42878. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42879. fallbacks.addCPUSkinningFallback(0, mesh);
  42880. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42881. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42882. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42883. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42884. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42885. }
  42886. }
  42887. };
  42888. /**
  42889. * Prepares the list of attributes required for instances according to the effect defines.
  42890. * @param attribs The current list of supported attribs
  42891. * @param defines The current Defines of the effect
  42892. */
  42893. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42894. if (defines["INSTANCES"]) {
  42895. attribs.push("world0");
  42896. attribs.push("world1");
  42897. attribs.push("world2");
  42898. attribs.push("world3");
  42899. }
  42900. };
  42901. /**
  42902. * Binds the light shadow information to the effect for the given mesh.
  42903. * @param light The light containing the generator
  42904. * @param scene The scene the lights belongs to
  42905. * @param mesh The mesh we are binding the information to render
  42906. * @param lightIndex The light index in the effect used to render the mesh
  42907. * @param effect The effect we are binding the data to
  42908. */
  42909. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42910. if (light.shadowEnabled && mesh.receiveShadows) {
  42911. var shadowGenerator = light.getShadowGenerator();
  42912. if (shadowGenerator) {
  42913. shadowGenerator.bindShadowLight(lightIndex, effect);
  42914. }
  42915. }
  42916. };
  42917. /**
  42918. * Binds the light information to the effect.
  42919. * @param light The light containing the generator
  42920. * @param effect The effect we are binding the data to
  42921. * @param lightIndex The light index in the effect used to render
  42922. */
  42923. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42924. light.transferToEffect(effect, lightIndex + "");
  42925. };
  42926. /**
  42927. * Binds the lights information from the scene to the effect for the given mesh.
  42928. * @param scene The scene the lights belongs to
  42929. * @param mesh The mesh we are binding the information to render
  42930. * @param effect The effect we are binding the data to
  42931. * @param defines The generated defines for the effect
  42932. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42933. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42934. */
  42935. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42936. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42937. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42938. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42939. for (var i = 0; i < len; i++) {
  42940. var light = mesh._lightSources[i];
  42941. var iAsString = i.toString();
  42942. var scaledIntensity = light.getScaledIntensity();
  42943. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42944. MaterialHelper.BindLightProperties(light, effect, i);
  42945. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42946. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42947. if (defines["SPECULARTERM"]) {
  42948. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42949. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42950. }
  42951. // Shadows
  42952. if (scene.shadowsEnabled) {
  42953. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42954. }
  42955. light._uniformBuffer.update();
  42956. }
  42957. };
  42958. /**
  42959. * Binds the fog information from the scene to the effect for the given mesh.
  42960. * @param scene The scene the lights belongs to
  42961. * @param mesh The mesh we are binding the information to render
  42962. * @param effect The effect we are binding the data to
  42963. */
  42964. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42965. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42966. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42967. effect.setColor3("vFogColor", scene.fogColor);
  42968. }
  42969. };
  42970. /**
  42971. * Binds the bones information from the mesh to the effect.
  42972. * @param mesh The mesh we are binding the information to render
  42973. * @param effect The effect we are binding the data to
  42974. */
  42975. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42976. if (!effect || !mesh) {
  42977. return;
  42978. }
  42979. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42980. mesh.computeBonesUsingShaders = false;
  42981. }
  42982. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42983. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42984. if (matrices) {
  42985. effect.setMatrices("mBones", matrices);
  42986. }
  42987. }
  42988. };
  42989. /**
  42990. * Binds the morph targets information from the mesh to the effect.
  42991. * @param abstractMesh The mesh we are binding the information to render
  42992. * @param effect The effect we are binding the data to
  42993. */
  42994. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42995. var manager = abstractMesh.morphTargetManager;
  42996. if (!abstractMesh || !manager) {
  42997. return;
  42998. }
  42999. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43000. };
  43001. /**
  43002. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43003. * @param defines The generated defines used in the effect
  43004. * @param effect The effect we are binding the data to
  43005. * @param scene The scene we are willing to render with logarithmic scale for
  43006. */
  43007. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43008. if (defines["LOGARITHMICDEPTH"]) {
  43009. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43010. }
  43011. };
  43012. /**
  43013. * Binds the clip plane information from the scene to the effect.
  43014. * @param scene The scene the clip plane information are extracted from
  43015. * @param effect The effect we are binding the data to
  43016. */
  43017. MaterialHelper.BindClipPlane = function (effect, scene) {
  43018. if (scene.clipPlane) {
  43019. var clipPlane = scene.clipPlane;
  43020. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43021. }
  43022. };
  43023. return MaterialHelper;
  43024. }());
  43025. BABYLON.MaterialHelper = MaterialHelper;
  43026. })(BABYLON || (BABYLON = {}));
  43027. //# sourceMappingURL=babylon.materialHelper.js.map
  43028. var BABYLON;
  43029. (function (BABYLON) {
  43030. var PushMaterial = /** @class */ (function (_super) {
  43031. __extends(PushMaterial, _super);
  43032. function PushMaterial(name, scene) {
  43033. var _this = _super.call(this, name, scene) || this;
  43034. _this._normalMatrix = new BABYLON.Matrix();
  43035. _this.storeEffectOnSubMeshes = true;
  43036. return _this;
  43037. }
  43038. PushMaterial.prototype.getEffect = function () {
  43039. return this._activeEffect;
  43040. };
  43041. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43042. if (!mesh) {
  43043. return false;
  43044. }
  43045. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43046. return true;
  43047. }
  43048. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43049. };
  43050. /**
  43051. * Binds the given world matrix to the active effect
  43052. *
  43053. * @param world the matrix to bind
  43054. */
  43055. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43056. this._activeEffect.setMatrix("world", world);
  43057. };
  43058. /**
  43059. * Binds the given normal matrix to the active effect
  43060. *
  43061. * @param normalMatrix the matrix to bind
  43062. */
  43063. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43064. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43065. };
  43066. PushMaterial.prototype.bind = function (world, mesh) {
  43067. if (!mesh) {
  43068. return;
  43069. }
  43070. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43071. };
  43072. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43073. if (effect === void 0) { effect = null; }
  43074. _super.prototype._afterBind.call(this, mesh);
  43075. this.getScene()._cachedEffect = effect;
  43076. };
  43077. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43078. if (visibility === void 0) { visibility = 1; }
  43079. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43080. };
  43081. return PushMaterial;
  43082. }(BABYLON.Material));
  43083. BABYLON.PushMaterial = PushMaterial;
  43084. })(BABYLON || (BABYLON = {}));
  43085. //# sourceMappingURL=babylon.pushMaterial.js.map
  43086. var BABYLON;
  43087. (function (BABYLON) {
  43088. /** @hidden */
  43089. var StandardMaterialDefines = /** @class */ (function (_super) {
  43090. __extends(StandardMaterialDefines, _super);
  43091. function StandardMaterialDefines() {
  43092. var _this = _super.call(this) || this;
  43093. _this.MAINUV1 = false;
  43094. _this.MAINUV2 = false;
  43095. _this.DIFFUSE = false;
  43096. _this.DIFFUSEDIRECTUV = 0;
  43097. _this.AMBIENT = false;
  43098. _this.AMBIENTDIRECTUV = 0;
  43099. _this.OPACITY = false;
  43100. _this.OPACITYDIRECTUV = 0;
  43101. _this.OPACITYRGB = false;
  43102. _this.REFLECTION = false;
  43103. _this.EMISSIVE = false;
  43104. _this.EMISSIVEDIRECTUV = 0;
  43105. _this.SPECULAR = false;
  43106. _this.SPECULARDIRECTUV = 0;
  43107. _this.BUMP = false;
  43108. _this.BUMPDIRECTUV = 0;
  43109. _this.PARALLAX = false;
  43110. _this.PARALLAXOCCLUSION = false;
  43111. _this.SPECULAROVERALPHA = false;
  43112. _this.CLIPPLANE = false;
  43113. _this.ALPHATEST = false;
  43114. _this.DEPTHPREPASS = false;
  43115. _this.ALPHAFROMDIFFUSE = false;
  43116. _this.POINTSIZE = false;
  43117. _this.FOG = false;
  43118. _this.SPECULARTERM = false;
  43119. _this.DIFFUSEFRESNEL = false;
  43120. _this.OPACITYFRESNEL = false;
  43121. _this.REFLECTIONFRESNEL = false;
  43122. _this.REFRACTIONFRESNEL = false;
  43123. _this.EMISSIVEFRESNEL = false;
  43124. _this.FRESNEL = false;
  43125. _this.NORMAL = false;
  43126. _this.UV1 = false;
  43127. _this.UV2 = false;
  43128. _this.VERTEXCOLOR = false;
  43129. _this.VERTEXALPHA = false;
  43130. _this.NUM_BONE_INFLUENCERS = 0;
  43131. _this.BonesPerMesh = 0;
  43132. _this.INSTANCES = false;
  43133. _this.GLOSSINESS = false;
  43134. _this.ROUGHNESS = false;
  43135. _this.EMISSIVEASILLUMINATION = false;
  43136. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43137. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43138. _this.LIGHTMAP = false;
  43139. _this.LIGHTMAPDIRECTUV = 0;
  43140. _this.OBJECTSPACE_NORMALMAP = false;
  43141. _this.USELIGHTMAPASSHADOWMAP = false;
  43142. _this.REFLECTIONMAP_3D = false;
  43143. _this.REFLECTIONMAP_SPHERICAL = false;
  43144. _this.REFLECTIONMAP_PLANAR = false;
  43145. _this.REFLECTIONMAP_CUBIC = false;
  43146. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43147. _this.REFLECTIONMAP_PROJECTION = false;
  43148. _this.REFLECTIONMAP_SKYBOX = false;
  43149. _this.REFLECTIONMAP_EXPLICIT = false;
  43150. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43151. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43152. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43153. _this.INVERTCUBICMAP = false;
  43154. _this.LOGARITHMICDEPTH = false;
  43155. _this.REFRACTION = false;
  43156. _this.REFRACTIONMAP_3D = false;
  43157. _this.REFLECTIONOVERALPHA = false;
  43158. _this.TWOSIDEDLIGHTING = false;
  43159. _this.SHADOWFLOAT = false;
  43160. _this.MORPHTARGETS = false;
  43161. _this.MORPHTARGETS_NORMAL = false;
  43162. _this.MORPHTARGETS_TANGENT = false;
  43163. _this.NUM_MORPH_INFLUENCERS = 0;
  43164. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43165. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43166. _this.IMAGEPROCESSING = false;
  43167. _this.VIGNETTE = false;
  43168. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43169. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43170. _this.TONEMAPPING = false;
  43171. _this.CONTRAST = false;
  43172. _this.COLORCURVES = false;
  43173. _this.COLORGRADING = false;
  43174. _this.COLORGRADING3D = false;
  43175. _this.SAMPLER3DGREENDEPTH = false;
  43176. _this.SAMPLER3DBGRMAP = false;
  43177. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43178. /**
  43179. * If the reflection texture on this material is in linear color space
  43180. * @hidden
  43181. */
  43182. _this.IS_REFLECTION_LINEAR = false;
  43183. /**
  43184. * If the refraction texture on this material is in linear color space
  43185. * @hidden
  43186. */
  43187. _this.IS_REFRACTION_LINEAR = false;
  43188. _this.EXPOSURE = false;
  43189. _this.rebuild();
  43190. return _this;
  43191. }
  43192. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43193. var modes = [
  43194. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43195. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43196. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43197. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43198. ];
  43199. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43200. var mode = modes_1[_i];
  43201. this[mode] = (mode === modeToEnable);
  43202. }
  43203. };
  43204. return StandardMaterialDefines;
  43205. }(BABYLON.MaterialDefines));
  43206. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43207. var StandardMaterial = /** @class */ (function (_super) {
  43208. __extends(StandardMaterial, _super);
  43209. function StandardMaterial(name, scene) {
  43210. var _this = _super.call(this, name, scene) || this;
  43211. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43212. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43213. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43214. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43215. _this.specularPower = 64;
  43216. _this._useAlphaFromDiffuseTexture = false;
  43217. _this._useEmissiveAsIllumination = false;
  43218. _this._linkEmissiveWithDiffuse = false;
  43219. _this._useSpecularOverAlpha = false;
  43220. _this._useReflectionOverAlpha = false;
  43221. _this._disableLighting = false;
  43222. _this._useObjectSpaceNormalMap = false;
  43223. _this._useParallax = false;
  43224. _this._useParallaxOcclusion = false;
  43225. _this.parallaxScaleBias = 0.05;
  43226. _this._roughness = 0;
  43227. _this.indexOfRefraction = 0.98;
  43228. _this.invertRefractionY = true;
  43229. /**
  43230. * Defines the alpha limits in alpha test mode
  43231. */
  43232. _this.alphaCutOff = 0.4;
  43233. _this._useLightmapAsShadowmap = false;
  43234. _this._useReflectionFresnelFromSpecular = false;
  43235. _this._useGlossinessFromSpecularMapAlpha = false;
  43236. _this._maxSimultaneousLights = 4;
  43237. /**
  43238. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43239. */
  43240. _this._invertNormalMapX = false;
  43241. /**
  43242. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43243. */
  43244. _this._invertNormalMapY = false;
  43245. /**
  43246. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43247. */
  43248. _this._twoSidedLighting = false;
  43249. _this._renderTargets = new BABYLON.SmartArray(16);
  43250. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43251. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43252. // Setup the default processing configuration to the scene.
  43253. _this._attachImageProcessingConfiguration(null);
  43254. _this.getRenderTargetTextures = function () {
  43255. _this._renderTargets.reset();
  43256. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43257. _this._renderTargets.push(_this._reflectionTexture);
  43258. }
  43259. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43260. _this._renderTargets.push(_this._refractionTexture);
  43261. }
  43262. return _this._renderTargets;
  43263. };
  43264. return _this;
  43265. }
  43266. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43267. /**
  43268. * Gets the image processing configuration used either in this material.
  43269. */
  43270. get: function () {
  43271. return this._imageProcessingConfiguration;
  43272. },
  43273. /**
  43274. * Sets the Default image processing configuration used either in the this material.
  43275. *
  43276. * If sets to null, the scene one is in use.
  43277. */
  43278. set: function (value) {
  43279. this._attachImageProcessingConfiguration(value);
  43280. // Ensure the effect will be rebuilt.
  43281. this._markAllSubMeshesAsTexturesDirty();
  43282. },
  43283. enumerable: true,
  43284. configurable: true
  43285. });
  43286. /**
  43287. * Attaches a new image processing configuration to the Standard Material.
  43288. * @param configuration
  43289. */
  43290. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43291. var _this = this;
  43292. if (configuration === this._imageProcessingConfiguration) {
  43293. return;
  43294. }
  43295. // Detaches observer.
  43296. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43297. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43298. }
  43299. // Pick the scene configuration if needed.
  43300. if (!configuration) {
  43301. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43302. }
  43303. else {
  43304. this._imageProcessingConfiguration = configuration;
  43305. }
  43306. // Attaches observer.
  43307. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43308. _this._markAllSubMeshesAsImageProcessingDirty();
  43309. });
  43310. };
  43311. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43312. /**
  43313. * Gets wether the color curves effect is enabled.
  43314. */
  43315. get: function () {
  43316. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43317. },
  43318. /**
  43319. * Sets wether the color curves effect is enabled.
  43320. */
  43321. set: function (value) {
  43322. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43323. },
  43324. enumerable: true,
  43325. configurable: true
  43326. });
  43327. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43328. /**
  43329. * Gets wether the color grading effect is enabled.
  43330. */
  43331. get: function () {
  43332. return this.imageProcessingConfiguration.colorGradingEnabled;
  43333. },
  43334. /**
  43335. * Gets wether the color grading effect is enabled.
  43336. */
  43337. set: function (value) {
  43338. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43339. },
  43340. enumerable: true,
  43341. configurable: true
  43342. });
  43343. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43344. /**
  43345. * Gets wether tonemapping is enabled or not.
  43346. */
  43347. get: function () {
  43348. return this._imageProcessingConfiguration.toneMappingEnabled;
  43349. },
  43350. /**
  43351. * Sets wether tonemapping is enabled or not
  43352. */
  43353. set: function (value) {
  43354. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43355. },
  43356. enumerable: true,
  43357. configurable: true
  43358. });
  43359. ;
  43360. ;
  43361. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43362. /**
  43363. * The camera exposure used on this material.
  43364. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43365. * This corresponds to a photographic exposure.
  43366. */
  43367. get: function () {
  43368. return this._imageProcessingConfiguration.exposure;
  43369. },
  43370. /**
  43371. * The camera exposure used on this material.
  43372. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43373. * This corresponds to a photographic exposure.
  43374. */
  43375. set: function (value) {
  43376. this._imageProcessingConfiguration.exposure = value;
  43377. },
  43378. enumerable: true,
  43379. configurable: true
  43380. });
  43381. ;
  43382. ;
  43383. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43384. /**
  43385. * Gets The camera contrast used on this material.
  43386. */
  43387. get: function () {
  43388. return this._imageProcessingConfiguration.contrast;
  43389. },
  43390. /**
  43391. * Sets The camera contrast used on this material.
  43392. */
  43393. set: function (value) {
  43394. this._imageProcessingConfiguration.contrast = value;
  43395. },
  43396. enumerable: true,
  43397. configurable: true
  43398. });
  43399. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43400. /**
  43401. * Gets the Color Grading 2D Lookup Texture.
  43402. */
  43403. get: function () {
  43404. return this._imageProcessingConfiguration.colorGradingTexture;
  43405. },
  43406. /**
  43407. * Sets the Color Grading 2D Lookup Texture.
  43408. */
  43409. set: function (value) {
  43410. this._imageProcessingConfiguration.colorGradingTexture = value;
  43411. },
  43412. enumerable: true,
  43413. configurable: true
  43414. });
  43415. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43416. /**
  43417. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43418. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43419. * 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;
  43420. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43421. */
  43422. get: function () {
  43423. return this._imageProcessingConfiguration.colorCurves;
  43424. },
  43425. /**
  43426. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43427. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43428. * 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;
  43429. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43430. */
  43431. set: function (value) {
  43432. this._imageProcessingConfiguration.colorCurves = value;
  43433. },
  43434. enumerable: true,
  43435. configurable: true
  43436. });
  43437. StandardMaterial.prototype.getClassName = function () {
  43438. return "StandardMaterial";
  43439. };
  43440. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43441. get: function () {
  43442. return this._useLogarithmicDepth;
  43443. },
  43444. set: function (value) {
  43445. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43446. this._markAllSubMeshesAsMiscDirty();
  43447. },
  43448. enumerable: true,
  43449. configurable: true
  43450. });
  43451. StandardMaterial.prototype.needAlphaBlending = function () {
  43452. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43453. };
  43454. StandardMaterial.prototype.needAlphaTesting = function () {
  43455. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43456. };
  43457. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43458. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43459. };
  43460. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43461. return this._diffuseTexture;
  43462. };
  43463. /**
  43464. * Child classes can use it to update shaders
  43465. */
  43466. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43467. if (useInstances === void 0) { useInstances = false; }
  43468. if (subMesh.effect && this.isFrozen) {
  43469. if (this._wasPreviouslyReady && subMesh.effect) {
  43470. return true;
  43471. }
  43472. }
  43473. if (!subMesh._materialDefines) {
  43474. subMesh._materialDefines = new StandardMaterialDefines();
  43475. }
  43476. var scene = this.getScene();
  43477. var defines = subMesh._materialDefines;
  43478. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43479. if (defines._renderId === scene.getRenderId()) {
  43480. return true;
  43481. }
  43482. }
  43483. var engine = scene.getEngine();
  43484. // Lights
  43485. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43486. // Textures
  43487. if (defines._areTexturesDirty) {
  43488. defines._needUVs = false;
  43489. defines.MAINUV1 = false;
  43490. defines.MAINUV2 = false;
  43491. if (scene.texturesEnabled) {
  43492. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43493. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43494. return false;
  43495. }
  43496. else {
  43497. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43498. }
  43499. }
  43500. else {
  43501. defines.DIFFUSE = false;
  43502. }
  43503. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43504. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43505. return false;
  43506. }
  43507. else {
  43508. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43509. }
  43510. }
  43511. else {
  43512. defines.AMBIENT = false;
  43513. }
  43514. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43515. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43516. return false;
  43517. }
  43518. else {
  43519. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43520. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43521. }
  43522. }
  43523. else {
  43524. defines.OPACITY = false;
  43525. }
  43526. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43527. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43528. return false;
  43529. }
  43530. else {
  43531. defines._needNormals = true;
  43532. defines.REFLECTION = true;
  43533. defines.ROUGHNESS = (this._roughness > 0);
  43534. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43535. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43536. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43537. switch (this._reflectionTexture.coordinatesMode) {
  43538. case BABYLON.Texture.EXPLICIT_MODE:
  43539. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43540. break;
  43541. case BABYLON.Texture.PLANAR_MODE:
  43542. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43543. break;
  43544. case BABYLON.Texture.PROJECTION_MODE:
  43545. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43546. break;
  43547. case BABYLON.Texture.SKYBOX_MODE:
  43548. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43549. break;
  43550. case BABYLON.Texture.SPHERICAL_MODE:
  43551. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43552. break;
  43553. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43554. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43555. break;
  43556. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43557. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43558. break;
  43559. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43560. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43561. break;
  43562. case BABYLON.Texture.CUBIC_MODE:
  43563. case BABYLON.Texture.INVCUBIC_MODE:
  43564. default:
  43565. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43566. break;
  43567. }
  43568. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43569. }
  43570. }
  43571. else {
  43572. defines.REFLECTION = false;
  43573. }
  43574. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43575. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43576. return false;
  43577. }
  43578. else {
  43579. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43580. }
  43581. }
  43582. else {
  43583. defines.EMISSIVE = false;
  43584. }
  43585. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43586. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43587. return false;
  43588. }
  43589. else {
  43590. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43591. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43592. }
  43593. }
  43594. else {
  43595. defines.LIGHTMAP = false;
  43596. }
  43597. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43598. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43599. return false;
  43600. }
  43601. else {
  43602. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43603. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43604. }
  43605. }
  43606. else {
  43607. defines.SPECULAR = false;
  43608. }
  43609. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43610. // Bump texure can not be not blocking.
  43611. if (!this._bumpTexture.isReady()) {
  43612. return false;
  43613. }
  43614. else {
  43615. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43616. defines.PARALLAX = this._useParallax;
  43617. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43618. }
  43619. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43620. }
  43621. else {
  43622. defines.BUMP = false;
  43623. }
  43624. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43625. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43626. return false;
  43627. }
  43628. else {
  43629. defines._needUVs = true;
  43630. defines.REFRACTION = true;
  43631. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43632. }
  43633. }
  43634. else {
  43635. defines.REFRACTION = false;
  43636. }
  43637. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43638. }
  43639. else {
  43640. defines.DIFFUSE = false;
  43641. defines.AMBIENT = false;
  43642. defines.OPACITY = false;
  43643. defines.REFLECTION = false;
  43644. defines.EMISSIVE = false;
  43645. defines.LIGHTMAP = false;
  43646. defines.BUMP = false;
  43647. defines.REFRACTION = false;
  43648. }
  43649. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43650. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43651. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43652. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43653. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43654. }
  43655. if (defines._areImageProcessingDirty) {
  43656. if (!this._imageProcessingConfiguration.isReady()) {
  43657. return false;
  43658. }
  43659. this._imageProcessingConfiguration.prepareDefines(defines);
  43660. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43661. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43662. }
  43663. if (defines._areFresnelDirty) {
  43664. if (StandardMaterial.FresnelEnabled) {
  43665. // Fresnel
  43666. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43667. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43668. this._reflectionFresnelParameters) {
  43669. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43670. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43671. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43672. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43673. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43674. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43675. defines._needNormals = true;
  43676. defines.FRESNEL = true;
  43677. }
  43678. }
  43679. else {
  43680. defines.FRESNEL = false;
  43681. }
  43682. }
  43683. // Misc.
  43684. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43685. // Attribs
  43686. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43687. // Values that need to be evaluated on every frame
  43688. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43689. // Get correct effect
  43690. if (defines.isDirty) {
  43691. defines.markAsProcessed();
  43692. scene.resetCachedMaterial();
  43693. // Fallbacks
  43694. var fallbacks = new BABYLON.EffectFallbacks();
  43695. if (defines.REFLECTION) {
  43696. fallbacks.addFallback(0, "REFLECTION");
  43697. }
  43698. if (defines.SPECULAR) {
  43699. fallbacks.addFallback(0, "SPECULAR");
  43700. }
  43701. if (defines.BUMP) {
  43702. fallbacks.addFallback(0, "BUMP");
  43703. }
  43704. if (defines.PARALLAX) {
  43705. fallbacks.addFallback(1, "PARALLAX");
  43706. }
  43707. if (defines.PARALLAXOCCLUSION) {
  43708. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43709. }
  43710. if (defines.SPECULAROVERALPHA) {
  43711. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43712. }
  43713. if (defines.FOG) {
  43714. fallbacks.addFallback(1, "FOG");
  43715. }
  43716. if (defines.POINTSIZE) {
  43717. fallbacks.addFallback(0, "POINTSIZE");
  43718. }
  43719. if (defines.LOGARITHMICDEPTH) {
  43720. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43721. }
  43722. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43723. if (defines.SPECULARTERM) {
  43724. fallbacks.addFallback(0, "SPECULARTERM");
  43725. }
  43726. if (defines.DIFFUSEFRESNEL) {
  43727. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43728. }
  43729. if (defines.OPACITYFRESNEL) {
  43730. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43731. }
  43732. if (defines.REFLECTIONFRESNEL) {
  43733. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43734. }
  43735. if (defines.EMISSIVEFRESNEL) {
  43736. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43737. }
  43738. if (defines.FRESNEL) {
  43739. fallbacks.addFallback(4, "FRESNEL");
  43740. }
  43741. //Attributes
  43742. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43743. if (defines.NORMAL) {
  43744. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43745. }
  43746. if (defines.UV1) {
  43747. attribs.push(BABYLON.VertexBuffer.UVKind);
  43748. }
  43749. if (defines.UV2) {
  43750. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43751. }
  43752. if (defines.VERTEXCOLOR) {
  43753. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43754. }
  43755. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43756. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43757. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43758. var shaderName = "default";
  43759. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43760. "vFogInfos", "vFogColor", "pointSize",
  43761. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43762. "mBones",
  43763. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43764. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43765. "vReflectionPosition", "vReflectionSize",
  43766. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43767. ];
  43768. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43769. var uniformBuffers = ["Material", "Scene"];
  43770. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43771. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43772. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43773. uniformsNames: uniforms,
  43774. uniformBuffersNames: uniformBuffers,
  43775. samplers: samplers,
  43776. defines: defines,
  43777. maxSimultaneousLights: this._maxSimultaneousLights
  43778. });
  43779. if (this.customShaderNameResolve) {
  43780. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43781. }
  43782. var join = defines.toString();
  43783. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43784. attributes: attribs,
  43785. uniformsNames: uniforms,
  43786. uniformBuffersNames: uniformBuffers,
  43787. samplers: samplers,
  43788. defines: join,
  43789. fallbacks: fallbacks,
  43790. onCompiled: this.onCompiled,
  43791. onError: this.onError,
  43792. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43793. }, engine), defines);
  43794. this.buildUniformLayout();
  43795. }
  43796. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43797. return false;
  43798. }
  43799. defines._renderId = scene.getRenderId();
  43800. this._wasPreviouslyReady = true;
  43801. return true;
  43802. };
  43803. StandardMaterial.prototype.buildUniformLayout = function () {
  43804. // Order is important !
  43805. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43806. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43807. this._uniformBuffer.addUniform("opacityParts", 4);
  43808. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43809. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43810. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43811. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43812. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43813. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43814. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43815. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43816. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43817. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43818. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43819. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43820. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43821. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43822. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43823. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43824. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43825. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43826. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43827. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43828. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43829. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43830. this._uniformBuffer.addUniform("specularMatrix", 16);
  43831. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43832. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43833. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43834. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43835. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43836. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43837. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43838. this._uniformBuffer.addUniform("pointSize", 1);
  43839. this._uniformBuffer.create();
  43840. };
  43841. StandardMaterial.prototype.unbind = function () {
  43842. if (this._activeEffect) {
  43843. var needFlag = false;
  43844. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43845. this._activeEffect.setTexture("reflection2DSampler", null);
  43846. needFlag = true;
  43847. }
  43848. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43849. this._activeEffect.setTexture("refraction2DSampler", null);
  43850. needFlag = true;
  43851. }
  43852. if (needFlag) {
  43853. this._markAllSubMeshesAsTexturesDirty();
  43854. }
  43855. }
  43856. _super.prototype.unbind.call(this);
  43857. };
  43858. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43859. var scene = this.getScene();
  43860. var defines = subMesh._materialDefines;
  43861. if (!defines) {
  43862. return;
  43863. }
  43864. var effect = subMesh.effect;
  43865. if (!effect) {
  43866. return;
  43867. }
  43868. this._activeEffect = effect;
  43869. // Matrices
  43870. this.bindOnlyWorldMatrix(world);
  43871. // Normal Matrix
  43872. if (defines.OBJECTSPACE_NORMALMAP) {
  43873. world.toNormalMatrix(this._normalMatrix);
  43874. this.bindOnlyNormalMatrix(this._normalMatrix);
  43875. }
  43876. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43877. // Bones
  43878. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43879. if (mustRebind) {
  43880. this._uniformBuffer.bindToEffect(effect, "Material");
  43881. this.bindViewProjection(effect);
  43882. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43883. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43884. // Fresnel
  43885. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43886. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43887. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43888. }
  43889. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43890. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43891. }
  43892. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43893. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43894. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43895. }
  43896. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43897. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43898. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43899. }
  43900. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43901. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43902. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43903. }
  43904. }
  43905. // Textures
  43906. if (scene.texturesEnabled) {
  43907. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43908. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43909. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43910. if (this._diffuseTexture.hasAlpha) {
  43911. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43912. }
  43913. }
  43914. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43915. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43916. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43917. }
  43918. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43919. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43920. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43921. }
  43922. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43923. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43924. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43925. if (this._reflectionTexture.boundingBoxSize) {
  43926. var cubeTexture = this._reflectionTexture;
  43927. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43928. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43929. }
  43930. }
  43931. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43932. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43933. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43934. }
  43935. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43936. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43937. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43938. }
  43939. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43940. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43941. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43942. }
  43943. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43944. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43945. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43946. if (scene._mirroredCameraPosition) {
  43947. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43948. }
  43949. else {
  43950. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43951. }
  43952. }
  43953. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43954. var depth = 1.0;
  43955. if (!this._refractionTexture.isCube) {
  43956. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43957. if (this._refractionTexture.depth) {
  43958. depth = this._refractionTexture.depth;
  43959. }
  43960. }
  43961. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43962. }
  43963. }
  43964. // Point size
  43965. if (this.pointsCloud) {
  43966. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43967. }
  43968. if (defines.SPECULARTERM) {
  43969. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43970. }
  43971. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43972. // Diffuse
  43973. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43974. }
  43975. // Textures
  43976. if (scene.texturesEnabled) {
  43977. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43978. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43979. }
  43980. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43981. effect.setTexture("ambientSampler", this._ambientTexture);
  43982. }
  43983. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43984. effect.setTexture("opacitySampler", this._opacityTexture);
  43985. }
  43986. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43987. if (this._reflectionTexture.isCube) {
  43988. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43989. }
  43990. else {
  43991. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43992. }
  43993. }
  43994. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43995. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43996. }
  43997. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43998. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43999. }
  44000. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44001. effect.setTexture("specularSampler", this._specularTexture);
  44002. }
  44003. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44004. effect.setTexture("bumpSampler", this._bumpTexture);
  44005. }
  44006. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44007. var depth = 1.0;
  44008. if (this._refractionTexture.isCube) {
  44009. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44010. }
  44011. else {
  44012. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44013. }
  44014. }
  44015. }
  44016. // Clip plane
  44017. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44018. // Colors
  44019. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44020. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44021. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44022. }
  44023. if (mustRebind || !this.isFrozen) {
  44024. // Lights
  44025. if (scene.lightsEnabled && !this._disableLighting) {
  44026. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44027. }
  44028. // View
  44029. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44030. this.bindView(effect);
  44031. }
  44032. // Fog
  44033. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44034. // Morph targets
  44035. if (defines.NUM_MORPH_INFLUENCERS) {
  44036. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44037. }
  44038. // Log. depth
  44039. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44040. // image processing
  44041. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44042. this._imageProcessingConfiguration.bind(this._activeEffect);
  44043. }
  44044. }
  44045. this._uniformBuffer.update();
  44046. this._afterBind(mesh, this._activeEffect);
  44047. };
  44048. StandardMaterial.prototype.getAnimatables = function () {
  44049. var results = [];
  44050. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44051. results.push(this._diffuseTexture);
  44052. }
  44053. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44054. results.push(this._ambientTexture);
  44055. }
  44056. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44057. results.push(this._opacityTexture);
  44058. }
  44059. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44060. results.push(this._reflectionTexture);
  44061. }
  44062. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44063. results.push(this._emissiveTexture);
  44064. }
  44065. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44066. results.push(this._specularTexture);
  44067. }
  44068. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44069. results.push(this._bumpTexture);
  44070. }
  44071. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44072. results.push(this._lightmapTexture);
  44073. }
  44074. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44075. results.push(this._refractionTexture);
  44076. }
  44077. return results;
  44078. };
  44079. StandardMaterial.prototype.getActiveTextures = function () {
  44080. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44081. if (this._diffuseTexture) {
  44082. activeTextures.push(this._diffuseTexture);
  44083. }
  44084. if (this._ambientTexture) {
  44085. activeTextures.push(this._ambientTexture);
  44086. }
  44087. if (this._opacityTexture) {
  44088. activeTextures.push(this._opacityTexture);
  44089. }
  44090. if (this._reflectionTexture) {
  44091. activeTextures.push(this._reflectionTexture);
  44092. }
  44093. if (this._emissiveTexture) {
  44094. activeTextures.push(this._emissiveTexture);
  44095. }
  44096. if (this._specularTexture) {
  44097. activeTextures.push(this._specularTexture);
  44098. }
  44099. if (this._bumpTexture) {
  44100. activeTextures.push(this._bumpTexture);
  44101. }
  44102. if (this._lightmapTexture) {
  44103. activeTextures.push(this._lightmapTexture);
  44104. }
  44105. if (this._refractionTexture) {
  44106. activeTextures.push(this._refractionTexture);
  44107. }
  44108. return activeTextures;
  44109. };
  44110. StandardMaterial.prototype.hasTexture = function (texture) {
  44111. if (_super.prototype.hasTexture.call(this, texture)) {
  44112. return true;
  44113. }
  44114. if (this._diffuseTexture === texture) {
  44115. return true;
  44116. }
  44117. if (this._ambientTexture === texture) {
  44118. return true;
  44119. }
  44120. if (this._opacityTexture === texture) {
  44121. return true;
  44122. }
  44123. if (this._reflectionTexture === texture) {
  44124. return true;
  44125. }
  44126. if (this._emissiveTexture === texture) {
  44127. return true;
  44128. }
  44129. if (this._specularTexture === texture) {
  44130. return true;
  44131. }
  44132. if (this._bumpTexture === texture) {
  44133. return true;
  44134. }
  44135. if (this._lightmapTexture === texture) {
  44136. return true;
  44137. }
  44138. if (this._refractionTexture === texture) {
  44139. return true;
  44140. }
  44141. return false;
  44142. };
  44143. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44144. if (forceDisposeTextures) {
  44145. if (this._diffuseTexture) {
  44146. this._diffuseTexture.dispose();
  44147. }
  44148. if (this._ambientTexture) {
  44149. this._ambientTexture.dispose();
  44150. }
  44151. if (this._opacityTexture) {
  44152. this._opacityTexture.dispose();
  44153. }
  44154. if (this._reflectionTexture) {
  44155. this._reflectionTexture.dispose();
  44156. }
  44157. if (this._emissiveTexture) {
  44158. this._emissiveTexture.dispose();
  44159. }
  44160. if (this._specularTexture) {
  44161. this._specularTexture.dispose();
  44162. }
  44163. if (this._bumpTexture) {
  44164. this._bumpTexture.dispose();
  44165. }
  44166. if (this._lightmapTexture) {
  44167. this._lightmapTexture.dispose();
  44168. }
  44169. if (this._refractionTexture) {
  44170. this._refractionTexture.dispose();
  44171. }
  44172. }
  44173. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44174. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44175. }
  44176. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44177. };
  44178. StandardMaterial.prototype.clone = function (name) {
  44179. var _this = this;
  44180. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44181. result.name = name;
  44182. result.id = name;
  44183. return result;
  44184. };
  44185. StandardMaterial.prototype.serialize = function () {
  44186. return BABYLON.SerializationHelper.Serialize(this);
  44187. };
  44188. // Statics
  44189. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44190. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44191. };
  44192. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44193. get: function () {
  44194. return StandardMaterial._DiffuseTextureEnabled;
  44195. },
  44196. set: function (value) {
  44197. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44198. return;
  44199. }
  44200. StandardMaterial._DiffuseTextureEnabled = value;
  44201. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44202. },
  44203. enumerable: true,
  44204. configurable: true
  44205. });
  44206. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44207. get: function () {
  44208. return StandardMaterial._AmbientTextureEnabled;
  44209. },
  44210. set: function (value) {
  44211. if (StandardMaterial._AmbientTextureEnabled === value) {
  44212. return;
  44213. }
  44214. StandardMaterial._AmbientTextureEnabled = value;
  44215. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44216. },
  44217. enumerable: true,
  44218. configurable: true
  44219. });
  44220. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44221. get: function () {
  44222. return StandardMaterial._OpacityTextureEnabled;
  44223. },
  44224. set: function (value) {
  44225. if (StandardMaterial._OpacityTextureEnabled === value) {
  44226. return;
  44227. }
  44228. StandardMaterial._OpacityTextureEnabled = value;
  44229. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44230. },
  44231. enumerable: true,
  44232. configurable: true
  44233. });
  44234. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44235. get: function () {
  44236. return StandardMaterial._ReflectionTextureEnabled;
  44237. },
  44238. set: function (value) {
  44239. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44240. return;
  44241. }
  44242. StandardMaterial._ReflectionTextureEnabled = value;
  44243. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44244. },
  44245. enumerable: true,
  44246. configurable: true
  44247. });
  44248. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44249. get: function () {
  44250. return StandardMaterial._EmissiveTextureEnabled;
  44251. },
  44252. set: function (value) {
  44253. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44254. return;
  44255. }
  44256. StandardMaterial._EmissiveTextureEnabled = value;
  44257. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44258. },
  44259. enumerable: true,
  44260. configurable: true
  44261. });
  44262. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44263. get: function () {
  44264. return StandardMaterial._SpecularTextureEnabled;
  44265. },
  44266. set: function (value) {
  44267. if (StandardMaterial._SpecularTextureEnabled === value) {
  44268. return;
  44269. }
  44270. StandardMaterial._SpecularTextureEnabled = value;
  44271. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44272. },
  44273. enumerable: true,
  44274. configurable: true
  44275. });
  44276. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44277. get: function () {
  44278. return StandardMaterial._BumpTextureEnabled;
  44279. },
  44280. set: function (value) {
  44281. if (StandardMaterial._BumpTextureEnabled === value) {
  44282. return;
  44283. }
  44284. StandardMaterial._BumpTextureEnabled = value;
  44285. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44286. },
  44287. enumerable: true,
  44288. configurable: true
  44289. });
  44290. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44291. get: function () {
  44292. return StandardMaterial._LightmapTextureEnabled;
  44293. },
  44294. set: function (value) {
  44295. if (StandardMaterial._LightmapTextureEnabled === value) {
  44296. return;
  44297. }
  44298. StandardMaterial._LightmapTextureEnabled = value;
  44299. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44300. },
  44301. enumerable: true,
  44302. configurable: true
  44303. });
  44304. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44305. get: function () {
  44306. return StandardMaterial._RefractionTextureEnabled;
  44307. },
  44308. set: function (value) {
  44309. if (StandardMaterial._RefractionTextureEnabled === value) {
  44310. return;
  44311. }
  44312. StandardMaterial._RefractionTextureEnabled = value;
  44313. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44314. },
  44315. enumerable: true,
  44316. configurable: true
  44317. });
  44318. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44319. get: function () {
  44320. return StandardMaterial._ColorGradingTextureEnabled;
  44321. },
  44322. set: function (value) {
  44323. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44324. return;
  44325. }
  44326. StandardMaterial._ColorGradingTextureEnabled = value;
  44327. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44328. },
  44329. enumerable: true,
  44330. configurable: true
  44331. });
  44332. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44333. get: function () {
  44334. return StandardMaterial._FresnelEnabled;
  44335. },
  44336. set: function (value) {
  44337. if (StandardMaterial._FresnelEnabled === value) {
  44338. return;
  44339. }
  44340. StandardMaterial._FresnelEnabled = value;
  44341. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44342. },
  44343. enumerable: true,
  44344. configurable: true
  44345. });
  44346. // Flags used to enable or disable a type of texture for all Standard Materials
  44347. StandardMaterial._DiffuseTextureEnabled = true;
  44348. StandardMaterial._AmbientTextureEnabled = true;
  44349. StandardMaterial._OpacityTextureEnabled = true;
  44350. StandardMaterial._ReflectionTextureEnabled = true;
  44351. StandardMaterial._EmissiveTextureEnabled = true;
  44352. StandardMaterial._SpecularTextureEnabled = true;
  44353. StandardMaterial._BumpTextureEnabled = true;
  44354. StandardMaterial._LightmapTextureEnabled = true;
  44355. StandardMaterial._RefractionTextureEnabled = true;
  44356. StandardMaterial._ColorGradingTextureEnabled = true;
  44357. StandardMaterial._FresnelEnabled = true;
  44358. __decorate([
  44359. BABYLON.serializeAsTexture("diffuseTexture")
  44360. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44361. __decorate([
  44362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44363. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44364. __decorate([
  44365. BABYLON.serializeAsTexture("ambientTexture")
  44366. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44367. __decorate([
  44368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44369. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44370. __decorate([
  44371. BABYLON.serializeAsTexture("opacityTexture")
  44372. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44373. __decorate([
  44374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44375. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44376. __decorate([
  44377. BABYLON.serializeAsTexture("reflectionTexture")
  44378. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44379. __decorate([
  44380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44381. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44382. __decorate([
  44383. BABYLON.serializeAsTexture("emissiveTexture")
  44384. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44385. __decorate([
  44386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44387. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44388. __decorate([
  44389. BABYLON.serializeAsTexture("specularTexture")
  44390. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44391. __decorate([
  44392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44393. ], StandardMaterial.prototype, "specularTexture", void 0);
  44394. __decorate([
  44395. BABYLON.serializeAsTexture("bumpTexture")
  44396. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44397. __decorate([
  44398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44399. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44400. __decorate([
  44401. BABYLON.serializeAsTexture("lightmapTexture")
  44402. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44403. __decorate([
  44404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44405. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44406. __decorate([
  44407. BABYLON.serializeAsTexture("refractionTexture")
  44408. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44409. __decorate([
  44410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44411. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44412. __decorate([
  44413. BABYLON.serializeAsColor3("ambient")
  44414. ], StandardMaterial.prototype, "ambientColor", void 0);
  44415. __decorate([
  44416. BABYLON.serializeAsColor3("diffuse")
  44417. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44418. __decorate([
  44419. BABYLON.serializeAsColor3("specular")
  44420. ], StandardMaterial.prototype, "specularColor", void 0);
  44421. __decorate([
  44422. BABYLON.serializeAsColor3("emissive")
  44423. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44424. __decorate([
  44425. BABYLON.serialize()
  44426. ], StandardMaterial.prototype, "specularPower", void 0);
  44427. __decorate([
  44428. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44429. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44430. __decorate([
  44431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44432. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44433. __decorate([
  44434. BABYLON.serialize("useEmissiveAsIllumination")
  44435. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44436. __decorate([
  44437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44438. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44439. __decorate([
  44440. BABYLON.serialize("linkEmissiveWithDiffuse")
  44441. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44442. __decorate([
  44443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44444. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44445. __decorate([
  44446. BABYLON.serialize("useSpecularOverAlpha")
  44447. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44448. __decorate([
  44449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44450. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44451. __decorate([
  44452. BABYLON.serialize("useReflectionOverAlpha")
  44453. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44454. __decorate([
  44455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44456. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44457. __decorate([
  44458. BABYLON.serialize("disableLighting")
  44459. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44460. __decorate([
  44461. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44462. ], StandardMaterial.prototype, "disableLighting", void 0);
  44463. __decorate([
  44464. BABYLON.serialize("useObjectSpaceNormalMap")
  44465. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44466. __decorate([
  44467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44468. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44469. __decorate([
  44470. BABYLON.serialize("useParallax")
  44471. ], StandardMaterial.prototype, "_useParallax", void 0);
  44472. __decorate([
  44473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44474. ], StandardMaterial.prototype, "useParallax", void 0);
  44475. __decorate([
  44476. BABYLON.serialize("useParallaxOcclusion")
  44477. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44478. __decorate([
  44479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44480. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44481. __decorate([
  44482. BABYLON.serialize()
  44483. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44484. __decorate([
  44485. BABYLON.serialize("roughness")
  44486. ], StandardMaterial.prototype, "_roughness", void 0);
  44487. __decorate([
  44488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44489. ], StandardMaterial.prototype, "roughness", void 0);
  44490. __decorate([
  44491. BABYLON.serialize()
  44492. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44493. __decorate([
  44494. BABYLON.serialize()
  44495. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44496. __decorate([
  44497. BABYLON.serialize()
  44498. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44499. __decorate([
  44500. BABYLON.serialize("useLightmapAsShadowmap")
  44501. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44502. __decorate([
  44503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44504. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44505. __decorate([
  44506. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44507. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44508. __decorate([
  44509. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44510. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44511. __decorate([
  44512. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44513. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44514. __decorate([
  44515. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44516. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44517. __decorate([
  44518. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44519. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44520. __decorate([
  44521. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44522. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44523. __decorate([
  44524. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44525. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44526. __decorate([
  44527. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44528. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44529. __decorate([
  44530. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44531. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44532. __decorate([
  44533. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44534. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44535. __decorate([
  44536. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44537. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44538. __decorate([
  44539. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44540. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44541. __decorate([
  44542. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44543. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44544. __decorate([
  44545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44546. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44547. __decorate([
  44548. BABYLON.serialize("maxSimultaneousLights")
  44549. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44550. __decorate([
  44551. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44552. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44553. __decorate([
  44554. BABYLON.serialize("invertNormalMapX")
  44555. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44556. __decorate([
  44557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44558. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44559. __decorate([
  44560. BABYLON.serialize("invertNormalMapY")
  44561. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44562. __decorate([
  44563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44564. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44565. __decorate([
  44566. BABYLON.serialize("twoSidedLighting")
  44567. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44568. __decorate([
  44569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44570. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44571. __decorate([
  44572. BABYLON.serialize()
  44573. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44574. return StandardMaterial;
  44575. }(BABYLON.PushMaterial));
  44576. BABYLON.StandardMaterial = StandardMaterial;
  44577. })(BABYLON || (BABYLON = {}));
  44578. //# sourceMappingURL=babylon.standardMaterial.js.map
  44579. var BABYLON;
  44580. (function (BABYLON) {
  44581. /**
  44582. * Manages the defines for the PBR Material.
  44583. * @hiddenChildren
  44584. */
  44585. var PBRMaterialDefines = /** @class */ (function (_super) {
  44586. __extends(PBRMaterialDefines, _super);
  44587. /**
  44588. * Initializes the PBR Material defines.
  44589. */
  44590. function PBRMaterialDefines() {
  44591. var _this = _super.call(this) || this;
  44592. _this.PBR = true;
  44593. _this.MAINUV1 = false;
  44594. _this.MAINUV2 = false;
  44595. _this.UV1 = false;
  44596. _this.UV2 = false;
  44597. _this.ALBEDO = false;
  44598. _this.ALBEDODIRECTUV = 0;
  44599. _this.VERTEXCOLOR = false;
  44600. _this.AMBIENT = false;
  44601. _this.AMBIENTDIRECTUV = 0;
  44602. _this.AMBIENTINGRAYSCALE = false;
  44603. _this.OPACITY = false;
  44604. _this.VERTEXALPHA = false;
  44605. _this.OPACITYDIRECTUV = 0;
  44606. _this.OPACITYRGB = false;
  44607. _this.ALPHATEST = false;
  44608. _this.DEPTHPREPASS = false;
  44609. _this.ALPHABLEND = false;
  44610. _this.ALPHAFROMALBEDO = false;
  44611. _this.ALPHATESTVALUE = "0.5";
  44612. _this.SPECULAROVERALPHA = false;
  44613. _this.RADIANCEOVERALPHA = false;
  44614. _this.ALPHAFRESNEL = false;
  44615. _this.LINEARALPHAFRESNEL = false;
  44616. _this.PREMULTIPLYALPHA = false;
  44617. _this.EMISSIVE = false;
  44618. _this.EMISSIVEDIRECTUV = 0;
  44619. _this.REFLECTIVITY = false;
  44620. _this.REFLECTIVITYDIRECTUV = 0;
  44621. _this.SPECULARTERM = false;
  44622. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44623. _this.MICROSURFACEAUTOMATIC = false;
  44624. _this.LODBASEDMICROSFURACE = false;
  44625. _this.MICROSURFACEMAP = false;
  44626. _this.MICROSURFACEMAPDIRECTUV = 0;
  44627. _this.METALLICWORKFLOW = false;
  44628. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44629. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44630. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44631. _this.AOSTOREINMETALMAPRED = false;
  44632. _this.ENVIRONMENTBRDF = false;
  44633. _this.NORMAL = false;
  44634. _this.TANGENT = false;
  44635. _this.BUMP = false;
  44636. _this.BUMPDIRECTUV = 0;
  44637. _this.OBJECTSPACE_NORMALMAP = false;
  44638. _this.PARALLAX = false;
  44639. _this.PARALLAXOCCLUSION = false;
  44640. _this.NORMALXYSCALE = true;
  44641. _this.LIGHTMAP = false;
  44642. _this.LIGHTMAPDIRECTUV = 0;
  44643. _this.USELIGHTMAPASSHADOWMAP = false;
  44644. _this.GAMMALIGHTMAP = false;
  44645. _this.REFLECTION = false;
  44646. _this.REFLECTIONMAP_3D = false;
  44647. _this.REFLECTIONMAP_SPHERICAL = false;
  44648. _this.REFLECTIONMAP_PLANAR = false;
  44649. _this.REFLECTIONMAP_CUBIC = false;
  44650. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44651. _this.REFLECTIONMAP_PROJECTION = false;
  44652. _this.REFLECTIONMAP_SKYBOX = false;
  44653. _this.REFLECTIONMAP_EXPLICIT = false;
  44654. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44655. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44656. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44657. _this.INVERTCUBICMAP = false;
  44658. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44659. _this.USESPHERICALINVERTEX = false;
  44660. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44661. _this.LODINREFLECTIONALPHA = false;
  44662. _this.GAMMAREFLECTION = false;
  44663. _this.RADIANCEOCCLUSION = false;
  44664. _this.HORIZONOCCLUSION = false;
  44665. _this.REFRACTION = false;
  44666. _this.REFRACTIONMAP_3D = false;
  44667. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44668. _this.LODINREFRACTIONALPHA = false;
  44669. _this.GAMMAREFRACTION = false;
  44670. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44671. _this.INSTANCES = false;
  44672. _this.NUM_BONE_INFLUENCERS = 0;
  44673. _this.BonesPerMesh = 0;
  44674. _this.NONUNIFORMSCALING = false;
  44675. _this.MORPHTARGETS = false;
  44676. _this.MORPHTARGETS_NORMAL = false;
  44677. _this.MORPHTARGETS_TANGENT = false;
  44678. _this.NUM_MORPH_INFLUENCERS = 0;
  44679. _this.IMAGEPROCESSING = false;
  44680. _this.VIGNETTE = false;
  44681. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44682. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44683. _this.TONEMAPPING = false;
  44684. _this.CONTRAST = false;
  44685. _this.COLORCURVES = false;
  44686. _this.COLORGRADING = false;
  44687. _this.COLORGRADING3D = false;
  44688. _this.SAMPLER3DGREENDEPTH = false;
  44689. _this.SAMPLER3DBGRMAP = false;
  44690. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44691. _this.EXPOSURE = false;
  44692. _this.USEPHYSICALLIGHTFALLOFF = false;
  44693. _this.TWOSIDEDLIGHTING = false;
  44694. _this.SHADOWFLOAT = false;
  44695. _this.CLIPPLANE = false;
  44696. _this.POINTSIZE = false;
  44697. _this.FOG = false;
  44698. _this.LOGARITHMICDEPTH = false;
  44699. _this.FORCENORMALFORWARD = false;
  44700. _this.SPECULARAA = false;
  44701. _this.UNLIT = false;
  44702. _this.rebuild();
  44703. return _this;
  44704. }
  44705. /**
  44706. * Resets the PBR Material defines.
  44707. */
  44708. PBRMaterialDefines.prototype.reset = function () {
  44709. _super.prototype.reset.call(this);
  44710. this.ALPHATESTVALUE = "0.5";
  44711. this.PBR = true;
  44712. };
  44713. return PBRMaterialDefines;
  44714. }(BABYLON.MaterialDefines));
  44715. /**
  44716. * The Physically based material base class of BJS.
  44717. *
  44718. * This offers the main features of a standard PBR material.
  44719. * For more information, please refer to the documentation :
  44720. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44721. */
  44722. var PBRBaseMaterial = /** @class */ (function (_super) {
  44723. __extends(PBRBaseMaterial, _super);
  44724. /**
  44725. * Instantiates a new PBRMaterial instance.
  44726. *
  44727. * @param name The material name
  44728. * @param scene The scene the material will be use in.
  44729. */
  44730. function PBRBaseMaterial(name, scene) {
  44731. var _this = _super.call(this, name, scene) || this;
  44732. /**
  44733. * Intensity of the direct lights e.g. the four lights available in your scene.
  44734. * This impacts both the direct diffuse and specular highlights.
  44735. */
  44736. _this._directIntensity = 1.0;
  44737. /**
  44738. * Intensity of the emissive part of the material.
  44739. * This helps controlling the emissive effect without modifying the emissive color.
  44740. */
  44741. _this._emissiveIntensity = 1.0;
  44742. /**
  44743. * Intensity of the environment e.g. how much the environment will light the object
  44744. * either through harmonics for rough material or through the refelction for shiny ones.
  44745. */
  44746. _this._environmentIntensity = 1.0;
  44747. /**
  44748. * This is a special control allowing the reduction of the specular highlights coming from the
  44749. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44750. */
  44751. _this._specularIntensity = 1.0;
  44752. /**
  44753. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44754. */
  44755. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44756. /**
  44757. * Debug Control allowing disabling the bump map on this material.
  44758. */
  44759. _this._disableBumpMap = false;
  44760. /**
  44761. * AKA Occlusion Texture Intensity in other nomenclature.
  44762. */
  44763. _this._ambientTextureStrength = 1.0;
  44764. /**
  44765. * The color of a material in ambient lighting.
  44766. */
  44767. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44768. /**
  44769. * AKA Diffuse Color in other nomenclature.
  44770. */
  44771. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44772. /**
  44773. * AKA Specular Color in other nomenclature.
  44774. */
  44775. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44776. /**
  44777. * The color applied when light is reflected from a material.
  44778. */
  44779. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44780. /**
  44781. * The color applied when light is emitted from a material.
  44782. */
  44783. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44784. /**
  44785. * AKA Glossiness in other nomenclature.
  44786. */
  44787. _this._microSurface = 0.9;
  44788. /**
  44789. * source material index of refraction (IOR)' / 'destination material IOR.
  44790. */
  44791. _this._indexOfRefraction = 0.66;
  44792. /**
  44793. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44794. */
  44795. _this._invertRefractionY = false;
  44796. /**
  44797. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44798. * Materials half opaque for instance using refraction could benefit from this control.
  44799. */
  44800. _this._linkRefractionWithTransparency = false;
  44801. /**
  44802. * Specifies that the material will use the light map as a show map.
  44803. */
  44804. _this._useLightmapAsShadowmap = false;
  44805. /**
  44806. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44807. * makes the reflect vector face the model (under horizon).
  44808. */
  44809. _this._useHorizonOcclusion = true;
  44810. /**
  44811. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44812. * too much the area relying on ambient texture to define their ambient occlusion.
  44813. */
  44814. _this._useRadianceOcclusion = true;
  44815. /**
  44816. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44817. */
  44818. _this._useAlphaFromAlbedoTexture = false;
  44819. /**
  44820. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44821. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44822. */
  44823. _this._useSpecularOverAlpha = true;
  44824. /**
  44825. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44826. */
  44827. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44828. /**
  44829. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44830. */
  44831. _this._useRoughnessFromMetallicTextureAlpha = true;
  44832. /**
  44833. * Specifies if the metallic texture contains the roughness information in its green channel.
  44834. */
  44835. _this._useRoughnessFromMetallicTextureGreen = false;
  44836. /**
  44837. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44838. */
  44839. _this._useMetallnessFromMetallicTextureBlue = false;
  44840. /**
  44841. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44842. */
  44843. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44844. /**
  44845. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44846. */
  44847. _this._useAmbientInGrayScale = false;
  44848. /**
  44849. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44850. * The material will try to infer what glossiness each pixel should be.
  44851. */
  44852. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44853. /**
  44854. * BJS is using an harcoded light falloff based on a manually sets up range.
  44855. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44856. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44857. */
  44858. _this._usePhysicalLightFalloff = true;
  44859. /**
  44860. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44861. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44862. */
  44863. _this._useRadianceOverAlpha = true;
  44864. /**
  44865. * Allows using an object space normal map (instead of tangent space).
  44866. */
  44867. _this._useObjectSpaceNormalMap = false;
  44868. /**
  44869. * Allows using the bump map in parallax mode.
  44870. */
  44871. _this._useParallax = false;
  44872. /**
  44873. * Allows using the bump map in parallax occlusion mode.
  44874. */
  44875. _this._useParallaxOcclusion = false;
  44876. /**
  44877. * Controls the scale bias of the parallax mode.
  44878. */
  44879. _this._parallaxScaleBias = 0.05;
  44880. /**
  44881. * If sets to true, disables all the lights affecting the material.
  44882. */
  44883. _this._disableLighting = false;
  44884. /**
  44885. * Number of Simultaneous lights allowed on the material.
  44886. */
  44887. _this._maxSimultaneousLights = 4;
  44888. /**
  44889. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44890. */
  44891. _this._invertNormalMapX = false;
  44892. /**
  44893. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44894. */
  44895. _this._invertNormalMapY = false;
  44896. /**
  44897. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44898. */
  44899. _this._twoSidedLighting = false;
  44900. /**
  44901. * Defines the alpha limits in alpha test mode.
  44902. */
  44903. _this._alphaCutOff = 0.4;
  44904. /**
  44905. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44906. */
  44907. _this._forceAlphaTest = false;
  44908. /**
  44909. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44910. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44911. */
  44912. _this._useAlphaFresnel = false;
  44913. /**
  44914. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44915. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44916. */
  44917. _this._useLinearAlphaFresnel = false;
  44918. /**
  44919. * The transparency mode of the material.
  44920. */
  44921. _this._transparencyMode = null;
  44922. /**
  44923. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44924. * from cos thetav and roughness:
  44925. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44926. */
  44927. _this._environmentBRDFTexture = null;
  44928. /**
  44929. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44930. */
  44931. _this._forceIrradianceInFragment = false;
  44932. /**
  44933. * Force normal to face away from face.
  44934. */
  44935. _this._forceNormalForward = false;
  44936. /**
  44937. * Enables specular anti aliasing in the PBR shader.
  44938. * It will both interacts on the Geometry for analytical and IBL lighting.
  44939. * It also prefilter the roughness map based on the bump values.
  44940. */
  44941. _this._enableSpecularAntiAliasing = false;
  44942. /**
  44943. * Stores the available render targets.
  44944. */
  44945. _this._renderTargets = new BABYLON.SmartArray(16);
  44946. /**
  44947. * Sets the global ambient color for the material used in lighting calculations.
  44948. */
  44949. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44950. /**
  44951. * If set to true, no lighting calculations will be applied.
  44952. */
  44953. _this._unlit = false;
  44954. // Setup the default processing configuration to the scene.
  44955. _this._attachImageProcessingConfiguration(null);
  44956. _this.getRenderTargetTextures = function () {
  44957. _this._renderTargets.reset();
  44958. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44959. _this._renderTargets.push(_this._reflectionTexture);
  44960. }
  44961. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44962. _this._renderTargets.push(_this._refractionTexture);
  44963. }
  44964. return _this._renderTargets;
  44965. };
  44966. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44967. return _this;
  44968. }
  44969. /**
  44970. * Attaches a new image processing configuration to the PBR Material.
  44971. * @param configuration
  44972. */
  44973. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44974. var _this = this;
  44975. if (configuration === this._imageProcessingConfiguration) {
  44976. return;
  44977. }
  44978. // Detaches observer.
  44979. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44980. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44981. }
  44982. // Pick the scene configuration if needed.
  44983. if (!configuration) {
  44984. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44985. }
  44986. else {
  44987. this._imageProcessingConfiguration = configuration;
  44988. }
  44989. // Attaches observer.
  44990. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44991. _this._markAllSubMeshesAsImageProcessingDirty();
  44992. });
  44993. };
  44994. /**
  44995. * Gets the name of the material class.
  44996. */
  44997. PBRBaseMaterial.prototype.getClassName = function () {
  44998. return "PBRBaseMaterial";
  44999. };
  45000. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45001. /**
  45002. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45003. */
  45004. get: function () {
  45005. return this._useLogarithmicDepth;
  45006. },
  45007. /**
  45008. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45009. */
  45010. set: function (value) {
  45011. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45012. },
  45013. enumerable: true,
  45014. configurable: true
  45015. });
  45016. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45017. /**
  45018. * Gets the current transparency mode.
  45019. */
  45020. get: function () {
  45021. return this._transparencyMode;
  45022. },
  45023. /**
  45024. * Sets the transparency mode of the material.
  45025. */
  45026. set: function (value) {
  45027. if (this._transparencyMode === value) {
  45028. return;
  45029. }
  45030. this._transparencyMode = value;
  45031. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45032. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45033. },
  45034. enumerable: true,
  45035. configurable: true
  45036. });
  45037. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45038. /**
  45039. * Returns true if alpha blending should be disabled.
  45040. */
  45041. get: function () {
  45042. return (this._linkRefractionWithTransparency ||
  45043. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45044. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45045. },
  45046. enumerable: true,
  45047. configurable: true
  45048. });
  45049. /**
  45050. * Specifies whether or not this material should be rendered in alpha blend mode.
  45051. */
  45052. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45053. if (this._disableAlphaBlending) {
  45054. return false;
  45055. }
  45056. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45057. };
  45058. /**
  45059. * Specifies if the mesh will require alpha blending.
  45060. * @param mesh - BJS mesh.
  45061. */
  45062. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45063. if (this._disableAlphaBlending) {
  45064. return false;
  45065. }
  45066. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45067. };
  45068. /**
  45069. * Specifies whether or not this material should be rendered in alpha test mode.
  45070. */
  45071. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45072. if (this._forceAlphaTest) {
  45073. return true;
  45074. }
  45075. if (this._linkRefractionWithTransparency) {
  45076. return false;
  45077. }
  45078. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45079. };
  45080. /**
  45081. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45082. */
  45083. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45084. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45085. };
  45086. /**
  45087. * Gets the texture used for the alpha test.
  45088. */
  45089. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45090. return this._albedoTexture;
  45091. };
  45092. /**
  45093. * Specifies that the submesh is ready to be used.
  45094. * @param mesh - BJS mesh.
  45095. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45096. * @param useInstances - Specifies that instances should be used.
  45097. * @returns - boolean indicating that the submesh is ready or not.
  45098. */
  45099. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45100. if (subMesh.effect && this.isFrozen) {
  45101. if (this._wasPreviouslyReady) {
  45102. return true;
  45103. }
  45104. }
  45105. if (!subMesh._materialDefines) {
  45106. subMesh._materialDefines = new PBRMaterialDefines();
  45107. }
  45108. var defines = subMesh._materialDefines;
  45109. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45110. if (defines._renderId === this.getScene().getRenderId()) {
  45111. return true;
  45112. }
  45113. }
  45114. var scene = this.getScene();
  45115. var engine = scene.getEngine();
  45116. if (defines._areTexturesDirty) {
  45117. if (scene.texturesEnabled) {
  45118. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45119. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45120. return false;
  45121. }
  45122. }
  45123. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45124. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45125. return false;
  45126. }
  45127. }
  45128. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45129. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45130. return false;
  45131. }
  45132. }
  45133. var reflectionTexture = this._getReflectionTexture();
  45134. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45135. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45136. return false;
  45137. }
  45138. }
  45139. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45140. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45141. return false;
  45142. }
  45143. }
  45144. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45145. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45146. return false;
  45147. }
  45148. }
  45149. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45150. if (this._metallicTexture) {
  45151. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45152. return false;
  45153. }
  45154. }
  45155. else if (this._reflectivityTexture) {
  45156. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45157. return false;
  45158. }
  45159. }
  45160. if (this._microSurfaceTexture) {
  45161. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45162. return false;
  45163. }
  45164. }
  45165. }
  45166. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45167. // Bump texture cannot be not blocking.
  45168. if (!this._bumpTexture.isReady()) {
  45169. return false;
  45170. }
  45171. }
  45172. var refractionTexture = this._getRefractionTexture();
  45173. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45174. if (!refractionTexture.isReadyOrNotBlocking()) {
  45175. return false;
  45176. }
  45177. }
  45178. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45179. // This is blocking.
  45180. if (!this._environmentBRDFTexture.isReady()) {
  45181. return false;
  45182. }
  45183. }
  45184. }
  45185. }
  45186. if (defines._areImageProcessingDirty) {
  45187. if (!this._imageProcessingConfiguration.isReady()) {
  45188. return false;
  45189. }
  45190. }
  45191. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45192. mesh.createNormals(true);
  45193. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45194. }
  45195. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45196. if (effect) {
  45197. scene.resetCachedMaterial();
  45198. subMesh.setEffect(effect, defines);
  45199. this.buildUniformLayout();
  45200. }
  45201. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45202. return false;
  45203. }
  45204. defines._renderId = scene.getRenderId();
  45205. this._wasPreviouslyReady = true;
  45206. return true;
  45207. };
  45208. /**
  45209. * Specifies if the material uses metallic roughness workflow.
  45210. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45211. */
  45212. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45213. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45214. return true;
  45215. }
  45216. return false;
  45217. };
  45218. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45219. if (onCompiled === void 0) { onCompiled = null; }
  45220. if (onError === void 0) { onError = null; }
  45221. if (useInstances === void 0) { useInstances = null; }
  45222. if (useClipPlane === void 0) { useClipPlane = null; }
  45223. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45224. if (!defines.isDirty) {
  45225. return null;
  45226. }
  45227. defines.markAsProcessed();
  45228. var scene = this.getScene();
  45229. var engine = scene.getEngine();
  45230. // Fallbacks
  45231. var fallbacks = new BABYLON.EffectFallbacks();
  45232. var fallbackRank = 0;
  45233. if (defines.USESPHERICALINVERTEX) {
  45234. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45235. }
  45236. if (defines.FOG) {
  45237. fallbacks.addFallback(fallbackRank, "FOG");
  45238. }
  45239. if (defines.SPECULARAA) {
  45240. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45241. }
  45242. if (defines.POINTSIZE) {
  45243. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45244. }
  45245. if (defines.LOGARITHMICDEPTH) {
  45246. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45247. }
  45248. if (defines.PARALLAX) {
  45249. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45250. }
  45251. if (defines.PARALLAXOCCLUSION) {
  45252. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45253. }
  45254. if (defines.ENVIRONMENTBRDF) {
  45255. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45256. }
  45257. if (defines.TANGENT) {
  45258. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45259. }
  45260. if (defines.BUMP) {
  45261. fallbacks.addFallback(fallbackRank++, "BUMP");
  45262. }
  45263. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45264. if (defines.SPECULARTERM) {
  45265. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45266. }
  45267. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45268. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45269. }
  45270. if (defines.LIGHTMAP) {
  45271. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45272. }
  45273. if (defines.NORMAL) {
  45274. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45275. }
  45276. if (defines.AMBIENT) {
  45277. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45278. }
  45279. if (defines.EMISSIVE) {
  45280. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45281. }
  45282. if (defines.VERTEXCOLOR) {
  45283. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45284. }
  45285. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45286. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45287. }
  45288. if (defines.MORPHTARGETS) {
  45289. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45290. }
  45291. //Attributes
  45292. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45293. if (defines.NORMAL) {
  45294. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45295. }
  45296. if (defines.TANGENT) {
  45297. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45298. }
  45299. if (defines.UV1) {
  45300. attribs.push(BABYLON.VertexBuffer.UVKind);
  45301. }
  45302. if (defines.UV2) {
  45303. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45304. }
  45305. if (defines.VERTEXCOLOR) {
  45306. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45307. }
  45308. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45309. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45310. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45311. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45312. "vFogInfos", "vFogColor", "pointSize",
  45313. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45314. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45315. "mBones",
  45316. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45317. "vLightingIntensity",
  45318. "logarithmicDepthConstant",
  45319. "vSphericalX", "vSphericalY", "vSphericalZ",
  45320. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45321. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45322. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45323. "vTangentSpaceParams"
  45324. ];
  45325. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45326. "bumpSampler", "lightmapSampler", "opacitySampler",
  45327. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45328. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45329. "microSurfaceSampler", "environmentBrdfSampler"];
  45330. var uniformBuffers = ["Material", "Scene"];
  45331. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45332. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45333. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45334. uniformsNames: uniforms,
  45335. uniformBuffersNames: uniformBuffers,
  45336. samplers: samplers,
  45337. defines: defines,
  45338. maxSimultaneousLights: this._maxSimultaneousLights
  45339. });
  45340. var join = defines.toString();
  45341. return engine.createEffect("pbr", {
  45342. attributes: attribs,
  45343. uniformsNames: uniforms,
  45344. uniformBuffersNames: uniformBuffers,
  45345. samplers: samplers,
  45346. defines: join,
  45347. fallbacks: fallbacks,
  45348. onCompiled: onCompiled,
  45349. onError: onError,
  45350. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45351. }, engine);
  45352. };
  45353. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45354. if (useInstances === void 0) { useInstances = null; }
  45355. if (useClipPlane === void 0) { useClipPlane = null; }
  45356. var scene = this.getScene();
  45357. var engine = scene.getEngine();
  45358. // Lights
  45359. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45360. defines._needNormals = true;
  45361. // Textures
  45362. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45363. if (defines._areTexturesDirty) {
  45364. defines._needUVs = false;
  45365. if (scene.texturesEnabled) {
  45366. if (scene.getEngine().getCaps().textureLOD) {
  45367. defines.LODBASEDMICROSFURACE = true;
  45368. }
  45369. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45370. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45371. }
  45372. else {
  45373. defines.ALBEDO = false;
  45374. }
  45375. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45376. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45377. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45378. }
  45379. else {
  45380. defines.AMBIENT = false;
  45381. }
  45382. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45383. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45384. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45385. }
  45386. else {
  45387. defines.OPACITY = false;
  45388. }
  45389. var reflectionTexture = this._getReflectionTexture();
  45390. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45391. defines.REFLECTION = true;
  45392. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45393. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45394. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45395. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45396. defines.INVERTCUBICMAP = true;
  45397. }
  45398. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45399. switch (reflectionTexture.coordinatesMode) {
  45400. case BABYLON.Texture.EXPLICIT_MODE:
  45401. defines.REFLECTIONMAP_EXPLICIT = true;
  45402. break;
  45403. case BABYLON.Texture.PLANAR_MODE:
  45404. defines.REFLECTIONMAP_PLANAR = true;
  45405. break;
  45406. case BABYLON.Texture.PROJECTION_MODE:
  45407. defines.REFLECTIONMAP_PROJECTION = true;
  45408. break;
  45409. case BABYLON.Texture.SKYBOX_MODE:
  45410. defines.REFLECTIONMAP_SKYBOX = true;
  45411. break;
  45412. case BABYLON.Texture.SPHERICAL_MODE:
  45413. defines.REFLECTIONMAP_SPHERICAL = true;
  45414. break;
  45415. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45416. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45417. break;
  45418. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45419. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45420. break;
  45421. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45422. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45423. break;
  45424. case BABYLON.Texture.CUBIC_MODE:
  45425. case BABYLON.Texture.INVCUBIC_MODE:
  45426. default:
  45427. defines.REFLECTIONMAP_CUBIC = true;
  45428. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45429. break;
  45430. }
  45431. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45432. if (reflectionTexture.sphericalPolynomial) {
  45433. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45434. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45435. defines.USESPHERICALINVERTEX = false;
  45436. }
  45437. else {
  45438. defines.USESPHERICALINVERTEX = true;
  45439. }
  45440. }
  45441. }
  45442. }
  45443. else {
  45444. defines.REFLECTION = false;
  45445. defines.REFLECTIONMAP_3D = false;
  45446. defines.REFLECTIONMAP_SPHERICAL = false;
  45447. defines.REFLECTIONMAP_PLANAR = false;
  45448. defines.REFLECTIONMAP_CUBIC = false;
  45449. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45450. defines.REFLECTIONMAP_PROJECTION = false;
  45451. defines.REFLECTIONMAP_SKYBOX = false;
  45452. defines.REFLECTIONMAP_EXPLICIT = false;
  45453. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45454. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45455. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45456. defines.INVERTCUBICMAP = false;
  45457. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45458. defines.USESPHERICALINVERTEX = false;
  45459. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45460. defines.LODINREFLECTIONALPHA = false;
  45461. defines.GAMMAREFLECTION = false;
  45462. }
  45463. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45464. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45465. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45466. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45467. }
  45468. else {
  45469. defines.LIGHTMAP = false;
  45470. }
  45471. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45472. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45473. }
  45474. else {
  45475. defines.EMISSIVE = false;
  45476. }
  45477. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45478. if (this._metallicTexture) {
  45479. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45480. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45481. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45482. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45483. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45484. }
  45485. else if (this._reflectivityTexture) {
  45486. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45487. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45488. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45489. }
  45490. else {
  45491. defines.REFLECTIVITY = false;
  45492. }
  45493. if (this._microSurfaceTexture) {
  45494. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45495. }
  45496. else {
  45497. defines.MICROSURFACEMAP = false;
  45498. }
  45499. }
  45500. else {
  45501. defines.REFLECTIVITY = false;
  45502. defines.MICROSURFACEMAP = false;
  45503. }
  45504. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45505. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45506. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45507. defines.PARALLAX = true;
  45508. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45509. }
  45510. else {
  45511. defines.PARALLAX = false;
  45512. }
  45513. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45514. }
  45515. else {
  45516. defines.BUMP = false;
  45517. }
  45518. var refractionTexture = this._getRefractionTexture();
  45519. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45520. defines.REFRACTION = true;
  45521. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45522. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45523. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45524. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45525. if (this._linkRefractionWithTransparency) {
  45526. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45527. }
  45528. }
  45529. else {
  45530. defines.REFRACTION = false;
  45531. }
  45532. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45533. defines.ENVIRONMENTBRDF = true;
  45534. }
  45535. else {
  45536. defines.ENVIRONMENTBRDF = false;
  45537. }
  45538. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45539. defines.ALPHAFROMALBEDO = true;
  45540. }
  45541. else {
  45542. defines.ALPHAFROMALBEDO = false;
  45543. }
  45544. }
  45545. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45546. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45547. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45548. if (!this.backFaceCulling && this._twoSidedLighting) {
  45549. defines.TWOSIDEDLIGHTING = true;
  45550. }
  45551. else {
  45552. defines.TWOSIDEDLIGHTING = false;
  45553. }
  45554. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45555. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45556. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45557. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45558. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45559. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45560. }
  45561. if (defines._areImageProcessingDirty) {
  45562. this._imageProcessingConfiguration.prepareDefines(defines);
  45563. }
  45564. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45565. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45566. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45567. // Misc.
  45568. if (defines._areMiscDirty) {
  45569. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45570. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45571. }
  45572. // Values that need to be evaluated on every frame
  45573. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45574. // Attribs
  45575. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45576. };
  45577. /**
  45578. * Force shader compilation
  45579. */
  45580. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45581. var _this = this;
  45582. var localOptions = __assign({ clipPlane: false }, options);
  45583. var defines = new PBRMaterialDefines();
  45584. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45585. if (effect.isReady()) {
  45586. if (onCompiled) {
  45587. onCompiled(this);
  45588. }
  45589. }
  45590. else {
  45591. effect.onCompileObservable.add(function () {
  45592. if (onCompiled) {
  45593. onCompiled(_this);
  45594. }
  45595. });
  45596. }
  45597. };
  45598. /**
  45599. * Initializes the uniform buffer layout for the shader.
  45600. */
  45601. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45602. // Order is important !
  45603. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45604. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45605. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45606. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45607. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45608. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45609. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45610. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45611. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45612. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45613. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45614. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45615. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45616. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45617. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45618. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45619. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45620. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45621. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45622. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45623. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45624. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45625. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45626. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45627. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45628. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45629. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45630. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45631. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45632. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45633. this._uniformBuffer.addUniform("pointSize", 1);
  45634. this._uniformBuffer.create();
  45635. };
  45636. /**
  45637. * Unbinds the textures.
  45638. */
  45639. PBRBaseMaterial.prototype.unbind = function () {
  45640. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45641. this._uniformBuffer.setTexture("reflectionSampler", null);
  45642. }
  45643. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45644. this._uniformBuffer.setTexture("refractionSampler", null);
  45645. }
  45646. _super.prototype.unbind.call(this);
  45647. };
  45648. /**
  45649. * Binds the submesh data.
  45650. * @param world - The world matrix.
  45651. * @param mesh - The BJS mesh.
  45652. * @param subMesh - A submesh of the BJS mesh.
  45653. */
  45654. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45655. var scene = this.getScene();
  45656. var defines = subMesh._materialDefines;
  45657. if (!defines) {
  45658. return;
  45659. }
  45660. var effect = subMesh.effect;
  45661. if (!effect) {
  45662. return;
  45663. }
  45664. this._activeEffect = effect;
  45665. // Matrices
  45666. this.bindOnlyWorldMatrix(world);
  45667. // Normal Matrix
  45668. if (defines.OBJECTSPACE_NORMALMAP) {
  45669. world.toNormalMatrix(this._normalMatrix);
  45670. this.bindOnlyNormalMatrix(this._normalMatrix);
  45671. }
  45672. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45673. // Bones
  45674. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45675. var reflectionTexture = null;
  45676. if (mustRebind) {
  45677. this._uniformBuffer.bindToEffect(effect, "Material");
  45678. this.bindViewProjection(effect);
  45679. reflectionTexture = this._getReflectionTexture();
  45680. var refractionTexture = this._getRefractionTexture();
  45681. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45682. // Texture uniforms
  45683. if (scene.texturesEnabled) {
  45684. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45685. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45686. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45687. }
  45688. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45689. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45690. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45691. }
  45692. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45693. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45694. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45695. }
  45696. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45697. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45698. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45699. if (reflectionTexture.boundingBoxSize) {
  45700. var cubeTexture = reflectionTexture;
  45701. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45702. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45703. }
  45704. var polynomials = reflectionTexture.sphericalPolynomial;
  45705. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45706. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45707. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45708. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45709. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45710. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45711. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45712. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45713. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45714. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45715. }
  45716. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45717. }
  45718. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45719. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45720. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45721. }
  45722. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45723. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45724. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45725. }
  45726. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45727. if (this._metallicTexture) {
  45728. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45729. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45730. }
  45731. else if (this._reflectivityTexture) {
  45732. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45733. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45734. }
  45735. if (this._microSurfaceTexture) {
  45736. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45737. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45738. }
  45739. }
  45740. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45741. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45742. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45743. if (scene._mirroredCameraPosition) {
  45744. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45745. }
  45746. else {
  45747. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45748. }
  45749. }
  45750. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45751. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45752. var depth = 1.0;
  45753. if (!refractionTexture.isCube) {
  45754. if (refractionTexture.depth) {
  45755. depth = refractionTexture.depth;
  45756. }
  45757. }
  45758. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45759. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45760. }
  45761. }
  45762. // Point size
  45763. if (this.pointsCloud) {
  45764. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45765. }
  45766. // Colors
  45767. if (defines.METALLICWORKFLOW) {
  45768. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45769. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45770. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45771. }
  45772. else {
  45773. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45774. }
  45775. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45776. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45777. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45778. // Misc
  45779. this._lightingInfos.x = this._directIntensity;
  45780. this._lightingInfos.y = this._emissiveIntensity;
  45781. this._lightingInfos.z = this._environmentIntensity;
  45782. this._lightingInfos.w = this._specularIntensity;
  45783. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45784. }
  45785. // Textures
  45786. if (scene.texturesEnabled) {
  45787. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45788. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45789. }
  45790. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45791. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45792. }
  45793. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45794. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45795. }
  45796. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45797. if (defines.LODBASEDMICROSFURACE) {
  45798. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45799. }
  45800. else {
  45801. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45802. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45803. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45804. }
  45805. }
  45806. if (defines.ENVIRONMENTBRDF) {
  45807. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45808. }
  45809. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45810. if (defines.LODBASEDMICROSFURACE) {
  45811. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45812. }
  45813. else {
  45814. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45815. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45816. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45817. }
  45818. }
  45819. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45820. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45821. }
  45822. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45823. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45824. }
  45825. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45826. if (this._metallicTexture) {
  45827. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45828. }
  45829. else if (this._reflectivityTexture) {
  45830. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45831. }
  45832. if (this._microSurfaceTexture) {
  45833. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45834. }
  45835. }
  45836. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45837. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45838. }
  45839. }
  45840. // Clip plane
  45841. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45842. // Colors
  45843. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45844. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45845. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45846. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45847. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45848. }
  45849. if (mustRebind || !this.isFrozen) {
  45850. // Lights
  45851. if (scene.lightsEnabled && !this._disableLighting) {
  45852. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45853. }
  45854. // View
  45855. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45856. this.bindView(effect);
  45857. }
  45858. // Fog
  45859. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45860. // Morph targets
  45861. if (defines.NUM_MORPH_INFLUENCERS) {
  45862. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45863. }
  45864. // image processing
  45865. this._imageProcessingConfiguration.bind(this._activeEffect);
  45866. // Log. depth
  45867. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45868. }
  45869. this._uniformBuffer.update();
  45870. this._afterBind(mesh, this._activeEffect);
  45871. };
  45872. /**
  45873. * Returns the animatable textures.
  45874. * @returns - Array of animatable textures.
  45875. */
  45876. PBRBaseMaterial.prototype.getAnimatables = function () {
  45877. var results = [];
  45878. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45879. results.push(this._albedoTexture);
  45880. }
  45881. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45882. results.push(this._ambientTexture);
  45883. }
  45884. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45885. results.push(this._opacityTexture);
  45886. }
  45887. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45888. results.push(this._reflectionTexture);
  45889. }
  45890. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45891. results.push(this._emissiveTexture);
  45892. }
  45893. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45894. results.push(this._metallicTexture);
  45895. }
  45896. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45897. results.push(this._reflectivityTexture);
  45898. }
  45899. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45900. results.push(this._bumpTexture);
  45901. }
  45902. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45903. results.push(this._lightmapTexture);
  45904. }
  45905. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45906. results.push(this._refractionTexture);
  45907. }
  45908. return results;
  45909. };
  45910. /**
  45911. * Returns the texture used for reflections.
  45912. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45913. */
  45914. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45915. if (this._reflectionTexture) {
  45916. return this._reflectionTexture;
  45917. }
  45918. return this.getScene().environmentTexture;
  45919. };
  45920. /**
  45921. * Returns the texture used for refraction or null if none is used.
  45922. * @returns - Refection texture if present. If no refraction texture and refraction
  45923. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45924. */
  45925. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45926. if (this._refractionTexture) {
  45927. return this._refractionTexture;
  45928. }
  45929. if (this._linkRefractionWithTransparency) {
  45930. return this.getScene().environmentTexture;
  45931. }
  45932. return null;
  45933. };
  45934. /**
  45935. * Disposes the resources of the material.
  45936. * @param forceDisposeEffect - Forces the disposal of effects.
  45937. * @param forceDisposeTextures - Forces the disposal of all textures.
  45938. */
  45939. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45940. if (forceDisposeTextures) {
  45941. if (this._albedoTexture) {
  45942. this._albedoTexture.dispose();
  45943. }
  45944. if (this._ambientTexture) {
  45945. this._ambientTexture.dispose();
  45946. }
  45947. if (this._opacityTexture) {
  45948. this._opacityTexture.dispose();
  45949. }
  45950. if (this._reflectionTexture) {
  45951. this._reflectionTexture.dispose();
  45952. }
  45953. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45954. this._environmentBRDFTexture.dispose();
  45955. }
  45956. if (this._emissiveTexture) {
  45957. this._emissiveTexture.dispose();
  45958. }
  45959. if (this._metallicTexture) {
  45960. this._metallicTexture.dispose();
  45961. }
  45962. if (this._reflectivityTexture) {
  45963. this._reflectivityTexture.dispose();
  45964. }
  45965. if (this._bumpTexture) {
  45966. this._bumpTexture.dispose();
  45967. }
  45968. if (this._lightmapTexture) {
  45969. this._lightmapTexture.dispose();
  45970. }
  45971. if (this._refractionTexture) {
  45972. this._refractionTexture.dispose();
  45973. }
  45974. }
  45975. this._renderTargets.dispose();
  45976. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45977. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45978. }
  45979. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45980. };
  45981. /**
  45982. * Stores the reflectivity values based on metallic roughness workflow.
  45983. */
  45984. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45985. __decorate([
  45986. BABYLON.serializeAsImageProcessingConfiguration()
  45987. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45988. __decorate([
  45989. BABYLON.serialize()
  45990. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45991. __decorate([
  45992. BABYLON.serialize()
  45993. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45994. return PBRBaseMaterial;
  45995. }(BABYLON.PushMaterial));
  45996. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45997. })(BABYLON || (BABYLON = {}));
  45998. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45999. var BABYLON;
  46000. (function (BABYLON) {
  46001. /**
  46002. * The Physically based simple base material of BJS.
  46003. *
  46004. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46005. * It is used as the base class for both the specGloss and metalRough conventions.
  46006. */
  46007. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46008. __extends(PBRBaseSimpleMaterial, _super);
  46009. /**
  46010. * Instantiates a new PBRMaterial instance.
  46011. *
  46012. * @param name The material name
  46013. * @param scene The scene the material will be use in.
  46014. */
  46015. function PBRBaseSimpleMaterial(name, scene) {
  46016. var _this = _super.call(this, name, scene) || this;
  46017. /**
  46018. * Number of Simultaneous lights allowed on the material.
  46019. */
  46020. _this.maxSimultaneousLights = 4;
  46021. /**
  46022. * If sets to true, disables all the lights affecting the material.
  46023. */
  46024. _this.disableLighting = false;
  46025. /**
  46026. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46027. */
  46028. _this.invertNormalMapX = false;
  46029. /**
  46030. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46031. */
  46032. _this.invertNormalMapY = false;
  46033. /**
  46034. * Emissivie color used to self-illuminate the model.
  46035. */
  46036. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46037. /**
  46038. * Occlusion Channel Strenght.
  46039. */
  46040. _this.occlusionStrength = 1.0;
  46041. _this.useLightmapAsShadowmap = false;
  46042. _this._useAlphaFromAlbedoTexture = true;
  46043. _this._useAmbientInGrayScale = true;
  46044. return _this;
  46045. }
  46046. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46047. /**
  46048. * Gets the current double sided mode.
  46049. */
  46050. get: function () {
  46051. return this._twoSidedLighting;
  46052. },
  46053. /**
  46054. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46055. */
  46056. set: function (value) {
  46057. if (this._twoSidedLighting === value) {
  46058. return;
  46059. }
  46060. this._twoSidedLighting = value;
  46061. this.backFaceCulling = !value;
  46062. this._markAllSubMeshesAsTexturesDirty();
  46063. },
  46064. enumerable: true,
  46065. configurable: true
  46066. });
  46067. /**
  46068. * Return the active textures of the material.
  46069. */
  46070. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46071. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46072. if (this.environmentTexture) {
  46073. activeTextures.push(this.environmentTexture);
  46074. }
  46075. if (this.normalTexture) {
  46076. activeTextures.push(this.normalTexture);
  46077. }
  46078. if (this.emissiveTexture) {
  46079. activeTextures.push(this.emissiveTexture);
  46080. }
  46081. if (this.occlusionTexture) {
  46082. activeTextures.push(this.occlusionTexture);
  46083. }
  46084. if (this.lightmapTexture) {
  46085. activeTextures.push(this.lightmapTexture);
  46086. }
  46087. return activeTextures;
  46088. };
  46089. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46090. if (_super.prototype.hasTexture.call(this, texture)) {
  46091. return true;
  46092. }
  46093. if (this.lightmapTexture === texture) {
  46094. return true;
  46095. }
  46096. return false;
  46097. };
  46098. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46099. return "PBRBaseSimpleMaterial";
  46100. };
  46101. __decorate([
  46102. BABYLON.serialize(),
  46103. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46104. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46105. __decorate([
  46106. BABYLON.serialize(),
  46107. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46108. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46109. __decorate([
  46110. BABYLON.serializeAsTexture(),
  46111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46112. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46113. __decorate([
  46114. BABYLON.serialize(),
  46115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46116. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46117. __decorate([
  46118. BABYLON.serialize(),
  46119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46120. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46121. __decorate([
  46122. BABYLON.serializeAsTexture(),
  46123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46124. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46125. __decorate([
  46126. BABYLON.serializeAsColor3("emissive"),
  46127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46128. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46129. __decorate([
  46130. BABYLON.serializeAsTexture(),
  46131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46132. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46133. __decorate([
  46134. BABYLON.serialize(),
  46135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46136. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46137. __decorate([
  46138. BABYLON.serializeAsTexture(),
  46139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46140. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46141. __decorate([
  46142. BABYLON.serialize(),
  46143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46144. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46145. __decorate([
  46146. BABYLON.serialize()
  46147. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46148. __decorate([
  46149. BABYLON.serializeAsTexture(),
  46150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46151. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46152. __decorate([
  46153. BABYLON.serialize(),
  46154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46155. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46156. return PBRBaseSimpleMaterial;
  46157. }(BABYLON.PBRBaseMaterial));
  46158. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46159. })(BABYLON || (BABYLON = {}));
  46160. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46161. var BABYLON;
  46162. (function (BABYLON) {
  46163. /**
  46164. * The Physically based material of BJS.
  46165. *
  46166. * This offers the main features of a standard PBR material.
  46167. * For more information, please refer to the documentation :
  46168. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46169. */
  46170. var PBRMaterial = /** @class */ (function (_super) {
  46171. __extends(PBRMaterial, _super);
  46172. /**
  46173. * Instantiates a new PBRMaterial instance.
  46174. *
  46175. * @param name The material name
  46176. * @param scene The scene the material will be use in.
  46177. */
  46178. function PBRMaterial(name, scene) {
  46179. var _this = _super.call(this, name, scene) || this;
  46180. /**
  46181. * Intensity of the direct lights e.g. the four lights available in your scene.
  46182. * This impacts both the direct diffuse and specular highlights.
  46183. */
  46184. _this.directIntensity = 1.0;
  46185. /**
  46186. * Intensity of the emissive part of the material.
  46187. * This helps controlling the emissive effect without modifying the emissive color.
  46188. */
  46189. _this.emissiveIntensity = 1.0;
  46190. /**
  46191. * Intensity of the environment e.g. how much the environment will light the object
  46192. * either through harmonics for rough material or through the refelction for shiny ones.
  46193. */
  46194. _this.environmentIntensity = 1.0;
  46195. /**
  46196. * This is a special control allowing the reduction of the specular highlights coming from the
  46197. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46198. */
  46199. _this.specularIntensity = 1.0;
  46200. /**
  46201. * Debug Control allowing disabling the bump map on this material.
  46202. */
  46203. _this.disableBumpMap = false;
  46204. /**
  46205. * AKA Occlusion Texture Intensity in other nomenclature.
  46206. */
  46207. _this.ambientTextureStrength = 1.0;
  46208. /**
  46209. * The color of a material in ambient lighting.
  46210. */
  46211. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46212. /**
  46213. * AKA Diffuse Color in other nomenclature.
  46214. */
  46215. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46216. /**
  46217. * AKA Specular Color in other nomenclature.
  46218. */
  46219. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46220. /**
  46221. * The color reflected from the material.
  46222. */
  46223. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46224. /**
  46225. * The color emitted from the material.
  46226. */
  46227. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46228. /**
  46229. * AKA Glossiness in other nomenclature.
  46230. */
  46231. _this.microSurface = 1.0;
  46232. /**
  46233. * source material index of refraction (IOR)' / 'destination material IOR.
  46234. */
  46235. _this.indexOfRefraction = 0.66;
  46236. /**
  46237. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46238. */
  46239. _this.invertRefractionY = false;
  46240. /**
  46241. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46242. * Materials half opaque for instance using refraction could benefit from this control.
  46243. */
  46244. _this.linkRefractionWithTransparency = false;
  46245. _this.useLightmapAsShadowmap = false;
  46246. /**
  46247. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46248. */
  46249. _this.useAlphaFromAlbedoTexture = false;
  46250. /**
  46251. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46252. */
  46253. _this.forceAlphaTest = false;
  46254. /**
  46255. * Defines the alpha limits in alpha test mode.
  46256. */
  46257. _this.alphaCutOff = 0.4;
  46258. /**
  46259. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46260. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46261. */
  46262. _this.useSpecularOverAlpha = true;
  46263. /**
  46264. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46265. */
  46266. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46267. /**
  46268. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46269. */
  46270. _this.useRoughnessFromMetallicTextureAlpha = true;
  46271. /**
  46272. * Specifies if the metallic texture contains the roughness information in its green channel.
  46273. */
  46274. _this.useRoughnessFromMetallicTextureGreen = false;
  46275. /**
  46276. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46277. */
  46278. _this.useMetallnessFromMetallicTextureBlue = false;
  46279. /**
  46280. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46281. */
  46282. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46283. /**
  46284. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46285. */
  46286. _this.useAmbientInGrayScale = false;
  46287. /**
  46288. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46289. * The material will try to infer what glossiness each pixel should be.
  46290. */
  46291. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46292. /**
  46293. * BJS is using an harcoded light falloff based on a manually sets up range.
  46294. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46295. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46296. */
  46297. _this.usePhysicalLightFalloff = true;
  46298. /**
  46299. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46300. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46301. */
  46302. _this.useRadianceOverAlpha = true;
  46303. /**
  46304. * Allows using an object space normal map (instead of tangent space).
  46305. */
  46306. _this.useObjectSpaceNormalMap = false;
  46307. /**
  46308. * Allows using the bump map in parallax mode.
  46309. */
  46310. _this.useParallax = false;
  46311. /**
  46312. * Allows using the bump map in parallax occlusion mode.
  46313. */
  46314. _this.useParallaxOcclusion = false;
  46315. /**
  46316. * Controls the scale bias of the parallax mode.
  46317. */
  46318. _this.parallaxScaleBias = 0.05;
  46319. /**
  46320. * If sets to true, disables all the lights affecting the material.
  46321. */
  46322. _this.disableLighting = false;
  46323. /**
  46324. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46325. */
  46326. _this.forceIrradianceInFragment = false;
  46327. /**
  46328. * Number of Simultaneous lights allowed on the material.
  46329. */
  46330. _this.maxSimultaneousLights = 4;
  46331. /**
  46332. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46333. */
  46334. _this.invertNormalMapX = false;
  46335. /**
  46336. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46337. */
  46338. _this.invertNormalMapY = false;
  46339. /**
  46340. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46341. */
  46342. _this.twoSidedLighting = false;
  46343. /**
  46344. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46345. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46346. */
  46347. _this.useAlphaFresnel = false;
  46348. /**
  46349. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46350. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46351. */
  46352. _this.useLinearAlphaFresnel = false;
  46353. /**
  46354. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46355. * And/Or occlude the blended part.
  46356. */
  46357. _this.environmentBRDFTexture = null;
  46358. /**
  46359. * Force normal to face away from face.
  46360. */
  46361. _this.forceNormalForward = false;
  46362. /**
  46363. * Enables specular anti aliasing in the PBR shader.
  46364. * It will both interacts on the Geometry for analytical and IBL lighting.
  46365. * It also prefilter the roughness map based on the bump values.
  46366. */
  46367. _this.enableSpecularAntiAliasing = false;
  46368. /**
  46369. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46370. * makes the reflect vector face the model (under horizon).
  46371. */
  46372. _this.useHorizonOcclusion = true;
  46373. /**
  46374. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46375. * too much the area relying on ambient texture to define their ambient occlusion.
  46376. */
  46377. _this.useRadianceOcclusion = true;
  46378. /**
  46379. * If set to true, no lighting calculations will be applied.
  46380. */
  46381. _this.unlit = false;
  46382. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46383. return _this;
  46384. }
  46385. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46386. /**
  46387. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46388. */
  46389. get: function () {
  46390. return this._PBRMATERIAL_OPAQUE;
  46391. },
  46392. enumerable: true,
  46393. configurable: true
  46394. });
  46395. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46396. /**
  46397. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46398. */
  46399. get: function () {
  46400. return this._PBRMATERIAL_ALPHATEST;
  46401. },
  46402. enumerable: true,
  46403. configurable: true
  46404. });
  46405. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46406. /**
  46407. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46408. */
  46409. get: function () {
  46410. return this._PBRMATERIAL_ALPHABLEND;
  46411. },
  46412. enumerable: true,
  46413. configurable: true
  46414. });
  46415. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46416. /**
  46417. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46418. * They are also discarded below the alpha cutoff threshold to improve performances.
  46419. */
  46420. get: function () {
  46421. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46422. },
  46423. enumerable: true,
  46424. configurable: true
  46425. });
  46426. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46427. /**
  46428. * Gets the image processing configuration used either in this material.
  46429. */
  46430. get: function () {
  46431. return this._imageProcessingConfiguration;
  46432. },
  46433. /**
  46434. * Sets the Default image processing configuration used either in the this material.
  46435. *
  46436. * If sets to null, the scene one is in use.
  46437. */
  46438. set: function (value) {
  46439. this._attachImageProcessingConfiguration(value);
  46440. // Ensure the effect will be rebuilt.
  46441. this._markAllSubMeshesAsTexturesDirty();
  46442. },
  46443. enumerable: true,
  46444. configurable: true
  46445. });
  46446. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46447. /**
  46448. * Gets wether the color curves effect is enabled.
  46449. */
  46450. get: function () {
  46451. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46452. },
  46453. /**
  46454. * Sets wether the color curves effect is enabled.
  46455. */
  46456. set: function (value) {
  46457. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46458. },
  46459. enumerable: true,
  46460. configurable: true
  46461. });
  46462. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46463. /**
  46464. * Gets wether the color grading effect is enabled.
  46465. */
  46466. get: function () {
  46467. return this.imageProcessingConfiguration.colorGradingEnabled;
  46468. },
  46469. /**
  46470. * Gets wether the color grading effect is enabled.
  46471. */
  46472. set: function (value) {
  46473. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46474. },
  46475. enumerable: true,
  46476. configurable: true
  46477. });
  46478. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46479. /**
  46480. * Gets wether tonemapping is enabled or not.
  46481. */
  46482. get: function () {
  46483. return this._imageProcessingConfiguration.toneMappingEnabled;
  46484. },
  46485. /**
  46486. * Sets wether tonemapping is enabled or not
  46487. */
  46488. set: function (value) {
  46489. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46490. },
  46491. enumerable: true,
  46492. configurable: true
  46493. });
  46494. ;
  46495. ;
  46496. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46497. /**
  46498. * The camera exposure used on this material.
  46499. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46500. * This corresponds to a photographic exposure.
  46501. */
  46502. get: function () {
  46503. return this._imageProcessingConfiguration.exposure;
  46504. },
  46505. /**
  46506. * The camera exposure used on this material.
  46507. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46508. * This corresponds to a photographic exposure.
  46509. */
  46510. set: function (value) {
  46511. this._imageProcessingConfiguration.exposure = value;
  46512. },
  46513. enumerable: true,
  46514. configurable: true
  46515. });
  46516. ;
  46517. ;
  46518. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46519. /**
  46520. * Gets The camera contrast used on this material.
  46521. */
  46522. get: function () {
  46523. return this._imageProcessingConfiguration.contrast;
  46524. },
  46525. /**
  46526. * Sets The camera contrast used on this material.
  46527. */
  46528. set: function (value) {
  46529. this._imageProcessingConfiguration.contrast = value;
  46530. },
  46531. enumerable: true,
  46532. configurable: true
  46533. });
  46534. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46535. /**
  46536. * Gets the Color Grading 2D Lookup Texture.
  46537. */
  46538. get: function () {
  46539. return this._imageProcessingConfiguration.colorGradingTexture;
  46540. },
  46541. /**
  46542. * Sets the Color Grading 2D Lookup Texture.
  46543. */
  46544. set: function (value) {
  46545. this._imageProcessingConfiguration.colorGradingTexture = value;
  46546. },
  46547. enumerable: true,
  46548. configurable: true
  46549. });
  46550. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46551. /**
  46552. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46553. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46554. * 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;
  46555. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46556. */
  46557. get: function () {
  46558. return this._imageProcessingConfiguration.colorCurves;
  46559. },
  46560. /**
  46561. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46562. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46563. * 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;
  46564. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46565. */
  46566. set: function (value) {
  46567. this._imageProcessingConfiguration.colorCurves = value;
  46568. },
  46569. enumerable: true,
  46570. configurable: true
  46571. });
  46572. /**
  46573. * Returns the name of this material class.
  46574. */
  46575. PBRMaterial.prototype.getClassName = function () {
  46576. return "PBRMaterial";
  46577. };
  46578. /**
  46579. * Returns an array of the actively used textures.
  46580. * @returns - Array of BaseTextures
  46581. */
  46582. PBRMaterial.prototype.getActiveTextures = function () {
  46583. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46584. if (this._albedoTexture) {
  46585. activeTextures.push(this._albedoTexture);
  46586. }
  46587. if (this._ambientTexture) {
  46588. activeTextures.push(this._ambientTexture);
  46589. }
  46590. if (this._opacityTexture) {
  46591. activeTextures.push(this._opacityTexture);
  46592. }
  46593. if (this._reflectionTexture) {
  46594. activeTextures.push(this._reflectionTexture);
  46595. }
  46596. if (this._emissiveTexture) {
  46597. activeTextures.push(this._emissiveTexture);
  46598. }
  46599. if (this._reflectivityTexture) {
  46600. activeTextures.push(this._reflectivityTexture);
  46601. }
  46602. if (this._metallicTexture) {
  46603. activeTextures.push(this._metallicTexture);
  46604. }
  46605. if (this._microSurfaceTexture) {
  46606. activeTextures.push(this._microSurfaceTexture);
  46607. }
  46608. if (this._bumpTexture) {
  46609. activeTextures.push(this._bumpTexture);
  46610. }
  46611. if (this._lightmapTexture) {
  46612. activeTextures.push(this._lightmapTexture);
  46613. }
  46614. if (this._refractionTexture) {
  46615. activeTextures.push(this._refractionTexture);
  46616. }
  46617. return activeTextures;
  46618. };
  46619. /**
  46620. * Checks to see if a texture is used in the material.
  46621. * @param texture - Base texture to use.
  46622. * @returns - Boolean specifying if a texture is used in the material.
  46623. */
  46624. PBRMaterial.prototype.hasTexture = function (texture) {
  46625. if (_super.prototype.hasTexture.call(this, texture)) {
  46626. return true;
  46627. }
  46628. if (this._albedoTexture === texture) {
  46629. return true;
  46630. }
  46631. if (this._ambientTexture === texture) {
  46632. return true;
  46633. }
  46634. if (this._opacityTexture === texture) {
  46635. return true;
  46636. }
  46637. if (this._reflectionTexture === texture) {
  46638. return true;
  46639. }
  46640. if (this._reflectivityTexture === texture) {
  46641. return true;
  46642. }
  46643. if (this._metallicTexture === texture) {
  46644. return true;
  46645. }
  46646. if (this._microSurfaceTexture === texture) {
  46647. return true;
  46648. }
  46649. if (this._bumpTexture === texture) {
  46650. return true;
  46651. }
  46652. if (this._lightmapTexture === texture) {
  46653. return true;
  46654. }
  46655. if (this._refractionTexture === texture) {
  46656. return true;
  46657. }
  46658. return false;
  46659. };
  46660. /**
  46661. * Makes a duplicate of the current material.
  46662. * @param name - name to use for the new material.
  46663. */
  46664. PBRMaterial.prototype.clone = function (name) {
  46665. var _this = this;
  46666. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46667. clone.id = name;
  46668. clone.name = name;
  46669. return clone;
  46670. };
  46671. /**
  46672. * Serializes this PBR Material.
  46673. * @returns - An object with the serialized material.
  46674. */
  46675. PBRMaterial.prototype.serialize = function () {
  46676. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46677. serializationObject.customType = "BABYLON.PBRMaterial";
  46678. return serializationObject;
  46679. };
  46680. // Statics
  46681. /**
  46682. * Parses a PBR Material from a serialized object.
  46683. * @param source - Serialized object.
  46684. * @param scene - BJS scene instance.
  46685. * @param rootUrl - url for the scene object
  46686. * @returns - PBRMaterial
  46687. */
  46688. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46689. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46690. };
  46691. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46692. /**
  46693. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46694. */
  46695. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46696. /**
  46697. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46698. */
  46699. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46700. /**
  46701. * 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.
  46702. * They are also discarded below the alpha cutoff threshold to improve performances.
  46703. */
  46704. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46705. __decorate([
  46706. BABYLON.serialize(),
  46707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46708. ], PBRMaterial.prototype, "directIntensity", void 0);
  46709. __decorate([
  46710. BABYLON.serialize(),
  46711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46712. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46713. __decorate([
  46714. BABYLON.serialize(),
  46715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46716. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46717. __decorate([
  46718. BABYLON.serialize(),
  46719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46720. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46721. __decorate([
  46722. BABYLON.serialize(),
  46723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46724. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46725. __decorate([
  46726. BABYLON.serializeAsTexture(),
  46727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46728. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46729. __decorate([
  46730. BABYLON.serializeAsTexture(),
  46731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46732. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46733. __decorate([
  46734. BABYLON.serialize(),
  46735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46736. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46737. __decorate([
  46738. BABYLON.serializeAsTexture(),
  46739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46740. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46741. __decorate([
  46742. BABYLON.serializeAsTexture(),
  46743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46744. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46745. __decorate([
  46746. BABYLON.serializeAsTexture(),
  46747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46748. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46749. __decorate([
  46750. BABYLON.serializeAsTexture(),
  46751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46752. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46753. __decorate([
  46754. BABYLON.serializeAsTexture(),
  46755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46756. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46757. __decorate([
  46758. BABYLON.serialize(),
  46759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46760. ], PBRMaterial.prototype, "metallic", void 0);
  46761. __decorate([
  46762. BABYLON.serialize(),
  46763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46764. ], PBRMaterial.prototype, "roughness", void 0);
  46765. __decorate([
  46766. BABYLON.serializeAsTexture(),
  46767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46768. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46769. __decorate([
  46770. BABYLON.serializeAsTexture(),
  46771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46772. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46773. __decorate([
  46774. BABYLON.serializeAsTexture(),
  46775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46776. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46777. __decorate([
  46778. BABYLON.serializeAsTexture(),
  46779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46780. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46781. __decorate([
  46782. BABYLON.serializeAsColor3("ambient"),
  46783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46784. ], PBRMaterial.prototype, "ambientColor", void 0);
  46785. __decorate([
  46786. BABYLON.serializeAsColor3("albedo"),
  46787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46788. ], PBRMaterial.prototype, "albedoColor", void 0);
  46789. __decorate([
  46790. BABYLON.serializeAsColor3("reflectivity"),
  46791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46792. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46793. __decorate([
  46794. BABYLON.serializeAsColor3("reflection"),
  46795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46796. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46797. __decorate([
  46798. BABYLON.serializeAsColor3("emissive"),
  46799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46800. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46801. __decorate([
  46802. BABYLON.serialize(),
  46803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46804. ], PBRMaterial.prototype, "microSurface", void 0);
  46805. __decorate([
  46806. BABYLON.serialize(),
  46807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46808. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46809. __decorate([
  46810. BABYLON.serialize(),
  46811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46812. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46813. __decorate([
  46814. BABYLON.serialize(),
  46815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46816. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46817. __decorate([
  46818. BABYLON.serialize(),
  46819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46820. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46821. __decorate([
  46822. BABYLON.serialize(),
  46823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46824. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46825. __decorate([
  46826. BABYLON.serialize(),
  46827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46828. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46829. __decorate([
  46830. BABYLON.serialize(),
  46831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46832. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46833. __decorate([
  46834. BABYLON.serialize(),
  46835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46836. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46837. __decorate([
  46838. BABYLON.serialize(),
  46839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46840. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46841. __decorate([
  46842. BABYLON.serialize(),
  46843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46844. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46845. __decorate([
  46846. BABYLON.serialize(),
  46847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46848. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46849. __decorate([
  46850. BABYLON.serialize(),
  46851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46852. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46853. __decorate([
  46854. BABYLON.serialize(),
  46855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46856. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46857. __decorate([
  46858. BABYLON.serialize(),
  46859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46860. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46861. __decorate([
  46862. BABYLON.serialize(),
  46863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46864. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46865. __decorate([
  46866. BABYLON.serialize(),
  46867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46868. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46869. __decorate([
  46870. BABYLON.serialize(),
  46871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46872. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46873. __decorate([
  46874. BABYLON.serialize(),
  46875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46876. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46877. __decorate([
  46878. BABYLON.serialize(),
  46879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46880. ], PBRMaterial.prototype, "useParallax", void 0);
  46881. __decorate([
  46882. BABYLON.serialize(),
  46883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46884. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46885. __decorate([
  46886. BABYLON.serialize(),
  46887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46888. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46889. __decorate([
  46890. BABYLON.serialize(),
  46891. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46892. ], PBRMaterial.prototype, "disableLighting", void 0);
  46893. __decorate([
  46894. BABYLON.serialize(),
  46895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46896. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46897. __decorate([
  46898. BABYLON.serialize(),
  46899. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46900. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46901. __decorate([
  46902. BABYLON.serialize(),
  46903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46904. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46905. __decorate([
  46906. BABYLON.serialize(),
  46907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46908. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46909. __decorate([
  46910. BABYLON.serialize(),
  46911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46912. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46913. __decorate([
  46914. BABYLON.serialize(),
  46915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46916. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46917. __decorate([
  46918. BABYLON.serialize(),
  46919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46920. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46921. __decorate([
  46922. BABYLON.serializeAsTexture(),
  46923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46924. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46925. __decorate([
  46926. BABYLON.serialize(),
  46927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46928. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46929. __decorate([
  46930. BABYLON.serialize(),
  46931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46932. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46933. __decorate([
  46934. BABYLON.serialize(),
  46935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46936. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46937. __decorate([
  46938. BABYLON.serialize(),
  46939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46940. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46941. __decorate([
  46942. BABYLON.serialize(),
  46943. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46944. ], PBRMaterial.prototype, "unlit", void 0);
  46945. return PBRMaterial;
  46946. }(BABYLON.PBRBaseMaterial));
  46947. BABYLON.PBRMaterial = PBRMaterial;
  46948. })(BABYLON || (BABYLON = {}));
  46949. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46950. var BABYLON;
  46951. (function (BABYLON) {
  46952. /**
  46953. * The PBR material of BJS following the metal roughness convention.
  46954. *
  46955. * This fits to the PBR convention in the GLTF definition:
  46956. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46957. */
  46958. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46959. __extends(PBRMetallicRoughnessMaterial, _super);
  46960. /**
  46961. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46962. *
  46963. * @param name The material name
  46964. * @param scene The scene the material will be use in.
  46965. */
  46966. function PBRMetallicRoughnessMaterial(name, scene) {
  46967. var _this = _super.call(this, name, scene) || this;
  46968. _this._useRoughnessFromMetallicTextureAlpha = false;
  46969. _this._useRoughnessFromMetallicTextureGreen = true;
  46970. _this._useMetallnessFromMetallicTextureBlue = true;
  46971. _this.metallic = 1.0;
  46972. _this.roughness = 1.0;
  46973. return _this;
  46974. }
  46975. /**
  46976. * Return the currrent class name of the material.
  46977. */
  46978. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46979. return "PBRMetallicRoughnessMaterial";
  46980. };
  46981. /**
  46982. * Return the active textures of the material.
  46983. */
  46984. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46985. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46986. if (this.baseTexture) {
  46987. activeTextures.push(this.baseTexture);
  46988. }
  46989. if (this.metallicRoughnessTexture) {
  46990. activeTextures.push(this.metallicRoughnessTexture);
  46991. }
  46992. return activeTextures;
  46993. };
  46994. /**
  46995. * Checks to see if a texture is used in the material.
  46996. * @param texture - Base texture to use.
  46997. * @returns - Boolean specifying if a texture is used in the material.
  46998. */
  46999. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47000. if (_super.prototype.hasTexture.call(this, texture)) {
  47001. return true;
  47002. }
  47003. if (this.baseTexture === texture) {
  47004. return true;
  47005. }
  47006. if (this.metallicRoughnessTexture === texture) {
  47007. return true;
  47008. }
  47009. return false;
  47010. };
  47011. /**
  47012. * Makes a duplicate of the current material.
  47013. * @param name - name to use for the new material.
  47014. */
  47015. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47016. var _this = this;
  47017. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47018. clone.id = name;
  47019. clone.name = name;
  47020. return clone;
  47021. };
  47022. /**
  47023. * Serialize the material to a parsable JSON object.
  47024. */
  47025. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47026. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47027. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47028. return serializationObject;
  47029. };
  47030. /**
  47031. * Parses a JSON object correponding to the serialize function.
  47032. */
  47033. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47034. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47035. };
  47036. __decorate([
  47037. BABYLON.serializeAsColor3(),
  47038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47039. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47040. __decorate([
  47041. BABYLON.serializeAsTexture(),
  47042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47043. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47044. __decorate([
  47045. BABYLON.serialize(),
  47046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47047. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47048. __decorate([
  47049. BABYLON.serialize(),
  47050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47051. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47052. __decorate([
  47053. BABYLON.serializeAsTexture(),
  47054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47055. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47056. return PBRMetallicRoughnessMaterial;
  47057. }(BABYLON.PBRBaseSimpleMaterial));
  47058. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47059. })(BABYLON || (BABYLON = {}));
  47060. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47061. var BABYLON;
  47062. (function (BABYLON) {
  47063. /**
  47064. * The PBR material of BJS following the specular glossiness convention.
  47065. *
  47066. * This fits to the PBR convention in the GLTF definition:
  47067. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47068. */
  47069. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47070. __extends(PBRSpecularGlossinessMaterial, _super);
  47071. /**
  47072. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47073. *
  47074. * @param name The material name
  47075. * @param scene The scene the material will be use in.
  47076. */
  47077. function PBRSpecularGlossinessMaterial(name, scene) {
  47078. var _this = _super.call(this, name, scene) || this;
  47079. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47080. return _this;
  47081. }
  47082. /**
  47083. * Return the currrent class name of the material.
  47084. */
  47085. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47086. return "PBRSpecularGlossinessMaterial";
  47087. };
  47088. /**
  47089. * Return the active textures of the material.
  47090. */
  47091. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47092. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47093. if (this.diffuseTexture) {
  47094. activeTextures.push(this.diffuseTexture);
  47095. }
  47096. if (this.specularGlossinessTexture) {
  47097. activeTextures.push(this.specularGlossinessTexture);
  47098. }
  47099. return activeTextures;
  47100. };
  47101. /**
  47102. * Checks to see if a texture is used in the material.
  47103. * @param texture - Base texture to use.
  47104. * @returns - Boolean specifying if a texture is used in the material.
  47105. */
  47106. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47107. if (_super.prototype.hasTexture.call(this, texture)) {
  47108. return true;
  47109. }
  47110. if (this.diffuseTexture === texture) {
  47111. return true;
  47112. }
  47113. if (this.specularGlossinessTexture === texture) {
  47114. return true;
  47115. }
  47116. return false;
  47117. };
  47118. /**
  47119. * Makes a duplicate of the current material.
  47120. * @param name - name to use for the new material.
  47121. */
  47122. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47123. var _this = this;
  47124. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47125. clone.id = name;
  47126. clone.name = name;
  47127. return clone;
  47128. };
  47129. /**
  47130. * Serialize the material to a parsable JSON object.
  47131. */
  47132. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47133. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47134. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47135. return serializationObject;
  47136. };
  47137. /**
  47138. * Parses a JSON object correponding to the serialize function.
  47139. */
  47140. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47141. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47142. };
  47143. __decorate([
  47144. BABYLON.serializeAsColor3("diffuse"),
  47145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47146. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47147. __decorate([
  47148. BABYLON.serializeAsTexture(),
  47149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47150. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47151. __decorate([
  47152. BABYLON.serializeAsColor3("specular"),
  47153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47154. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47155. __decorate([
  47156. BABYLON.serialize(),
  47157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47158. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47159. __decorate([
  47160. BABYLON.serializeAsTexture(),
  47161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47162. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47163. return PBRSpecularGlossinessMaterial;
  47164. }(BABYLON.PBRBaseSimpleMaterial));
  47165. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47166. })(BABYLON || (BABYLON = {}));
  47167. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47168. var BABYLON;
  47169. (function (BABYLON) {
  47170. BABYLON.CameraInputTypes = {};
  47171. var CameraInputsManager = /** @class */ (function () {
  47172. function CameraInputsManager(camera) {
  47173. this.attached = {};
  47174. this.camera = camera;
  47175. this.checkInputs = function () { };
  47176. }
  47177. /**
  47178. * Add an input method to a camera.
  47179. * builtin inputs example: camera.inputs.addGamepad();
  47180. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47181. * @param input camera input method
  47182. */
  47183. CameraInputsManager.prototype.add = function (input) {
  47184. var type = input.getSimpleName();
  47185. if (this.attached[type]) {
  47186. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47187. return;
  47188. }
  47189. this.attached[type] = input;
  47190. input.camera = this.camera;
  47191. //for checkInputs, we are dynamically creating a function
  47192. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47193. if (input.checkInputs) {
  47194. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47195. }
  47196. if (this.attachedElement) {
  47197. input.attachControl(this.attachedElement);
  47198. }
  47199. };
  47200. /**
  47201. * Remove a specific input method from a camera
  47202. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47203. * @param inputToRemove camera input method
  47204. */
  47205. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47206. for (var cam in this.attached) {
  47207. var input = this.attached[cam];
  47208. if (input === inputToRemove) {
  47209. input.detachControl(this.attachedElement);
  47210. input.camera = null;
  47211. delete this.attached[cam];
  47212. this.rebuildInputCheck();
  47213. }
  47214. }
  47215. };
  47216. CameraInputsManager.prototype.removeByType = function (inputType) {
  47217. for (var cam in this.attached) {
  47218. var input = this.attached[cam];
  47219. if (input.getClassName() === inputType) {
  47220. input.detachControl(this.attachedElement);
  47221. input.camera = null;
  47222. delete this.attached[cam];
  47223. this.rebuildInputCheck();
  47224. }
  47225. }
  47226. };
  47227. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47228. var current = this.checkInputs;
  47229. return function () {
  47230. current();
  47231. fn();
  47232. };
  47233. };
  47234. CameraInputsManager.prototype.attachInput = function (input) {
  47235. if (this.attachedElement) {
  47236. input.attachControl(this.attachedElement, this.noPreventDefault);
  47237. }
  47238. };
  47239. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47240. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47241. if (this.attachedElement) {
  47242. return;
  47243. }
  47244. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47245. this.attachedElement = element;
  47246. this.noPreventDefault = noPreventDefault;
  47247. for (var cam in this.attached) {
  47248. this.attached[cam].attachControl(element, noPreventDefault);
  47249. }
  47250. };
  47251. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47252. if (disconnect === void 0) { disconnect = false; }
  47253. if (this.attachedElement !== element) {
  47254. return;
  47255. }
  47256. for (var cam in this.attached) {
  47257. this.attached[cam].detachControl(element);
  47258. if (disconnect) {
  47259. this.attached[cam].camera = null;
  47260. }
  47261. }
  47262. this.attachedElement = null;
  47263. };
  47264. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47265. this.checkInputs = function () { };
  47266. for (var cam in this.attached) {
  47267. var input = this.attached[cam];
  47268. if (input.checkInputs) {
  47269. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47270. }
  47271. }
  47272. };
  47273. /**
  47274. * Remove all attached input methods from a camera
  47275. */
  47276. CameraInputsManager.prototype.clear = function () {
  47277. if (this.attachedElement) {
  47278. this.detachElement(this.attachedElement, true);
  47279. }
  47280. this.attached = {};
  47281. this.attachedElement = null;
  47282. this.checkInputs = function () { };
  47283. };
  47284. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47285. var inputs = {};
  47286. for (var cam in this.attached) {
  47287. var input = this.attached[cam];
  47288. var res = BABYLON.SerializationHelper.Serialize(input);
  47289. inputs[input.getClassName()] = res;
  47290. }
  47291. serializedCamera.inputsmgr = inputs;
  47292. };
  47293. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47294. var parsedInputs = parsedCamera.inputsmgr;
  47295. if (parsedInputs) {
  47296. this.clear();
  47297. for (var n in parsedInputs) {
  47298. var construct = BABYLON.CameraInputTypes[n];
  47299. if (construct) {
  47300. var parsedinput = parsedInputs[n];
  47301. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47302. this.add(input);
  47303. }
  47304. }
  47305. }
  47306. else {
  47307. //2016-03-08 this part is for managing backward compatibility
  47308. for (var n in this.attached) {
  47309. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47310. if (construct) {
  47311. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47312. this.remove(this.attached[n]);
  47313. this.add(input);
  47314. }
  47315. }
  47316. }
  47317. };
  47318. return CameraInputsManager;
  47319. }());
  47320. BABYLON.CameraInputsManager = CameraInputsManager;
  47321. })(BABYLON || (BABYLON = {}));
  47322. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47323. var BABYLON;
  47324. (function (BABYLON) {
  47325. var TargetCamera = /** @class */ (function (_super) {
  47326. __extends(TargetCamera, _super);
  47327. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47328. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47329. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47330. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47331. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47332. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47333. _this.speed = 2.0;
  47334. _this.noRotationConstraint = false;
  47335. _this.lockedTarget = null;
  47336. _this._currentTarget = BABYLON.Vector3.Zero();
  47337. _this._viewMatrix = BABYLON.Matrix.Zero();
  47338. _this._camMatrix = BABYLON.Matrix.Zero();
  47339. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47340. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47341. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47342. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47343. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47344. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47345. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47346. return _this;
  47347. }
  47348. TargetCamera.prototype.getFrontPosition = function (distance) {
  47349. this.getWorldMatrix();
  47350. var direction = this.getTarget().subtract(this.position);
  47351. direction.normalize();
  47352. direction.scaleInPlace(distance);
  47353. return this.globalPosition.add(direction);
  47354. };
  47355. TargetCamera.prototype._getLockedTargetPosition = function () {
  47356. if (!this.lockedTarget) {
  47357. return null;
  47358. }
  47359. if (this.lockedTarget.absolutePosition) {
  47360. this.lockedTarget.computeWorldMatrix();
  47361. }
  47362. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47363. };
  47364. TargetCamera.prototype.storeState = function () {
  47365. this._storedPosition = this.position.clone();
  47366. this._storedRotation = this.rotation.clone();
  47367. if (this.rotationQuaternion) {
  47368. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47369. }
  47370. return _super.prototype.storeState.call(this);
  47371. };
  47372. /**
  47373. * Restored camera state. You must call storeState() first
  47374. */
  47375. TargetCamera.prototype._restoreStateValues = function () {
  47376. if (!_super.prototype._restoreStateValues.call(this)) {
  47377. return false;
  47378. }
  47379. this.position = this._storedPosition.clone();
  47380. this.rotation = this._storedRotation.clone();
  47381. if (this.rotationQuaternion) {
  47382. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47383. }
  47384. this.cameraDirection.copyFromFloats(0, 0, 0);
  47385. this.cameraRotation.copyFromFloats(0, 0);
  47386. return true;
  47387. };
  47388. // Cache
  47389. TargetCamera.prototype._initCache = function () {
  47390. _super.prototype._initCache.call(this);
  47391. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47392. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47393. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47394. };
  47395. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47396. if (!ignoreParentClass) {
  47397. _super.prototype._updateCache.call(this);
  47398. }
  47399. var lockedTargetPosition = this._getLockedTargetPosition();
  47400. if (!lockedTargetPosition) {
  47401. this._cache.lockedTarget = null;
  47402. }
  47403. else {
  47404. if (!this._cache.lockedTarget) {
  47405. this._cache.lockedTarget = lockedTargetPosition.clone();
  47406. }
  47407. else {
  47408. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47409. }
  47410. }
  47411. this._cache.rotation.copyFrom(this.rotation);
  47412. if (this.rotationQuaternion)
  47413. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47414. };
  47415. // Synchronized
  47416. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47417. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47418. return false;
  47419. }
  47420. var lockedTargetPosition = this._getLockedTargetPosition();
  47421. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47422. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47423. };
  47424. // Methods
  47425. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47426. var engine = this.getEngine();
  47427. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47428. };
  47429. // Target
  47430. TargetCamera.prototype.setTarget = function (target) {
  47431. this.upVector.normalize();
  47432. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47433. this._camMatrix.invert();
  47434. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47435. var vDir = target.subtract(this.position);
  47436. if (vDir.x >= 0.0) {
  47437. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47438. }
  47439. else {
  47440. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47441. }
  47442. this.rotation.z = 0;
  47443. if (isNaN(this.rotation.x)) {
  47444. this.rotation.x = 0;
  47445. }
  47446. if (isNaN(this.rotation.y)) {
  47447. this.rotation.y = 0;
  47448. }
  47449. if (isNaN(this.rotation.z)) {
  47450. this.rotation.z = 0;
  47451. }
  47452. if (this.rotationQuaternion) {
  47453. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47454. }
  47455. };
  47456. /**
  47457. * Return the current target position of the camera. This value is expressed in local space.
  47458. */
  47459. TargetCamera.prototype.getTarget = function () {
  47460. return this._currentTarget;
  47461. };
  47462. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47463. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47464. };
  47465. TargetCamera.prototype._updatePosition = function () {
  47466. if (this.parent) {
  47467. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47468. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47469. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47470. return;
  47471. }
  47472. this.position.addInPlace(this.cameraDirection);
  47473. };
  47474. TargetCamera.prototype._checkInputs = function () {
  47475. var needToMove = this._decideIfNeedsToMove();
  47476. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47477. // Move
  47478. if (needToMove) {
  47479. this._updatePosition();
  47480. }
  47481. // Rotate
  47482. if (needToRotate) {
  47483. this.rotation.x += this.cameraRotation.x;
  47484. this.rotation.y += this.cameraRotation.y;
  47485. //rotate, if quaternion is set and rotation was used
  47486. if (this.rotationQuaternion) {
  47487. var len = this.rotation.lengthSquared();
  47488. if (len) {
  47489. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47490. }
  47491. }
  47492. if (!this.noRotationConstraint) {
  47493. var limit = (Math.PI / 2) * 0.95;
  47494. if (this.rotation.x > limit)
  47495. this.rotation.x = limit;
  47496. if (this.rotation.x < -limit)
  47497. this.rotation.x = -limit;
  47498. }
  47499. }
  47500. // Inertia
  47501. if (needToMove) {
  47502. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47503. this.cameraDirection.x = 0;
  47504. }
  47505. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47506. this.cameraDirection.y = 0;
  47507. }
  47508. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47509. this.cameraDirection.z = 0;
  47510. }
  47511. this.cameraDirection.scaleInPlace(this.inertia);
  47512. }
  47513. if (needToRotate) {
  47514. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47515. this.cameraRotation.x = 0;
  47516. }
  47517. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47518. this.cameraRotation.y = 0;
  47519. }
  47520. this.cameraRotation.scaleInPlace(this.inertia);
  47521. }
  47522. _super.prototype._checkInputs.call(this);
  47523. };
  47524. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47525. if (this.rotationQuaternion) {
  47526. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47527. }
  47528. else {
  47529. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47530. }
  47531. //update the up vector!
  47532. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47533. };
  47534. TargetCamera.prototype._getViewMatrix = function () {
  47535. if (this.lockedTarget) {
  47536. this.setTarget(this._getLockedTargetPosition());
  47537. }
  47538. // Compute
  47539. this._updateCameraRotationMatrix();
  47540. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47541. // Computing target and final matrix
  47542. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47543. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47544. return this._viewMatrix;
  47545. };
  47546. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47547. if (this.parent) {
  47548. var parentWorldMatrix = this.parent.getWorldMatrix();
  47549. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47550. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47551. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47552. this._markSyncedWithParent();
  47553. }
  47554. else {
  47555. this._globalPosition.copyFrom(this.position);
  47556. this._globalCurrentTarget.copyFrom(target);
  47557. this._globalCurrentUpVector.copyFrom(up);
  47558. }
  47559. if (this.getScene().useRightHandedSystem) {
  47560. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47561. }
  47562. else {
  47563. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47564. }
  47565. };
  47566. /**
  47567. * @override
  47568. * Override Camera.createRigCamera
  47569. */
  47570. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47571. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47572. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47573. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47574. if (!this.rotationQuaternion) {
  47575. this.rotationQuaternion = new BABYLON.Quaternion();
  47576. }
  47577. rigCamera._cameraRigParams = {};
  47578. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47579. }
  47580. return rigCamera;
  47581. }
  47582. return null;
  47583. };
  47584. /**
  47585. * @override
  47586. * Override Camera._updateRigCameras
  47587. */
  47588. TargetCamera.prototype._updateRigCameras = function () {
  47589. var camLeft = this._rigCameras[0];
  47590. var camRight = this._rigCameras[1];
  47591. switch (this.cameraRigMode) {
  47592. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47594. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47595. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47596. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47597. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47598. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47599. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47600. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47601. camLeft.setTarget(this.getTarget());
  47602. camRight.setTarget(this.getTarget());
  47603. break;
  47604. case BABYLON.Camera.RIG_MODE_VR:
  47605. if (camLeft.rotationQuaternion) {
  47606. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47607. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47608. }
  47609. else {
  47610. camLeft.rotation.copyFrom(this.rotation);
  47611. camRight.rotation.copyFrom(this.rotation);
  47612. }
  47613. camLeft.position.copyFrom(this.position);
  47614. camRight.position.copyFrom(this.position);
  47615. break;
  47616. }
  47617. _super.prototype._updateRigCameras.call(this);
  47618. };
  47619. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47620. if (!this._rigCamTransformMatrix) {
  47621. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47622. }
  47623. var target = this.getTarget();
  47624. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47625. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47626. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47627. };
  47628. TargetCamera.prototype.getClassName = function () {
  47629. return "TargetCamera";
  47630. };
  47631. __decorate([
  47632. BABYLON.serializeAsVector3()
  47633. ], TargetCamera.prototype, "rotation", void 0);
  47634. __decorate([
  47635. BABYLON.serialize()
  47636. ], TargetCamera.prototype, "speed", void 0);
  47637. __decorate([
  47638. BABYLON.serializeAsMeshReference("lockedTargetId")
  47639. ], TargetCamera.prototype, "lockedTarget", void 0);
  47640. return TargetCamera;
  47641. }(BABYLON.Camera));
  47642. BABYLON.TargetCamera = TargetCamera;
  47643. })(BABYLON || (BABYLON = {}));
  47644. //# sourceMappingURL=babylon.targetCamera.js.map
  47645. var BABYLON;
  47646. (function (BABYLON) {
  47647. var FreeCameraMouseInput = /** @class */ (function () {
  47648. function FreeCameraMouseInput(touchEnabled) {
  47649. if (touchEnabled === void 0) { touchEnabled = true; }
  47650. this.touchEnabled = touchEnabled;
  47651. this.buttons = [0, 1, 2];
  47652. this.angularSensibility = 2000.0;
  47653. this.previousPosition = null;
  47654. }
  47655. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47656. var _this = this;
  47657. var engine = this.camera.getEngine();
  47658. if (!this._pointerInput) {
  47659. this._pointerInput = function (p, s) {
  47660. var evt = p.event;
  47661. if (engine.isInVRExclusivePointerMode) {
  47662. return;
  47663. }
  47664. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47665. return;
  47666. }
  47667. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47668. return;
  47669. }
  47670. var srcElement = (evt.srcElement || evt.target);
  47671. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47672. try {
  47673. srcElement.setPointerCapture(evt.pointerId);
  47674. }
  47675. catch (e) {
  47676. //Nothing to do with the error. Execution will continue.
  47677. }
  47678. _this.previousPosition = {
  47679. x: evt.clientX,
  47680. y: evt.clientY
  47681. };
  47682. if (!noPreventDefault) {
  47683. evt.preventDefault();
  47684. element.focus();
  47685. }
  47686. }
  47687. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47688. try {
  47689. srcElement.releasePointerCapture(evt.pointerId);
  47690. }
  47691. catch (e) {
  47692. //Nothing to do with the error.
  47693. }
  47694. _this.previousPosition = null;
  47695. if (!noPreventDefault) {
  47696. evt.preventDefault();
  47697. }
  47698. }
  47699. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47700. if (!_this.previousPosition || engine.isPointerLock) {
  47701. return;
  47702. }
  47703. var offsetX = evt.clientX - _this.previousPosition.x;
  47704. if (_this.camera.getScene().useRightHandedSystem)
  47705. offsetX *= -1;
  47706. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47707. offsetX *= -1;
  47708. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47709. var offsetY = evt.clientY - _this.previousPosition.y;
  47710. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47711. _this.previousPosition = {
  47712. x: evt.clientX,
  47713. y: evt.clientY
  47714. };
  47715. if (!noPreventDefault) {
  47716. evt.preventDefault();
  47717. }
  47718. }
  47719. };
  47720. }
  47721. this._onMouseMove = function (evt) {
  47722. if (!engine.isPointerLock) {
  47723. return;
  47724. }
  47725. if (engine.isInVRExclusivePointerMode) {
  47726. return;
  47727. }
  47728. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47729. if (_this.camera.getScene().useRightHandedSystem)
  47730. offsetX *= -1;
  47731. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47732. offsetX *= -1;
  47733. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47734. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47735. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47736. _this.previousPosition = null;
  47737. if (!noPreventDefault) {
  47738. evt.preventDefault();
  47739. }
  47740. };
  47741. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47742. element.addEventListener("mousemove", this._onMouseMove, false);
  47743. };
  47744. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47745. if (this._observer && element) {
  47746. this.camera.getScene().onPointerObservable.remove(this._observer);
  47747. if (this._onMouseMove) {
  47748. element.removeEventListener("mousemove", this._onMouseMove);
  47749. }
  47750. this._observer = null;
  47751. this._onMouseMove = null;
  47752. this.previousPosition = null;
  47753. }
  47754. };
  47755. FreeCameraMouseInput.prototype.getClassName = function () {
  47756. return "FreeCameraMouseInput";
  47757. };
  47758. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47759. return "mouse";
  47760. };
  47761. __decorate([
  47762. BABYLON.serialize()
  47763. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47764. __decorate([
  47765. BABYLON.serialize()
  47766. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47767. return FreeCameraMouseInput;
  47768. }());
  47769. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47770. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47771. })(BABYLON || (BABYLON = {}));
  47772. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47773. var BABYLON;
  47774. (function (BABYLON) {
  47775. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47776. function FreeCameraKeyboardMoveInput() {
  47777. this._keys = new Array();
  47778. this.keysUp = [38];
  47779. this.keysDown = [40];
  47780. this.keysLeft = [37];
  47781. this.keysRight = [39];
  47782. }
  47783. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47784. var _this = this;
  47785. if (this._onCanvasBlurObserver) {
  47786. return;
  47787. }
  47788. this._scene = this.camera.getScene();
  47789. this._engine = this._scene.getEngine();
  47790. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47791. _this._keys = [];
  47792. });
  47793. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47794. var evt = info.event;
  47795. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47796. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47797. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47798. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47799. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47800. var index = _this._keys.indexOf(evt.keyCode);
  47801. if (index === -1) {
  47802. _this._keys.push(evt.keyCode);
  47803. }
  47804. if (!noPreventDefault) {
  47805. evt.preventDefault();
  47806. }
  47807. }
  47808. }
  47809. else {
  47810. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47811. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47812. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47813. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47814. var index = _this._keys.indexOf(evt.keyCode);
  47815. if (index >= 0) {
  47816. _this._keys.splice(index, 1);
  47817. }
  47818. if (!noPreventDefault) {
  47819. evt.preventDefault();
  47820. }
  47821. }
  47822. }
  47823. });
  47824. };
  47825. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47826. if (this._scene) {
  47827. if (this._onKeyboardObserver) {
  47828. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47829. }
  47830. if (this._onCanvasBlurObserver) {
  47831. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47832. }
  47833. this._onKeyboardObserver = null;
  47834. this._onCanvasBlurObserver = null;
  47835. }
  47836. this._keys = [];
  47837. };
  47838. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47839. if (this._onKeyboardObserver) {
  47840. var camera = this.camera;
  47841. // Keyboard
  47842. for (var index = 0; index < this._keys.length; index++) {
  47843. var keyCode = this._keys[index];
  47844. var speed = camera._computeLocalCameraSpeed();
  47845. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47846. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47847. }
  47848. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47849. camera._localDirection.copyFromFloats(0, 0, speed);
  47850. }
  47851. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47852. camera._localDirection.copyFromFloats(speed, 0, 0);
  47853. }
  47854. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47855. camera._localDirection.copyFromFloats(0, 0, -speed);
  47856. }
  47857. if (camera.getScene().useRightHandedSystem) {
  47858. camera._localDirection.z *= -1;
  47859. }
  47860. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47861. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47862. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47863. }
  47864. }
  47865. };
  47866. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47867. return "FreeCameraKeyboardMoveInput";
  47868. };
  47869. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47870. this._keys = [];
  47871. };
  47872. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47873. return "keyboard";
  47874. };
  47875. __decorate([
  47876. BABYLON.serialize()
  47877. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47878. __decorate([
  47879. BABYLON.serialize()
  47880. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47881. __decorate([
  47882. BABYLON.serialize()
  47883. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47884. __decorate([
  47885. BABYLON.serialize()
  47886. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47887. return FreeCameraKeyboardMoveInput;
  47888. }());
  47889. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47890. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47891. })(BABYLON || (BABYLON = {}));
  47892. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47893. var BABYLON;
  47894. (function (BABYLON) {
  47895. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47896. __extends(FreeCameraInputsManager, _super);
  47897. function FreeCameraInputsManager(camera) {
  47898. return _super.call(this, camera) || this;
  47899. }
  47900. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47901. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47902. return this;
  47903. };
  47904. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47905. if (touchEnabled === void 0) { touchEnabled = true; }
  47906. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47907. return this;
  47908. };
  47909. FreeCameraInputsManager.prototype.addGamepad = function () {
  47910. this.add(new BABYLON.FreeCameraGamepadInput());
  47911. return this;
  47912. };
  47913. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47914. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47915. return this;
  47916. };
  47917. FreeCameraInputsManager.prototype.addTouch = function () {
  47918. this.add(new BABYLON.FreeCameraTouchInput());
  47919. return this;
  47920. };
  47921. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47922. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47923. return this;
  47924. };
  47925. return FreeCameraInputsManager;
  47926. }(BABYLON.CameraInputsManager));
  47927. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47928. })(BABYLON || (BABYLON = {}));
  47929. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47930. var BABYLON;
  47931. (function (BABYLON) {
  47932. var FreeCamera = /** @class */ (function (_super) {
  47933. __extends(FreeCamera, _super);
  47934. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47935. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47936. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47937. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47938. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47939. _this.checkCollisions = false;
  47940. _this.applyGravity = false;
  47941. _this._needMoveForGravity = false;
  47942. _this._oldPosition = BABYLON.Vector3.Zero();
  47943. _this._diffPosition = BABYLON.Vector3.Zero();
  47944. _this._newPosition = BABYLON.Vector3.Zero();
  47945. // Collisions
  47946. _this._collisionMask = -1;
  47947. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47948. if (collidedMesh === void 0) { collidedMesh = null; }
  47949. //TODO move this to the collision coordinator!
  47950. if (_this.getScene().workerCollisions)
  47951. newPosition.multiplyInPlace(_this._collider._radius);
  47952. var updatePosition = function (newPos) {
  47953. _this._newPosition.copyFrom(newPos);
  47954. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47955. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47956. _this.position.addInPlace(_this._diffPosition);
  47957. if (_this.onCollide && collidedMesh) {
  47958. _this.onCollide(collidedMesh);
  47959. }
  47960. }
  47961. };
  47962. updatePosition(newPosition);
  47963. };
  47964. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47965. _this.inputs.addKeyboard().addMouse();
  47966. return _this;
  47967. }
  47968. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47969. //-- begin properties for backward compatibility for inputs
  47970. /**
  47971. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47972. * Higher values reduce sensitivity.
  47973. */
  47974. get: function () {
  47975. var mouse = this.inputs.attached["mouse"];
  47976. if (mouse)
  47977. return mouse.angularSensibility;
  47978. return 0;
  47979. },
  47980. /**
  47981. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47982. * Higher values reduce sensitivity.
  47983. */
  47984. set: function (value) {
  47985. var mouse = this.inputs.attached["mouse"];
  47986. if (mouse)
  47987. mouse.angularSensibility = value;
  47988. },
  47989. enumerable: true,
  47990. configurable: true
  47991. });
  47992. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47993. get: function () {
  47994. var keyboard = this.inputs.attached["keyboard"];
  47995. if (keyboard)
  47996. return keyboard.keysUp;
  47997. return [];
  47998. },
  47999. set: function (value) {
  48000. var keyboard = this.inputs.attached["keyboard"];
  48001. if (keyboard)
  48002. keyboard.keysUp = value;
  48003. },
  48004. enumerable: true,
  48005. configurable: true
  48006. });
  48007. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48008. get: function () {
  48009. var keyboard = this.inputs.attached["keyboard"];
  48010. if (keyboard)
  48011. return keyboard.keysDown;
  48012. return [];
  48013. },
  48014. set: function (value) {
  48015. var keyboard = this.inputs.attached["keyboard"];
  48016. if (keyboard)
  48017. keyboard.keysDown = value;
  48018. },
  48019. enumerable: true,
  48020. configurable: true
  48021. });
  48022. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48023. get: function () {
  48024. var keyboard = this.inputs.attached["keyboard"];
  48025. if (keyboard)
  48026. return keyboard.keysLeft;
  48027. return [];
  48028. },
  48029. set: function (value) {
  48030. var keyboard = this.inputs.attached["keyboard"];
  48031. if (keyboard)
  48032. keyboard.keysLeft = value;
  48033. },
  48034. enumerable: true,
  48035. configurable: true
  48036. });
  48037. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48038. get: function () {
  48039. var keyboard = this.inputs.attached["keyboard"];
  48040. if (keyboard)
  48041. return keyboard.keysRight;
  48042. return [];
  48043. },
  48044. set: function (value) {
  48045. var keyboard = this.inputs.attached["keyboard"];
  48046. if (keyboard)
  48047. keyboard.keysRight = value;
  48048. },
  48049. enumerable: true,
  48050. configurable: true
  48051. });
  48052. // Controls
  48053. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48054. this.inputs.attachElement(element, noPreventDefault);
  48055. };
  48056. FreeCamera.prototype.detachControl = function (element) {
  48057. this.inputs.detachElement(element);
  48058. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48059. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48060. };
  48061. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48062. get: function () {
  48063. return this._collisionMask;
  48064. },
  48065. set: function (mask) {
  48066. this._collisionMask = !isNaN(mask) ? mask : -1;
  48067. },
  48068. enumerable: true,
  48069. configurable: true
  48070. });
  48071. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48072. var globalPosition;
  48073. if (this.parent) {
  48074. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48075. }
  48076. else {
  48077. globalPosition = this.position;
  48078. }
  48079. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48080. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48081. if (!this._collider) {
  48082. this._collider = new BABYLON.Collider();
  48083. }
  48084. this._collider._radius = this.ellipsoid;
  48085. this._collider.collisionMask = this._collisionMask;
  48086. //no need for clone, as long as gravity is not on.
  48087. var actualDisplacement = displacement;
  48088. //add gravity to the direction to prevent the dual-collision checking
  48089. if (this.applyGravity) {
  48090. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48091. actualDisplacement = displacement.add(this.getScene().gravity);
  48092. }
  48093. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48094. };
  48095. FreeCamera.prototype._checkInputs = function () {
  48096. if (!this._localDirection) {
  48097. this._localDirection = BABYLON.Vector3.Zero();
  48098. this._transformedDirection = BABYLON.Vector3.Zero();
  48099. }
  48100. this.inputs.checkInputs();
  48101. _super.prototype._checkInputs.call(this);
  48102. };
  48103. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48104. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48105. };
  48106. FreeCamera.prototype._updatePosition = function () {
  48107. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48108. this._collideWithWorld(this.cameraDirection);
  48109. }
  48110. else {
  48111. _super.prototype._updatePosition.call(this);
  48112. }
  48113. };
  48114. FreeCamera.prototype.dispose = function () {
  48115. this.inputs.clear();
  48116. _super.prototype.dispose.call(this);
  48117. };
  48118. FreeCamera.prototype.getClassName = function () {
  48119. return "FreeCamera";
  48120. };
  48121. __decorate([
  48122. BABYLON.serializeAsVector3()
  48123. ], FreeCamera.prototype, "ellipsoid", void 0);
  48124. __decorate([
  48125. BABYLON.serializeAsVector3()
  48126. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48127. __decorate([
  48128. BABYLON.serialize()
  48129. ], FreeCamera.prototype, "checkCollisions", void 0);
  48130. __decorate([
  48131. BABYLON.serialize()
  48132. ], FreeCamera.prototype, "applyGravity", void 0);
  48133. return FreeCamera;
  48134. }(BABYLON.TargetCamera));
  48135. BABYLON.FreeCamera = FreeCamera;
  48136. })(BABYLON || (BABYLON = {}));
  48137. //# sourceMappingURL=babylon.freeCamera.js.map
  48138. var BABYLON;
  48139. (function (BABYLON) {
  48140. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48141. function ArcRotateCameraKeyboardMoveInput() {
  48142. this._keys = new Array();
  48143. this.keysUp = [38];
  48144. this.keysDown = [40];
  48145. this.keysLeft = [37];
  48146. this.keysRight = [39];
  48147. this.keysReset = [220];
  48148. this.panningSensibility = 50.0;
  48149. this.zoomingSensibility = 25.0;
  48150. this.useAltToZoom = true;
  48151. }
  48152. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48153. var _this = this;
  48154. if (this._onCanvasBlurObserver) {
  48155. return;
  48156. }
  48157. this._scene = this.camera.getScene();
  48158. this._engine = this._scene.getEngine();
  48159. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48160. _this._keys = [];
  48161. });
  48162. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48163. var evt = info.event;
  48164. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48165. _this._ctrlPressed = evt.ctrlKey;
  48166. _this._altPressed = evt.altKey;
  48167. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48168. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48169. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48170. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48171. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48172. var index = _this._keys.indexOf(evt.keyCode);
  48173. if (index === -1) {
  48174. _this._keys.push(evt.keyCode);
  48175. }
  48176. if (evt.preventDefault) {
  48177. if (!noPreventDefault) {
  48178. evt.preventDefault();
  48179. }
  48180. }
  48181. }
  48182. }
  48183. else {
  48184. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48185. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48186. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48187. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48188. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48189. var index = _this._keys.indexOf(evt.keyCode);
  48190. if (index >= 0) {
  48191. _this._keys.splice(index, 1);
  48192. }
  48193. if (evt.preventDefault) {
  48194. if (!noPreventDefault) {
  48195. evt.preventDefault();
  48196. }
  48197. }
  48198. }
  48199. }
  48200. });
  48201. };
  48202. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48203. if (this._scene) {
  48204. if (this._onKeyboardObserver) {
  48205. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48206. }
  48207. if (this._onCanvasBlurObserver) {
  48208. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48209. }
  48210. this._onKeyboardObserver = null;
  48211. this._onCanvasBlurObserver = null;
  48212. }
  48213. this._keys = [];
  48214. };
  48215. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48216. if (this._onKeyboardObserver) {
  48217. var camera = this.camera;
  48218. for (var index = 0; index < this._keys.length; index++) {
  48219. var keyCode = this._keys[index];
  48220. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48221. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48222. camera.inertialPanningX -= 1 / this.panningSensibility;
  48223. }
  48224. else {
  48225. camera.inertialAlphaOffset -= 0.01;
  48226. }
  48227. }
  48228. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48229. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48230. camera.inertialPanningY += 1 / this.panningSensibility;
  48231. }
  48232. else if (this._altPressed && this.useAltToZoom) {
  48233. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48234. }
  48235. else {
  48236. camera.inertialBetaOffset -= 0.01;
  48237. }
  48238. }
  48239. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48240. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48241. camera.inertialPanningX += 1 / this.panningSensibility;
  48242. }
  48243. else {
  48244. camera.inertialAlphaOffset += 0.01;
  48245. }
  48246. }
  48247. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48248. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48249. camera.inertialPanningY -= 1 / this.panningSensibility;
  48250. }
  48251. else if (this._altPressed && this.useAltToZoom) {
  48252. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48253. }
  48254. else {
  48255. camera.inertialBetaOffset += 0.01;
  48256. }
  48257. }
  48258. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48259. camera.restoreState();
  48260. }
  48261. }
  48262. }
  48263. };
  48264. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48265. return "ArcRotateCameraKeyboardMoveInput";
  48266. };
  48267. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48268. return "keyboard";
  48269. };
  48270. __decorate([
  48271. BABYLON.serialize()
  48272. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48273. __decorate([
  48274. BABYLON.serialize()
  48275. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48276. __decorate([
  48277. BABYLON.serialize()
  48278. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48279. __decorate([
  48280. BABYLON.serialize()
  48281. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48282. __decorate([
  48283. BABYLON.serialize()
  48284. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48285. __decorate([
  48286. BABYLON.serialize()
  48287. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48288. __decorate([
  48289. BABYLON.serialize()
  48290. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48291. __decorate([
  48292. BABYLON.serialize()
  48293. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48294. return ArcRotateCameraKeyboardMoveInput;
  48295. }());
  48296. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48297. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48298. })(BABYLON || (BABYLON = {}));
  48299. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48300. var BABYLON;
  48301. (function (BABYLON) {
  48302. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48303. function ArcRotateCameraMouseWheelInput() {
  48304. this.wheelPrecision = 3.0;
  48305. /**
  48306. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48307. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48308. */
  48309. this.wheelDeltaPercentage = 0;
  48310. }
  48311. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48312. var _this = this;
  48313. this._wheel = function (p, s) {
  48314. //sanity check - this should be a PointerWheel event.
  48315. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48316. return;
  48317. var event = p.event;
  48318. var delta = 0;
  48319. if (event.wheelDelta) {
  48320. if (_this.wheelDeltaPercentage) {
  48321. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48322. if (event.wheelDelta > 0) {
  48323. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48324. }
  48325. else {
  48326. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48327. }
  48328. }
  48329. else {
  48330. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48331. }
  48332. }
  48333. else if (event.detail) {
  48334. delta = -event.detail / _this.wheelPrecision;
  48335. }
  48336. if (delta)
  48337. _this.camera.inertialRadiusOffset += delta;
  48338. if (event.preventDefault) {
  48339. if (!noPreventDefault) {
  48340. event.preventDefault();
  48341. }
  48342. }
  48343. };
  48344. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48345. };
  48346. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48347. if (this._observer && element) {
  48348. this.camera.getScene().onPointerObservable.remove(this._observer);
  48349. this._observer = null;
  48350. this._wheel = null;
  48351. }
  48352. };
  48353. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48354. return "ArcRotateCameraMouseWheelInput";
  48355. };
  48356. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48357. return "mousewheel";
  48358. };
  48359. __decorate([
  48360. BABYLON.serialize()
  48361. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48362. __decorate([
  48363. BABYLON.serialize()
  48364. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48365. return ArcRotateCameraMouseWheelInput;
  48366. }());
  48367. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48368. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48369. })(BABYLON || (BABYLON = {}));
  48370. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48371. var BABYLON;
  48372. (function (BABYLON) {
  48373. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48374. function ArcRotateCameraPointersInput() {
  48375. this.buttons = [0, 1, 2];
  48376. this.angularSensibilityX = 1000.0;
  48377. this.angularSensibilityY = 1000.0;
  48378. this.pinchPrecision = 12.0;
  48379. /**
  48380. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48381. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48382. */
  48383. this.pinchDeltaPercentage = 0;
  48384. this.panningSensibility = 1000.0;
  48385. this.multiTouchPanning = true;
  48386. this.multiTouchPanAndZoom = true;
  48387. this._isPanClick = false;
  48388. this.pinchInwards = true;
  48389. }
  48390. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48391. var _this = this;
  48392. var engine = this.camera.getEngine();
  48393. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48394. var pointA = null;
  48395. var pointB = null;
  48396. var previousPinchSquaredDistance = 0;
  48397. var initialDistance = 0;
  48398. var twoFingerActivityCount = 0;
  48399. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48400. this._pointerInput = function (p, s) {
  48401. var evt = p.event;
  48402. var isTouch = p.event.pointerType === "touch";
  48403. if (engine.isInVRExclusivePointerMode) {
  48404. return;
  48405. }
  48406. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48407. return;
  48408. }
  48409. var srcElement = (evt.srcElement || evt.target);
  48410. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48411. try {
  48412. srcElement.setPointerCapture(evt.pointerId);
  48413. }
  48414. catch (e) {
  48415. //Nothing to do with the error. Execution will continue.
  48416. }
  48417. // Manage panning with pan button click
  48418. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48419. // manage pointers
  48420. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48421. if (pointA === null) {
  48422. pointA = cacheSoloPointer;
  48423. }
  48424. else if (pointB === null) {
  48425. pointB = cacheSoloPointer;
  48426. }
  48427. if (!noPreventDefault) {
  48428. evt.preventDefault();
  48429. element.focus();
  48430. }
  48431. }
  48432. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48433. _this.camera.restoreState();
  48434. }
  48435. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48436. try {
  48437. srcElement.releasePointerCapture(evt.pointerId);
  48438. }
  48439. catch (e) {
  48440. //Nothing to do with the error.
  48441. }
  48442. cacheSoloPointer = null;
  48443. previousPinchSquaredDistance = 0;
  48444. previousMultiTouchPanPosition.isPaning = false;
  48445. previousMultiTouchPanPosition.isPinching = false;
  48446. twoFingerActivityCount = 0;
  48447. initialDistance = 0;
  48448. if (!isTouch) {
  48449. pointB = null; // Mouse and pen are mono pointer
  48450. }
  48451. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48452. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48453. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48454. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48455. if (engine._badOS) {
  48456. pointA = pointB = null;
  48457. }
  48458. else {
  48459. //only remove the impacted pointer in case of multitouch allowing on most
  48460. //platforms switching from rotate to zoom and pan seamlessly.
  48461. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48462. pointA = pointB;
  48463. pointB = null;
  48464. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48465. }
  48466. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48467. pointB = null;
  48468. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48469. }
  48470. else {
  48471. pointA = pointB = null;
  48472. }
  48473. }
  48474. if (!noPreventDefault) {
  48475. evt.preventDefault();
  48476. }
  48477. }
  48478. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48479. if (!noPreventDefault) {
  48480. evt.preventDefault();
  48481. }
  48482. // One button down
  48483. if (pointA && pointB === null && cacheSoloPointer) {
  48484. if (_this.panningSensibility !== 0 &&
  48485. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48486. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48487. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48488. }
  48489. else {
  48490. var offsetX = evt.clientX - cacheSoloPointer.x;
  48491. var offsetY = evt.clientY - cacheSoloPointer.y;
  48492. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48493. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48494. }
  48495. cacheSoloPointer.x = evt.clientX;
  48496. cacheSoloPointer.y = evt.clientY;
  48497. }
  48498. // Two buttons down: pinch/pan
  48499. else if (pointA && pointB) {
  48500. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48501. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48502. ed.x = evt.clientX;
  48503. ed.y = evt.clientY;
  48504. var direction = _this.pinchInwards ? 1 : -1;
  48505. var distX = pointA.x - pointB.x;
  48506. var distY = pointA.y - pointB.y;
  48507. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48508. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48509. if (previousPinchSquaredDistance === 0) {
  48510. initialDistance = pinchDistance;
  48511. previousPinchSquaredDistance = pinchSquaredDistance;
  48512. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48513. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48514. return;
  48515. }
  48516. if (_this.multiTouchPanAndZoom) {
  48517. if (_this.pinchDeltaPercentage) {
  48518. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48519. }
  48520. else {
  48521. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48522. (_this.pinchPrecision *
  48523. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48524. direction);
  48525. }
  48526. if (_this.panningSensibility !== 0) {
  48527. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48528. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48529. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48530. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48531. previousMultiTouchPanPosition.x = pointersCenterX;
  48532. previousMultiTouchPanPosition.y = pointersCenterY;
  48533. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48534. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48535. }
  48536. }
  48537. else {
  48538. twoFingerActivityCount++;
  48539. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48540. if (_this.pinchDeltaPercentage) {
  48541. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48542. }
  48543. else {
  48544. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48545. (_this.pinchPrecision *
  48546. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48547. direction);
  48548. }
  48549. previousMultiTouchPanPosition.isPaning = false;
  48550. previousMultiTouchPanPosition.isPinching = true;
  48551. }
  48552. else {
  48553. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48554. if (!previousMultiTouchPanPosition.isPaning) {
  48555. previousMultiTouchPanPosition.isPaning = true;
  48556. previousMultiTouchPanPosition.isPinching = false;
  48557. previousMultiTouchPanPosition.x = ed.x;
  48558. previousMultiTouchPanPosition.y = ed.y;
  48559. return;
  48560. }
  48561. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48562. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48563. }
  48564. }
  48565. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48566. previousMultiTouchPanPosition.x = ed.x;
  48567. previousMultiTouchPanPosition.y = ed.y;
  48568. }
  48569. }
  48570. previousPinchSquaredDistance = pinchSquaredDistance;
  48571. }
  48572. }
  48573. };
  48574. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48575. this._onContextMenu = function (evt) {
  48576. evt.preventDefault();
  48577. };
  48578. if (!this.camera._useCtrlForPanning) {
  48579. element.addEventListener("contextmenu", this._onContextMenu, false);
  48580. }
  48581. this._onLostFocus = function () {
  48582. //this._keys = [];
  48583. pointA = pointB = null;
  48584. previousPinchSquaredDistance = 0;
  48585. previousMultiTouchPanPosition.isPaning = false;
  48586. previousMultiTouchPanPosition.isPinching = false;
  48587. twoFingerActivityCount = 0;
  48588. cacheSoloPointer = null;
  48589. initialDistance = 0;
  48590. };
  48591. this._onMouseMove = function (evt) {
  48592. if (!engine.isPointerLock) {
  48593. return;
  48594. }
  48595. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48596. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48597. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48598. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48599. if (!noPreventDefault) {
  48600. evt.preventDefault();
  48601. }
  48602. };
  48603. this._onGestureStart = function (e) {
  48604. if (window.MSGesture === undefined) {
  48605. return;
  48606. }
  48607. if (!_this._MSGestureHandler) {
  48608. _this._MSGestureHandler = new MSGesture();
  48609. _this._MSGestureHandler.target = element;
  48610. }
  48611. _this._MSGestureHandler.addPointer(e.pointerId);
  48612. };
  48613. this._onGesture = function (e) {
  48614. _this.camera.radius *= e.scale;
  48615. if (e.preventDefault) {
  48616. if (!noPreventDefault) {
  48617. e.stopPropagation();
  48618. e.preventDefault();
  48619. }
  48620. }
  48621. };
  48622. element.addEventListener("mousemove", this._onMouseMove, false);
  48623. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48624. element.addEventListener("MSGestureChange", this._onGesture, false);
  48625. BABYLON.Tools.RegisterTopRootEvents([
  48626. { name: "blur", handler: this._onLostFocus }
  48627. ]);
  48628. };
  48629. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48630. if (this._onLostFocus) {
  48631. BABYLON.Tools.UnregisterTopRootEvents([
  48632. { name: "blur", handler: this._onLostFocus }
  48633. ]);
  48634. }
  48635. if (element && this._observer) {
  48636. this.camera.getScene().onPointerObservable.remove(this._observer);
  48637. this._observer = null;
  48638. if (this._onContextMenu) {
  48639. element.removeEventListener("contextmenu", this._onContextMenu);
  48640. }
  48641. if (this._onMouseMove) {
  48642. element.removeEventListener("mousemove", this._onMouseMove);
  48643. }
  48644. if (this._onGestureStart) {
  48645. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48646. }
  48647. if (this._onGesture) {
  48648. element.removeEventListener("MSGestureChange", this._onGesture);
  48649. }
  48650. this._isPanClick = false;
  48651. this.pinchInwards = true;
  48652. this._onMouseMove = null;
  48653. this._onGestureStart = null;
  48654. this._onGesture = null;
  48655. this._MSGestureHandler = null;
  48656. this._onLostFocus = null;
  48657. this._onContextMenu = null;
  48658. }
  48659. };
  48660. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48661. return "ArcRotateCameraPointersInput";
  48662. };
  48663. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48664. return "pointers";
  48665. };
  48666. __decorate([
  48667. BABYLON.serialize()
  48668. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48669. __decorate([
  48670. BABYLON.serialize()
  48671. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48672. __decorate([
  48673. BABYLON.serialize()
  48674. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48675. __decorate([
  48676. BABYLON.serialize()
  48677. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48678. __decorate([
  48679. BABYLON.serialize()
  48680. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48681. __decorate([
  48682. BABYLON.serialize()
  48683. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48684. __decorate([
  48685. BABYLON.serialize()
  48686. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48687. __decorate([
  48688. BABYLON.serialize()
  48689. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48690. return ArcRotateCameraPointersInput;
  48691. }());
  48692. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48693. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48694. })(BABYLON || (BABYLON = {}));
  48695. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48696. var BABYLON;
  48697. (function (BABYLON) {
  48698. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48699. __extends(ArcRotateCameraInputsManager, _super);
  48700. function ArcRotateCameraInputsManager(camera) {
  48701. return _super.call(this, camera) || this;
  48702. }
  48703. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48704. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48705. return this;
  48706. };
  48707. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48708. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48709. return this;
  48710. };
  48711. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48712. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48713. return this;
  48714. };
  48715. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48716. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48717. return this;
  48718. };
  48719. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48720. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48721. return this;
  48722. };
  48723. return ArcRotateCameraInputsManager;
  48724. }(BABYLON.CameraInputsManager));
  48725. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48726. })(BABYLON || (BABYLON = {}));
  48727. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48728. var BABYLON;
  48729. (function (BABYLON) {
  48730. var ArcRotateCamera = /** @class */ (function (_super) {
  48731. __extends(ArcRotateCamera, _super);
  48732. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48733. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48734. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48735. _this.inertialAlphaOffset = 0;
  48736. _this.inertialBetaOffset = 0;
  48737. _this.inertialRadiusOffset = 0;
  48738. _this.lowerAlphaLimit = null;
  48739. _this.upperAlphaLimit = null;
  48740. _this.lowerBetaLimit = 0.01;
  48741. _this.upperBetaLimit = Math.PI;
  48742. _this.lowerRadiusLimit = null;
  48743. _this.upperRadiusLimit = null;
  48744. _this.inertialPanningX = 0;
  48745. _this.inertialPanningY = 0;
  48746. _this.pinchToPanMaxDistance = 20;
  48747. _this.panningDistanceLimit = null;
  48748. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48749. _this.panningInertia = 0.9;
  48750. //-- end properties for backward compatibility for inputs
  48751. _this.zoomOnFactor = 1;
  48752. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48753. _this.allowUpsideDown = true;
  48754. _this._viewMatrix = new BABYLON.Matrix();
  48755. // Panning
  48756. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48757. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48758. _this.checkCollisions = false;
  48759. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48760. _this._previousPosition = BABYLON.Vector3.Zero();
  48761. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48762. _this._newPosition = BABYLON.Vector3.Zero();
  48763. _this._computationVector = BABYLON.Vector3.Zero();
  48764. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48765. if (collidedMesh === void 0) { collidedMesh = null; }
  48766. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48767. newPosition.multiplyInPlace(_this._collider._radius);
  48768. }
  48769. if (!collidedMesh) {
  48770. _this._previousPosition.copyFrom(_this.position);
  48771. }
  48772. else {
  48773. _this.setPosition(newPosition);
  48774. if (_this.onCollide) {
  48775. _this.onCollide(collidedMesh);
  48776. }
  48777. }
  48778. // Recompute because of constraints
  48779. var cosa = Math.cos(_this.alpha);
  48780. var sina = Math.sin(_this.alpha);
  48781. var cosb = Math.cos(_this.beta);
  48782. var sinb = Math.sin(_this.beta);
  48783. if (sinb === 0) {
  48784. sinb = 0.0001;
  48785. }
  48786. var target = _this._getTargetPosition();
  48787. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48788. target.addToRef(_this._computationVector, _this._newPosition);
  48789. _this.position.copyFrom(_this._newPosition);
  48790. var up = _this.upVector;
  48791. if (_this.allowUpsideDown && _this.beta < 0) {
  48792. up = up.clone();
  48793. up = up.negate();
  48794. }
  48795. _this._computeViewMatrix(_this.position, target, up);
  48796. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48797. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48798. _this._collisionTriggered = false;
  48799. };
  48800. _this._target = BABYLON.Vector3.Zero();
  48801. if (target) {
  48802. _this.setTarget(target);
  48803. }
  48804. _this.alpha = alpha;
  48805. _this.beta = beta;
  48806. _this.radius = radius;
  48807. _this.getViewMatrix();
  48808. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48809. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48810. return _this;
  48811. }
  48812. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48813. get: function () {
  48814. return this._target;
  48815. },
  48816. set: function (value) {
  48817. this.setTarget(value);
  48818. },
  48819. enumerable: true,
  48820. configurable: true
  48821. });
  48822. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48823. //-- begin properties for backward compatibility for inputs
  48824. get: function () {
  48825. var pointers = this.inputs.attached["pointers"];
  48826. if (pointers)
  48827. return pointers.angularSensibilityX;
  48828. return 0;
  48829. },
  48830. set: function (value) {
  48831. var pointers = this.inputs.attached["pointers"];
  48832. if (pointers) {
  48833. pointers.angularSensibilityX = value;
  48834. }
  48835. },
  48836. enumerable: true,
  48837. configurable: true
  48838. });
  48839. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48840. get: function () {
  48841. var pointers = this.inputs.attached["pointers"];
  48842. if (pointers)
  48843. return pointers.angularSensibilityY;
  48844. return 0;
  48845. },
  48846. set: function (value) {
  48847. var pointers = this.inputs.attached["pointers"];
  48848. if (pointers) {
  48849. pointers.angularSensibilityY = value;
  48850. }
  48851. },
  48852. enumerable: true,
  48853. configurable: true
  48854. });
  48855. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48856. get: function () {
  48857. var pointers = this.inputs.attached["pointers"];
  48858. if (pointers)
  48859. return pointers.pinchPrecision;
  48860. return 0;
  48861. },
  48862. set: function (value) {
  48863. var pointers = this.inputs.attached["pointers"];
  48864. if (pointers) {
  48865. pointers.pinchPrecision = value;
  48866. }
  48867. },
  48868. enumerable: true,
  48869. configurable: true
  48870. });
  48871. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48872. get: function () {
  48873. var pointers = this.inputs.attached["pointers"];
  48874. if (pointers)
  48875. return pointers.pinchDeltaPercentage;
  48876. return 0;
  48877. },
  48878. set: function (value) {
  48879. var pointers = this.inputs.attached["pointers"];
  48880. if (pointers) {
  48881. pointers.pinchDeltaPercentage = value;
  48882. }
  48883. },
  48884. enumerable: true,
  48885. configurable: true
  48886. });
  48887. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48888. get: function () {
  48889. var pointers = this.inputs.attached["pointers"];
  48890. if (pointers)
  48891. return pointers.panningSensibility;
  48892. return 0;
  48893. },
  48894. set: function (value) {
  48895. var pointers = this.inputs.attached["pointers"];
  48896. if (pointers) {
  48897. pointers.panningSensibility = value;
  48898. }
  48899. },
  48900. enumerable: true,
  48901. configurable: true
  48902. });
  48903. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48904. get: function () {
  48905. var keyboard = this.inputs.attached["keyboard"];
  48906. if (keyboard)
  48907. return keyboard.keysUp;
  48908. return [];
  48909. },
  48910. set: function (value) {
  48911. var keyboard = this.inputs.attached["keyboard"];
  48912. if (keyboard)
  48913. keyboard.keysUp = value;
  48914. },
  48915. enumerable: true,
  48916. configurable: true
  48917. });
  48918. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48919. get: function () {
  48920. var keyboard = this.inputs.attached["keyboard"];
  48921. if (keyboard)
  48922. return keyboard.keysDown;
  48923. return [];
  48924. },
  48925. set: function (value) {
  48926. var keyboard = this.inputs.attached["keyboard"];
  48927. if (keyboard)
  48928. keyboard.keysDown = value;
  48929. },
  48930. enumerable: true,
  48931. configurable: true
  48932. });
  48933. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48934. get: function () {
  48935. var keyboard = this.inputs.attached["keyboard"];
  48936. if (keyboard)
  48937. return keyboard.keysLeft;
  48938. return [];
  48939. },
  48940. set: function (value) {
  48941. var keyboard = this.inputs.attached["keyboard"];
  48942. if (keyboard)
  48943. keyboard.keysLeft = value;
  48944. },
  48945. enumerable: true,
  48946. configurable: true
  48947. });
  48948. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48949. get: function () {
  48950. var keyboard = this.inputs.attached["keyboard"];
  48951. if (keyboard)
  48952. return keyboard.keysRight;
  48953. return [];
  48954. },
  48955. set: function (value) {
  48956. var keyboard = this.inputs.attached["keyboard"];
  48957. if (keyboard)
  48958. keyboard.keysRight = value;
  48959. },
  48960. enumerable: true,
  48961. configurable: true
  48962. });
  48963. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48964. get: function () {
  48965. var mousewheel = this.inputs.attached["mousewheel"];
  48966. if (mousewheel)
  48967. return mousewheel.wheelPrecision;
  48968. return 0;
  48969. },
  48970. set: function (value) {
  48971. var mousewheel = this.inputs.attached["mousewheel"];
  48972. if (mousewheel)
  48973. mousewheel.wheelPrecision = value;
  48974. },
  48975. enumerable: true,
  48976. configurable: true
  48977. });
  48978. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48979. get: function () {
  48980. var mousewheel = this.inputs.attached["mousewheel"];
  48981. if (mousewheel)
  48982. return mousewheel.wheelDeltaPercentage;
  48983. return 0;
  48984. },
  48985. set: function (value) {
  48986. var mousewheel = this.inputs.attached["mousewheel"];
  48987. if (mousewheel)
  48988. mousewheel.wheelDeltaPercentage = value;
  48989. },
  48990. enumerable: true,
  48991. configurable: true
  48992. });
  48993. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48994. get: function () {
  48995. return this._bouncingBehavior;
  48996. },
  48997. enumerable: true,
  48998. configurable: true
  48999. });
  49000. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49001. get: function () {
  49002. return this._bouncingBehavior != null;
  49003. },
  49004. set: function (value) {
  49005. if (value === this.useBouncingBehavior) {
  49006. return;
  49007. }
  49008. if (value) {
  49009. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49010. this.addBehavior(this._bouncingBehavior);
  49011. }
  49012. else if (this._bouncingBehavior) {
  49013. this.removeBehavior(this._bouncingBehavior);
  49014. this._bouncingBehavior = null;
  49015. }
  49016. },
  49017. enumerable: true,
  49018. configurable: true
  49019. });
  49020. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49021. get: function () {
  49022. return this._framingBehavior;
  49023. },
  49024. enumerable: true,
  49025. configurable: true
  49026. });
  49027. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49028. get: function () {
  49029. return this._framingBehavior != null;
  49030. },
  49031. set: function (value) {
  49032. if (value === this.useFramingBehavior) {
  49033. return;
  49034. }
  49035. if (value) {
  49036. this._framingBehavior = new BABYLON.FramingBehavior();
  49037. this.addBehavior(this._framingBehavior);
  49038. }
  49039. else if (this._framingBehavior) {
  49040. this.removeBehavior(this._framingBehavior);
  49041. this._framingBehavior = null;
  49042. }
  49043. },
  49044. enumerable: true,
  49045. configurable: true
  49046. });
  49047. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49048. get: function () {
  49049. return this._autoRotationBehavior;
  49050. },
  49051. enumerable: true,
  49052. configurable: true
  49053. });
  49054. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49055. get: function () {
  49056. return this._autoRotationBehavior != null;
  49057. },
  49058. set: function (value) {
  49059. if (value === this.useAutoRotationBehavior) {
  49060. return;
  49061. }
  49062. if (value) {
  49063. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49064. this.addBehavior(this._autoRotationBehavior);
  49065. }
  49066. else if (this._autoRotationBehavior) {
  49067. this.removeBehavior(this._autoRotationBehavior);
  49068. this._autoRotationBehavior = null;
  49069. }
  49070. },
  49071. enumerable: true,
  49072. configurable: true
  49073. });
  49074. // Cache
  49075. ArcRotateCamera.prototype._initCache = function () {
  49076. _super.prototype._initCache.call(this);
  49077. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49078. this._cache.alpha = undefined;
  49079. this._cache.beta = undefined;
  49080. this._cache.radius = undefined;
  49081. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49082. };
  49083. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49084. if (!ignoreParentClass) {
  49085. _super.prototype._updateCache.call(this);
  49086. }
  49087. this._cache._target.copyFrom(this._getTargetPosition());
  49088. this._cache.alpha = this.alpha;
  49089. this._cache.beta = this.beta;
  49090. this._cache.radius = this.radius;
  49091. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49092. };
  49093. ArcRotateCamera.prototype._getTargetPosition = function () {
  49094. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49095. var pos = this._targetHost.getAbsolutePosition();
  49096. if (this._targetBoundingCenter) {
  49097. pos.addToRef(this._targetBoundingCenter, this._target);
  49098. }
  49099. else {
  49100. this._target.copyFrom(pos);
  49101. }
  49102. }
  49103. var lockedTargetPosition = this._getLockedTargetPosition();
  49104. if (lockedTargetPosition) {
  49105. return lockedTargetPosition;
  49106. }
  49107. return this._target;
  49108. };
  49109. ArcRotateCamera.prototype.storeState = function () {
  49110. this._storedAlpha = this.alpha;
  49111. this._storedBeta = this.beta;
  49112. this._storedRadius = this.radius;
  49113. this._storedTarget = this._getTargetPosition().clone();
  49114. return _super.prototype.storeState.call(this);
  49115. };
  49116. /**
  49117. * Restored camera state. You must call storeState() first
  49118. */
  49119. ArcRotateCamera.prototype._restoreStateValues = function () {
  49120. if (!_super.prototype._restoreStateValues.call(this)) {
  49121. return false;
  49122. }
  49123. this.alpha = this._storedAlpha;
  49124. this.beta = this._storedBeta;
  49125. this.radius = this._storedRadius;
  49126. this.setTarget(this._storedTarget.clone());
  49127. this.inertialAlphaOffset = 0;
  49128. this.inertialBetaOffset = 0;
  49129. this.inertialRadiusOffset = 0;
  49130. this.inertialPanningX = 0;
  49131. this.inertialPanningY = 0;
  49132. return true;
  49133. };
  49134. // Synchronized
  49135. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49136. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49137. return false;
  49138. return this._cache._target.equals(this._getTargetPosition())
  49139. && this._cache.alpha === this.alpha
  49140. && this._cache.beta === this.beta
  49141. && this._cache.radius === this.radius
  49142. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49143. };
  49144. // Methods
  49145. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49146. var _this = this;
  49147. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49148. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49149. this._useCtrlForPanning = useCtrlForPanning;
  49150. this._panningMouseButton = panningMouseButton;
  49151. this.inputs.attachElement(element, noPreventDefault);
  49152. this._reset = function () {
  49153. _this.inertialAlphaOffset = 0;
  49154. _this.inertialBetaOffset = 0;
  49155. _this.inertialRadiusOffset = 0;
  49156. _this.inertialPanningX = 0;
  49157. _this.inertialPanningY = 0;
  49158. };
  49159. };
  49160. ArcRotateCamera.prototype.detachControl = function (element) {
  49161. this.inputs.detachElement(element);
  49162. if (this._reset) {
  49163. this._reset();
  49164. }
  49165. };
  49166. ArcRotateCamera.prototype._checkInputs = function () {
  49167. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49168. if (this._collisionTriggered) {
  49169. return;
  49170. }
  49171. this.inputs.checkInputs();
  49172. // Inertia
  49173. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49174. var inertialAlphaOffset = this.inertialAlphaOffset;
  49175. if (this.beta <= 0)
  49176. inertialAlphaOffset *= -1;
  49177. if (this.getScene().useRightHandedSystem)
  49178. inertialAlphaOffset *= -1;
  49179. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49180. inertialAlphaOffset *= -1;
  49181. this.alpha += inertialAlphaOffset;
  49182. this.beta += this.inertialBetaOffset;
  49183. this.radius -= this.inertialRadiusOffset;
  49184. this.inertialAlphaOffset *= this.inertia;
  49185. this.inertialBetaOffset *= this.inertia;
  49186. this.inertialRadiusOffset *= this.inertia;
  49187. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49188. this.inertialAlphaOffset = 0;
  49189. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49190. this.inertialBetaOffset = 0;
  49191. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49192. this.inertialRadiusOffset = 0;
  49193. }
  49194. // Panning inertia
  49195. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49196. if (!this._localDirection) {
  49197. this._localDirection = BABYLON.Vector3.Zero();
  49198. this._transformedDirection = BABYLON.Vector3.Zero();
  49199. }
  49200. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49201. this._localDirection.multiplyInPlace(this.panningAxis);
  49202. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49203. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49204. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49205. if (!this.panningAxis.y) {
  49206. this._transformedDirection.y = 0;
  49207. }
  49208. if (!this._targetHost) {
  49209. if (this.panningDistanceLimit) {
  49210. this._transformedDirection.addInPlace(this._target);
  49211. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49212. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49213. this._target.copyFrom(this._transformedDirection);
  49214. }
  49215. }
  49216. else {
  49217. this._target.addInPlace(this._transformedDirection);
  49218. }
  49219. }
  49220. this.inertialPanningX *= this.panningInertia;
  49221. this.inertialPanningY *= this.panningInertia;
  49222. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49223. this.inertialPanningX = 0;
  49224. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49225. this.inertialPanningY = 0;
  49226. }
  49227. // Limits
  49228. this._checkLimits();
  49229. _super.prototype._checkInputs.call(this);
  49230. };
  49231. ArcRotateCamera.prototype._checkLimits = function () {
  49232. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49233. if (this.allowUpsideDown && this.beta > Math.PI) {
  49234. this.beta = this.beta - (2 * Math.PI);
  49235. }
  49236. }
  49237. else {
  49238. if (this.beta < this.lowerBetaLimit) {
  49239. this.beta = this.lowerBetaLimit;
  49240. }
  49241. }
  49242. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49243. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49244. this.beta = this.beta + (2 * Math.PI);
  49245. }
  49246. }
  49247. else {
  49248. if (this.beta > this.upperBetaLimit) {
  49249. this.beta = this.upperBetaLimit;
  49250. }
  49251. }
  49252. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49253. this.alpha = this.lowerAlphaLimit;
  49254. }
  49255. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49256. this.alpha = this.upperAlphaLimit;
  49257. }
  49258. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49259. this.radius = this.lowerRadiusLimit;
  49260. }
  49261. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49262. this.radius = this.upperRadiusLimit;
  49263. }
  49264. };
  49265. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49266. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49267. this.radius = this._computationVector.length();
  49268. if (this.radius === 0) {
  49269. this.radius = 0.0001; // Just to avoid division by zero
  49270. }
  49271. // Alpha
  49272. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49273. if (this._computationVector.z < 0) {
  49274. this.alpha = 2 * Math.PI - this.alpha;
  49275. }
  49276. // Beta
  49277. this.beta = Math.acos(this._computationVector.y / this.radius);
  49278. this._checkLimits();
  49279. };
  49280. ArcRotateCamera.prototype.setPosition = function (position) {
  49281. if (this.position.equals(position)) {
  49282. return;
  49283. }
  49284. this.position.copyFrom(position);
  49285. this.rebuildAnglesAndRadius();
  49286. };
  49287. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49288. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49289. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49290. if (target.getBoundingInfo) {
  49291. if (toBoundingCenter) {
  49292. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49293. }
  49294. else {
  49295. this._targetBoundingCenter = null;
  49296. }
  49297. this._targetHost = target;
  49298. this._target = this._getTargetPosition();
  49299. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49300. }
  49301. else {
  49302. var newTarget = target;
  49303. var currentTarget = this._getTargetPosition();
  49304. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49305. return;
  49306. }
  49307. this._targetHost = null;
  49308. this._target = newTarget;
  49309. this._targetBoundingCenter = null;
  49310. this.onMeshTargetChangedObservable.notifyObservers(null);
  49311. }
  49312. this.rebuildAnglesAndRadius();
  49313. };
  49314. ArcRotateCamera.prototype._getViewMatrix = function () {
  49315. // Compute
  49316. var cosa = Math.cos(this.alpha);
  49317. var sina = Math.sin(this.alpha);
  49318. var cosb = Math.cos(this.beta);
  49319. var sinb = Math.sin(this.beta);
  49320. if (sinb === 0) {
  49321. sinb = 0.0001;
  49322. }
  49323. var target = this._getTargetPosition();
  49324. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49325. target.addToRef(this._computationVector, this._newPosition);
  49326. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49327. if (!this._collider) {
  49328. this._collider = new BABYLON.Collider();
  49329. }
  49330. this._collider._radius = this.collisionRadius;
  49331. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49332. this._collisionTriggered = true;
  49333. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49334. }
  49335. else {
  49336. this.position.copyFrom(this._newPosition);
  49337. var up = this.upVector;
  49338. if (this.allowUpsideDown && sinb < 0) {
  49339. up = up.clone();
  49340. up = up.negate();
  49341. }
  49342. this._computeViewMatrix(this.position, target, up);
  49343. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49344. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49345. }
  49346. this._currentTarget = target;
  49347. return this._viewMatrix;
  49348. };
  49349. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49350. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49351. meshes = meshes || this.getScene().meshes;
  49352. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49353. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49354. this.radius = distance * this.zoomOnFactor;
  49355. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49356. };
  49357. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49358. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49359. var meshesOrMinMaxVector;
  49360. var distance;
  49361. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49362. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49363. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49364. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49365. }
  49366. else { //minMaxVector and distance
  49367. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49368. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49369. distance = minMaxVectorAndDistance.distance;
  49370. }
  49371. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49372. if (!doNotUpdateMaxZ) {
  49373. this.maxZ = distance * 2;
  49374. }
  49375. };
  49376. /**
  49377. * @override
  49378. * Override Camera.createRigCamera
  49379. */
  49380. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49381. var alphaShift = 0;
  49382. switch (this.cameraRigMode) {
  49383. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49384. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49385. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49386. case BABYLON.Camera.RIG_MODE_VR:
  49387. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49388. break;
  49389. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49390. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49391. break;
  49392. }
  49393. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49394. rigCam._cameraRigParams = {};
  49395. return rigCam;
  49396. };
  49397. /**
  49398. * @override
  49399. * Override Camera._updateRigCameras
  49400. */
  49401. ArcRotateCamera.prototype._updateRigCameras = function () {
  49402. var camLeft = this._rigCameras[0];
  49403. var camRight = this._rigCameras[1];
  49404. camLeft.beta = camRight.beta = this.beta;
  49405. camLeft.radius = camRight.radius = this.radius;
  49406. switch (this.cameraRigMode) {
  49407. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49408. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49409. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49410. case BABYLON.Camera.RIG_MODE_VR:
  49411. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49412. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49413. break;
  49414. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49415. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49416. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49417. break;
  49418. }
  49419. _super.prototype._updateRigCameras.call(this);
  49420. };
  49421. ArcRotateCamera.prototype.dispose = function () {
  49422. this.inputs.clear();
  49423. _super.prototype.dispose.call(this);
  49424. };
  49425. ArcRotateCamera.prototype.getClassName = function () {
  49426. return "ArcRotateCamera";
  49427. };
  49428. __decorate([
  49429. BABYLON.serialize()
  49430. ], ArcRotateCamera.prototype, "alpha", void 0);
  49431. __decorate([
  49432. BABYLON.serialize()
  49433. ], ArcRotateCamera.prototype, "beta", void 0);
  49434. __decorate([
  49435. BABYLON.serialize()
  49436. ], ArcRotateCamera.prototype, "radius", void 0);
  49437. __decorate([
  49438. BABYLON.serializeAsVector3("target")
  49439. ], ArcRotateCamera.prototype, "_target", void 0);
  49440. __decorate([
  49441. BABYLON.serialize()
  49442. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49443. __decorate([
  49444. BABYLON.serialize()
  49445. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49446. __decorate([
  49447. BABYLON.serialize()
  49448. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49449. __decorate([
  49450. BABYLON.serialize()
  49451. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49452. __decorate([
  49453. BABYLON.serialize()
  49454. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49455. __decorate([
  49456. BABYLON.serialize()
  49457. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49458. __decorate([
  49459. BABYLON.serialize()
  49460. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49461. __decorate([
  49462. BABYLON.serialize()
  49463. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49464. __decorate([
  49465. BABYLON.serialize()
  49466. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49467. __decorate([
  49468. BABYLON.serialize()
  49469. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49470. __decorate([
  49471. BABYLON.serialize()
  49472. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49473. __decorate([
  49474. BABYLON.serialize()
  49475. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49476. __decorate([
  49477. BABYLON.serialize()
  49478. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49479. __decorate([
  49480. BABYLON.serializeAsVector3()
  49481. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49482. __decorate([
  49483. BABYLON.serialize()
  49484. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49485. __decorate([
  49486. BABYLON.serialize()
  49487. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49488. __decorate([
  49489. BABYLON.serialize()
  49490. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49491. return ArcRotateCamera;
  49492. }(BABYLON.TargetCamera));
  49493. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49494. })(BABYLON || (BABYLON = {}));
  49495. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49496. var BABYLON;
  49497. (function (BABYLON) {
  49498. /**
  49499. * The HemisphericLight simulates the ambient environment light,
  49500. * so the passed direction is the light reflection direction, not the incoming direction.
  49501. */
  49502. var HemisphericLight = /** @class */ (function (_super) {
  49503. __extends(HemisphericLight, _super);
  49504. /**
  49505. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49506. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49507. * The HemisphericLight can't cast shadows.
  49508. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49509. * @param name The friendly name of the light
  49510. * @param direction The direction of the light reflection
  49511. * @param scene The scene the light belongs to
  49512. */
  49513. function HemisphericLight(name, direction, scene) {
  49514. var _this = _super.call(this, name, scene) || this;
  49515. /**
  49516. * The groundColor is the light in the opposite direction to the one specified during creation.
  49517. * 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.
  49518. */
  49519. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49520. _this.direction = direction || BABYLON.Vector3.Up();
  49521. return _this;
  49522. }
  49523. HemisphericLight.prototype._buildUniformLayout = function () {
  49524. this._uniformBuffer.addUniform("vLightData", 4);
  49525. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49526. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49527. this._uniformBuffer.addUniform("vLightGround", 3);
  49528. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49529. this._uniformBuffer.addUniform("depthValues", 2);
  49530. this._uniformBuffer.create();
  49531. };
  49532. /**
  49533. * Returns the string "HemisphericLight".
  49534. * @return The class name
  49535. */
  49536. HemisphericLight.prototype.getClassName = function () {
  49537. return "HemisphericLight";
  49538. };
  49539. /**
  49540. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49541. * Returns the updated direction.
  49542. * @param target The target the direction should point to
  49543. * @return The computed direction
  49544. */
  49545. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49546. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49547. return this.direction;
  49548. };
  49549. /**
  49550. * Returns the shadow generator associated to the light.
  49551. * @returns Always null for hemispheric lights because it does not support shadows.
  49552. */
  49553. HemisphericLight.prototype.getShadowGenerator = function () {
  49554. return null;
  49555. };
  49556. /**
  49557. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49558. * @param effect The effect to update
  49559. * @param lightIndex The index of the light in the effect to update
  49560. * @returns The hemispheric light
  49561. */
  49562. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49563. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49564. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49565. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49566. return this;
  49567. };
  49568. /**
  49569. * @hidden internal use only.
  49570. */
  49571. HemisphericLight.prototype._getWorldMatrix = function () {
  49572. if (!this._worldMatrix) {
  49573. this._worldMatrix = BABYLON.Matrix.Identity();
  49574. }
  49575. return this._worldMatrix;
  49576. };
  49577. /**
  49578. * Returns the integer 3.
  49579. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49580. */
  49581. HemisphericLight.prototype.getTypeID = function () {
  49582. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49583. };
  49584. __decorate([
  49585. BABYLON.serializeAsColor3()
  49586. ], HemisphericLight.prototype, "groundColor", void 0);
  49587. __decorate([
  49588. BABYLON.serializeAsVector3()
  49589. ], HemisphericLight.prototype, "direction", void 0);
  49590. return HemisphericLight;
  49591. }(BABYLON.Light));
  49592. BABYLON.HemisphericLight = HemisphericLight;
  49593. })(BABYLON || (BABYLON = {}));
  49594. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49595. var BABYLON;
  49596. (function (BABYLON) {
  49597. /**
  49598. * Base implementation IShadowLight
  49599. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49600. */
  49601. var ShadowLight = /** @class */ (function (_super) {
  49602. __extends(ShadowLight, _super);
  49603. function ShadowLight() {
  49604. var _this = _super !== null && _super.apply(this, arguments) || this;
  49605. _this._needProjectionMatrixCompute = true;
  49606. return _this;
  49607. }
  49608. ShadowLight.prototype._setPosition = function (value) {
  49609. this._position = value;
  49610. };
  49611. Object.defineProperty(ShadowLight.prototype, "position", {
  49612. /**
  49613. * Sets the position the shadow will be casted from. Also use as the light position for both
  49614. * point and spot lights.
  49615. */
  49616. get: function () {
  49617. return this._position;
  49618. },
  49619. /**
  49620. * Sets the position the shadow will be casted from. Also use as the light position for both
  49621. * point and spot lights.
  49622. */
  49623. set: function (value) {
  49624. this._setPosition(value);
  49625. },
  49626. enumerable: true,
  49627. configurable: true
  49628. });
  49629. ShadowLight.prototype._setDirection = function (value) {
  49630. this._direction = value;
  49631. };
  49632. Object.defineProperty(ShadowLight.prototype, "direction", {
  49633. /**
  49634. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49635. * Also use as the light direction on spot and directional lights.
  49636. */
  49637. get: function () {
  49638. return this._direction;
  49639. },
  49640. /**
  49641. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49642. * Also use as the light direction on spot and directional lights.
  49643. */
  49644. set: function (value) {
  49645. this._setDirection(value);
  49646. },
  49647. enumerable: true,
  49648. configurable: true
  49649. });
  49650. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49651. /**
  49652. * Gets the shadow projection clipping minimum z value.
  49653. */
  49654. get: function () {
  49655. return this._shadowMinZ;
  49656. },
  49657. /**
  49658. * Sets the shadow projection clipping minimum z value.
  49659. */
  49660. set: function (value) {
  49661. this._shadowMinZ = value;
  49662. this.forceProjectionMatrixCompute();
  49663. },
  49664. enumerable: true,
  49665. configurable: true
  49666. });
  49667. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49668. /**
  49669. * Sets the shadow projection clipping maximum z value.
  49670. */
  49671. get: function () {
  49672. return this._shadowMaxZ;
  49673. },
  49674. /**
  49675. * Gets the shadow projection clipping maximum z value.
  49676. */
  49677. set: function (value) {
  49678. this._shadowMaxZ = value;
  49679. this.forceProjectionMatrixCompute();
  49680. },
  49681. enumerable: true,
  49682. configurable: true
  49683. });
  49684. /**
  49685. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49686. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49687. */
  49688. ShadowLight.prototype.computeTransformedInformation = function () {
  49689. if (this.parent && this.parent.getWorldMatrix) {
  49690. if (!this.transformedPosition) {
  49691. this.transformedPosition = BABYLON.Vector3.Zero();
  49692. }
  49693. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49694. // In case the direction is present.
  49695. if (this.direction) {
  49696. if (!this.transformedDirection) {
  49697. this.transformedDirection = BABYLON.Vector3.Zero();
  49698. }
  49699. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49700. }
  49701. return true;
  49702. }
  49703. return false;
  49704. };
  49705. /**
  49706. * Return the depth scale used for the shadow map.
  49707. * @returns the depth scale.
  49708. */
  49709. ShadowLight.prototype.getDepthScale = function () {
  49710. return 50.0;
  49711. };
  49712. /**
  49713. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49714. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49715. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49716. */
  49717. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49718. return this.transformedDirection ? this.transformedDirection : this.direction;
  49719. };
  49720. /**
  49721. * Returns the ShadowLight absolute position in the World.
  49722. * @returns the position vector in world space
  49723. */
  49724. ShadowLight.prototype.getAbsolutePosition = function () {
  49725. return this.transformedPosition ? this.transformedPosition : this.position;
  49726. };
  49727. /**
  49728. * Sets the ShadowLight direction toward the passed target.
  49729. * @param target The point tot target in local space
  49730. * @returns the updated ShadowLight direction
  49731. */
  49732. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49733. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49734. return this.direction;
  49735. };
  49736. /**
  49737. * Returns the light rotation in euler definition.
  49738. * @returns the x y z rotation in local space.
  49739. */
  49740. ShadowLight.prototype.getRotation = function () {
  49741. this.direction.normalize();
  49742. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49743. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49744. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49745. };
  49746. /**
  49747. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49748. * @returns true if a cube texture needs to be use
  49749. */
  49750. ShadowLight.prototype.needCube = function () {
  49751. return false;
  49752. };
  49753. /**
  49754. * Detects if the projection matrix requires to be recomputed this frame.
  49755. * @returns true if it requires to be recomputed otherwise, false.
  49756. */
  49757. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49758. return this._needProjectionMatrixCompute;
  49759. };
  49760. /**
  49761. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49762. */
  49763. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49764. this._needProjectionMatrixCompute = true;
  49765. };
  49766. /**
  49767. * Get the world matrix of the sahdow lights.
  49768. * @hidden Internal Use Only
  49769. */
  49770. ShadowLight.prototype._getWorldMatrix = function () {
  49771. if (!this._worldMatrix) {
  49772. this._worldMatrix = BABYLON.Matrix.Identity();
  49773. }
  49774. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49775. return this._worldMatrix;
  49776. };
  49777. /**
  49778. * Gets the minZ used for shadow according to both the scene and the light.
  49779. * @param activeCamera The camera we are returning the min for
  49780. * @returns the depth min z
  49781. */
  49782. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49783. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49784. };
  49785. /**
  49786. * Gets the maxZ used for shadow according to both the scene and the light.
  49787. * @param activeCamera The camera we are returning the max for
  49788. * @returns the depth max z
  49789. */
  49790. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49791. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49792. };
  49793. /**
  49794. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49795. * @param matrix The materix to updated with the projection information
  49796. * @param viewMatrix The transform matrix of the light
  49797. * @param renderList The list of mesh to render in the map
  49798. * @returns The current light
  49799. */
  49800. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49801. if (this.customProjectionMatrixBuilder) {
  49802. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49803. }
  49804. else {
  49805. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49806. }
  49807. return this;
  49808. };
  49809. __decorate([
  49810. BABYLON.serializeAsVector3()
  49811. ], ShadowLight.prototype, "position", null);
  49812. __decorate([
  49813. BABYLON.serializeAsVector3()
  49814. ], ShadowLight.prototype, "direction", null);
  49815. __decorate([
  49816. BABYLON.serialize()
  49817. ], ShadowLight.prototype, "shadowMinZ", null);
  49818. __decorate([
  49819. BABYLON.serialize()
  49820. ], ShadowLight.prototype, "shadowMaxZ", null);
  49821. return ShadowLight;
  49822. }(BABYLON.Light));
  49823. BABYLON.ShadowLight = ShadowLight;
  49824. })(BABYLON || (BABYLON = {}));
  49825. //# sourceMappingURL=babylon.shadowLight.js.map
  49826. var BABYLON;
  49827. (function (BABYLON) {
  49828. /**
  49829. * A point light is a light defined by an unique point in world space.
  49830. * The light is emitted in every direction from this point.
  49831. * A good example of a point light is a standard light bulb.
  49832. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49833. */
  49834. var PointLight = /** @class */ (function (_super) {
  49835. __extends(PointLight, _super);
  49836. /**
  49837. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49838. * A PointLight emits the light in every direction.
  49839. * It can cast shadows.
  49840. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49841. * ```javascript
  49842. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49843. * ```
  49844. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49845. * @param name The light friendly name
  49846. * @param position The position of the point light in the scene
  49847. * @param scene The scene the lights belongs to
  49848. */
  49849. function PointLight(name, position, scene) {
  49850. var _this = _super.call(this, name, scene) || this;
  49851. _this._shadowAngle = Math.PI / 2;
  49852. _this.position = position;
  49853. return _this;
  49854. }
  49855. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49856. /**
  49857. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49858. * This specifies what angle the shadow will use to be created.
  49859. *
  49860. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49861. */
  49862. get: function () {
  49863. return this._shadowAngle;
  49864. },
  49865. /**
  49866. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49867. * This specifies what angle the shadow will use to be created.
  49868. *
  49869. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49870. */
  49871. set: function (value) {
  49872. this._shadowAngle = value;
  49873. this.forceProjectionMatrixCompute();
  49874. },
  49875. enumerable: true,
  49876. configurable: true
  49877. });
  49878. Object.defineProperty(PointLight.prototype, "direction", {
  49879. /**
  49880. * Gets the direction if it has been set.
  49881. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49882. */
  49883. get: function () {
  49884. return this._direction;
  49885. },
  49886. /**
  49887. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49888. */
  49889. set: function (value) {
  49890. var previousNeedCube = this.needCube();
  49891. this._direction = value;
  49892. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49893. this._shadowGenerator.recreateShadowMap();
  49894. }
  49895. },
  49896. enumerable: true,
  49897. configurable: true
  49898. });
  49899. /**
  49900. * Returns the string "PointLight"
  49901. * @returns the class name
  49902. */
  49903. PointLight.prototype.getClassName = function () {
  49904. return "PointLight";
  49905. };
  49906. /**
  49907. * Returns the integer 0.
  49908. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49909. */
  49910. PointLight.prototype.getTypeID = function () {
  49911. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49912. };
  49913. /**
  49914. * Specifies wether or not the shadowmap should be a cube texture.
  49915. * @returns true if the shadowmap needs to be a cube texture.
  49916. */
  49917. PointLight.prototype.needCube = function () {
  49918. return !this.direction;
  49919. };
  49920. /**
  49921. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49922. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49923. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49924. */
  49925. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49926. if (this.direction) {
  49927. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49928. }
  49929. else {
  49930. switch (faceIndex) {
  49931. case 0:
  49932. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49933. case 1:
  49934. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49935. case 2:
  49936. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49937. case 3:
  49938. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49939. case 4:
  49940. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49941. case 5:
  49942. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49943. }
  49944. }
  49945. return BABYLON.Vector3.Zero();
  49946. };
  49947. /**
  49948. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49949. * - fov = PI / 2
  49950. * - aspect ratio : 1.0
  49951. * - z-near and far equal to the active camera minZ and maxZ.
  49952. * Returns the PointLight.
  49953. */
  49954. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49955. var activeCamera = this.getScene().activeCamera;
  49956. if (!activeCamera) {
  49957. return;
  49958. }
  49959. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49960. };
  49961. PointLight.prototype._buildUniformLayout = function () {
  49962. this._uniformBuffer.addUniform("vLightData", 4);
  49963. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49964. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49965. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49966. this._uniformBuffer.addUniform("depthValues", 2);
  49967. this._uniformBuffer.create();
  49968. };
  49969. /**
  49970. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49971. * @param effect The effect to update
  49972. * @param lightIndex The index of the light in the effect to update
  49973. * @returns The point light
  49974. */
  49975. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49976. if (this.computeTransformedInformation()) {
  49977. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49978. return this;
  49979. }
  49980. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49981. return this;
  49982. };
  49983. __decorate([
  49984. BABYLON.serialize()
  49985. ], PointLight.prototype, "shadowAngle", null);
  49986. return PointLight;
  49987. }(BABYLON.ShadowLight));
  49988. BABYLON.PointLight = PointLight;
  49989. })(BABYLON || (BABYLON = {}));
  49990. //# sourceMappingURL=babylon.pointLight.js.map
  49991. var BABYLON;
  49992. (function (BABYLON) {
  49993. /**
  49994. * A directional light is defined by a direction (what a surprise!).
  49995. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49996. * 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.
  49997. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49998. */
  49999. var DirectionalLight = /** @class */ (function (_super) {
  50000. __extends(DirectionalLight, _super);
  50001. /**
  50002. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50003. * The directional light is emitted from everywhere in the given direction.
  50004. * It can cast shawdows.
  50005. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50006. * @param name The friendly name of the light
  50007. * @param direction The direction of the light
  50008. * @param scene The scene the light belongs to
  50009. */
  50010. function DirectionalLight(name, direction, scene) {
  50011. var _this = _super.call(this, name, scene) || this;
  50012. _this._shadowFrustumSize = 0;
  50013. _this._shadowOrthoScale = 0.1;
  50014. /**
  50015. * Automatically compute the projection matrix to best fit (including all the casters)
  50016. * on each frame.
  50017. */
  50018. _this.autoUpdateExtends = true;
  50019. // Cache
  50020. _this._orthoLeft = Number.MAX_VALUE;
  50021. _this._orthoRight = Number.MIN_VALUE;
  50022. _this._orthoTop = Number.MIN_VALUE;
  50023. _this._orthoBottom = Number.MAX_VALUE;
  50024. _this.position = direction.scale(-1.0);
  50025. _this.direction = direction;
  50026. return _this;
  50027. }
  50028. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50029. /**
  50030. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50031. */
  50032. get: function () {
  50033. return this._shadowFrustumSize;
  50034. },
  50035. /**
  50036. * Specifies a fix frustum size for the shadow generation.
  50037. */
  50038. set: function (value) {
  50039. this._shadowFrustumSize = value;
  50040. this.forceProjectionMatrixCompute();
  50041. },
  50042. enumerable: true,
  50043. configurable: true
  50044. });
  50045. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50046. /**
  50047. * Gets the shadow projection scale against the optimal computed one.
  50048. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50049. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50050. */
  50051. get: function () {
  50052. return this._shadowOrthoScale;
  50053. },
  50054. /**
  50055. * Sets the shadow projection scale against the optimal computed one.
  50056. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50057. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50058. */
  50059. set: function (value) {
  50060. this._shadowOrthoScale = value;
  50061. this.forceProjectionMatrixCompute();
  50062. },
  50063. enumerable: true,
  50064. configurable: true
  50065. });
  50066. /**
  50067. * Returns the string "DirectionalLight".
  50068. * @return The class name
  50069. */
  50070. DirectionalLight.prototype.getClassName = function () {
  50071. return "DirectionalLight";
  50072. };
  50073. /**
  50074. * Returns the integer 1.
  50075. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50076. */
  50077. DirectionalLight.prototype.getTypeID = function () {
  50078. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50079. };
  50080. /**
  50081. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50082. * Returns the DirectionalLight Shadow projection matrix.
  50083. */
  50084. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50085. if (this.shadowFrustumSize > 0) {
  50086. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50087. }
  50088. else {
  50089. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50090. }
  50091. };
  50092. /**
  50093. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50094. * Returns the DirectionalLight Shadow projection matrix.
  50095. */
  50096. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50097. var activeCamera = this.getScene().activeCamera;
  50098. if (!activeCamera) {
  50099. return;
  50100. }
  50101. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50102. };
  50103. /**
  50104. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50105. * Returns the DirectionalLight Shadow projection matrix.
  50106. */
  50107. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50108. var activeCamera = this.getScene().activeCamera;
  50109. if (!activeCamera) {
  50110. return;
  50111. }
  50112. // Check extends
  50113. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50114. var tempVector3 = BABYLON.Vector3.Zero();
  50115. this._orthoLeft = Number.MAX_VALUE;
  50116. this._orthoRight = Number.MIN_VALUE;
  50117. this._orthoTop = Number.MIN_VALUE;
  50118. this._orthoBottom = Number.MAX_VALUE;
  50119. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50120. var mesh = renderList[meshIndex];
  50121. if (!mesh) {
  50122. continue;
  50123. }
  50124. var boundingInfo = mesh.getBoundingInfo();
  50125. var boundingBox = boundingInfo.boundingBox;
  50126. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50127. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50128. if (tempVector3.x < this._orthoLeft)
  50129. this._orthoLeft = tempVector3.x;
  50130. if (tempVector3.y < this._orthoBottom)
  50131. this._orthoBottom = tempVector3.y;
  50132. if (tempVector3.x > this._orthoRight)
  50133. this._orthoRight = tempVector3.x;
  50134. if (tempVector3.y > this._orthoTop)
  50135. this._orthoTop = tempVector3.y;
  50136. }
  50137. }
  50138. }
  50139. var xOffset = this._orthoRight - this._orthoLeft;
  50140. var yOffset = this._orthoTop - this._orthoBottom;
  50141. 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);
  50142. };
  50143. DirectionalLight.prototype._buildUniformLayout = function () {
  50144. this._uniformBuffer.addUniform("vLightData", 4);
  50145. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50146. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50147. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50148. this._uniformBuffer.addUniform("depthValues", 2);
  50149. this._uniformBuffer.create();
  50150. };
  50151. /**
  50152. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50153. * @param effect The effect to update
  50154. * @param lightIndex The index of the light in the effect to update
  50155. * @returns The directional light
  50156. */
  50157. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50158. if (this.computeTransformedInformation()) {
  50159. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50160. return this;
  50161. }
  50162. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50163. return this;
  50164. };
  50165. /**
  50166. * Gets the minZ used for shadow according to both the scene and the light.
  50167. *
  50168. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50169. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50170. * @param activeCamera The camera we are returning the min for
  50171. * @returns the depth min z
  50172. */
  50173. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50174. return 1;
  50175. };
  50176. /**
  50177. * Gets the maxZ used for shadow according to both the scene and the light.
  50178. *
  50179. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50180. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50181. * @param activeCamera The camera we are returning the max for
  50182. * @returns the depth max z
  50183. */
  50184. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50185. return 1;
  50186. };
  50187. __decorate([
  50188. BABYLON.serialize()
  50189. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50190. __decorate([
  50191. BABYLON.serialize()
  50192. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50193. __decorate([
  50194. BABYLON.serialize()
  50195. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50196. return DirectionalLight;
  50197. }(BABYLON.ShadowLight));
  50198. BABYLON.DirectionalLight = DirectionalLight;
  50199. })(BABYLON || (BABYLON = {}));
  50200. //# sourceMappingURL=babylon.directionalLight.js.map
  50201. var BABYLON;
  50202. (function (BABYLON) {
  50203. /**
  50204. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50205. * These values define a cone of light starting from the position, emitting toward the direction.
  50206. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50207. * and the exponent defines the speed of the decay of the light with distance (reach).
  50208. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50209. */
  50210. var SpotLight = /** @class */ (function (_super) {
  50211. __extends(SpotLight, _super);
  50212. /**
  50213. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50214. * It can cast shadows.
  50215. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50216. * @param name The light friendly name
  50217. * @param position The position of the spot light in the scene
  50218. * @param direction The direction of the light in the scene
  50219. * @param angle The cone angle of the light in Radians
  50220. * @param exponent The light decay speed with the distance from the emission spot
  50221. * @param scene The scene the lights belongs to
  50222. */
  50223. function SpotLight(name, position, direction, angle, exponent, scene) {
  50224. var _this = _super.call(this, name, scene) || this;
  50225. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50226. _this._projectionTextureLightNear = 1e-6;
  50227. _this._projectionTextureLightFar = 1000.0;
  50228. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50229. _this._projectionTextureViewLightDirty = true;
  50230. _this._projectionTextureProjectionLightDirty = true;
  50231. _this._projectionTextureDirty = true;
  50232. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50233. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50234. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50235. _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);
  50236. _this.position = position;
  50237. _this.direction = direction;
  50238. _this.angle = angle;
  50239. _this.exponent = exponent;
  50240. return _this;
  50241. }
  50242. Object.defineProperty(SpotLight.prototype, "angle", {
  50243. /**
  50244. * Gets the cone angle of the spot light in Radians.
  50245. */
  50246. get: function () {
  50247. return this._angle;
  50248. },
  50249. /**
  50250. * Sets the cone angle of the spot light in Radians.
  50251. */
  50252. set: function (value) {
  50253. this._angle = value;
  50254. this._projectionTextureProjectionLightDirty = true;
  50255. this.forceProjectionMatrixCompute();
  50256. },
  50257. enumerable: true,
  50258. configurable: true
  50259. });
  50260. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50261. /**
  50262. * Allows scaling the angle of the light for shadow generation only.
  50263. */
  50264. get: function () {
  50265. return this._shadowAngleScale;
  50266. },
  50267. /**
  50268. * Allows scaling the angle of the light for shadow generation only.
  50269. */
  50270. set: function (value) {
  50271. this._shadowAngleScale = value;
  50272. this.forceProjectionMatrixCompute();
  50273. },
  50274. enumerable: true,
  50275. configurable: true
  50276. });
  50277. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50278. /**
  50279. * Allows reading the projecton texture
  50280. */
  50281. get: function () {
  50282. return this._projectionTextureMatrix;
  50283. },
  50284. enumerable: true,
  50285. configurable: true
  50286. });
  50287. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50288. /**
  50289. * Gets the near clip of the Spotlight for texture projection.
  50290. */
  50291. get: function () {
  50292. return this._projectionTextureLightNear;
  50293. },
  50294. /**
  50295. * Sets the near clip of the Spotlight for texture projection.
  50296. */
  50297. set: function (value) {
  50298. this._projectionTextureLightNear = value;
  50299. this._projectionTextureProjectionLightDirty = true;
  50300. },
  50301. enumerable: true,
  50302. configurable: true
  50303. });
  50304. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50305. /**
  50306. * Gets the far clip of the Spotlight for texture projection.
  50307. */
  50308. get: function () {
  50309. return this._projectionTextureLightFar;
  50310. },
  50311. /**
  50312. * Sets the far clip of the Spotlight for texture projection.
  50313. */
  50314. set: function (value) {
  50315. this._projectionTextureLightFar = value;
  50316. this._projectionTextureProjectionLightDirty = true;
  50317. },
  50318. enumerable: true,
  50319. configurable: true
  50320. });
  50321. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50322. /**
  50323. * Gets the Up vector of the Spotlight for texture projection.
  50324. */
  50325. get: function () {
  50326. return this._projectionTextureUpDirection;
  50327. },
  50328. /**
  50329. * Sets the Up vector of the Spotlight for texture projection.
  50330. */
  50331. set: function (value) {
  50332. this._projectionTextureUpDirection = value;
  50333. this._projectionTextureProjectionLightDirty = true;
  50334. },
  50335. enumerable: true,
  50336. configurable: true
  50337. });
  50338. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50339. /**
  50340. * Gets the projection texture of the light.
  50341. */
  50342. get: function () {
  50343. return this._projectionTexture;
  50344. },
  50345. /**
  50346. * Sets the projection texture of the light.
  50347. */
  50348. set: function (value) {
  50349. this._projectionTexture = value;
  50350. this._projectionTextureDirty = true;
  50351. },
  50352. enumerable: true,
  50353. configurable: true
  50354. });
  50355. /**
  50356. * Returns the string "SpotLight".
  50357. * @returns the class name
  50358. */
  50359. SpotLight.prototype.getClassName = function () {
  50360. return "SpotLight";
  50361. };
  50362. /**
  50363. * Returns the integer 2.
  50364. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50365. */
  50366. SpotLight.prototype.getTypeID = function () {
  50367. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50368. };
  50369. /**
  50370. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50371. */
  50372. SpotLight.prototype._setDirection = function (value) {
  50373. _super.prototype._setDirection.call(this, value);
  50374. this._projectionTextureViewLightDirty = true;
  50375. };
  50376. /**
  50377. * Overrides the position setter to recompute the projection texture view light Matrix.
  50378. */
  50379. SpotLight.prototype._setPosition = function (value) {
  50380. _super.prototype._setPosition.call(this, value);
  50381. this._projectionTextureViewLightDirty = true;
  50382. };
  50383. /**
  50384. * 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.
  50385. * Returns the SpotLight.
  50386. */
  50387. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50388. var activeCamera = this.getScene().activeCamera;
  50389. if (!activeCamera) {
  50390. return;
  50391. }
  50392. this._shadowAngleScale = this._shadowAngleScale || 1;
  50393. var angle = this._shadowAngleScale * this._angle;
  50394. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50395. };
  50396. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50397. this._projectionTextureViewLightDirty = false;
  50398. this._projectionTextureDirty = true;
  50399. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50400. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50401. };
  50402. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50403. this._projectionTextureProjectionLightDirty = false;
  50404. this._projectionTextureDirty = true;
  50405. var light_far = this.projectionTextureLightFar;
  50406. var light_near = this.projectionTextureLightNear;
  50407. var P = light_far / (light_far - light_near);
  50408. var Q = -P * light_near;
  50409. var S = 1.0 / Math.tan(this._angle / 2.0);
  50410. var A = 1.0;
  50411. 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);
  50412. };
  50413. /**
  50414. * Main function for light texture projection matrix computing.
  50415. */
  50416. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50417. this._projectionTextureDirty = false;
  50418. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50419. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50420. };
  50421. SpotLight.prototype._buildUniformLayout = function () {
  50422. this._uniformBuffer.addUniform("vLightData", 4);
  50423. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50424. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50425. this._uniformBuffer.addUniform("vLightDirection", 3);
  50426. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50427. this._uniformBuffer.addUniform("depthValues", 2);
  50428. this._uniformBuffer.create();
  50429. };
  50430. /**
  50431. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50432. * @param effect The effect to update
  50433. * @param lightIndex The index of the light in the effect to update
  50434. * @returns The spot light
  50435. */
  50436. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50437. var normalizeDirection;
  50438. if (this.computeTransformedInformation()) {
  50439. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50440. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50441. }
  50442. else {
  50443. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50444. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50445. }
  50446. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50447. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50448. if (this._projectionTextureViewLightDirty) {
  50449. this._computeProjectionTextureViewLightMatrix();
  50450. }
  50451. if (this._projectionTextureProjectionLightDirty) {
  50452. this._computeProjectionTextureProjectionLightMatrix();
  50453. }
  50454. if (this._projectionTextureDirty) {
  50455. this._computeProjectionTextureMatrix();
  50456. }
  50457. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50458. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50459. }
  50460. return this;
  50461. };
  50462. /**
  50463. * Disposes the light and the associated resources.
  50464. */
  50465. SpotLight.prototype.dispose = function () {
  50466. _super.prototype.dispose.call(this);
  50467. if (this._projectionTexture) {
  50468. this._projectionTexture.dispose();
  50469. }
  50470. };
  50471. __decorate([
  50472. BABYLON.serialize()
  50473. ], SpotLight.prototype, "angle", null);
  50474. __decorate([
  50475. BABYLON.serialize()
  50476. ], SpotLight.prototype, "shadowAngleScale", null);
  50477. __decorate([
  50478. BABYLON.serialize()
  50479. ], SpotLight.prototype, "exponent", void 0);
  50480. __decorate([
  50481. BABYLON.serialize()
  50482. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50483. __decorate([
  50484. BABYLON.serialize()
  50485. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50486. __decorate([
  50487. BABYLON.serialize()
  50488. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50489. __decorate([
  50490. BABYLON.serializeAsTexture("projectedLightTexture")
  50491. ], SpotLight.prototype, "_projectionTexture", void 0);
  50492. return SpotLight;
  50493. }(BABYLON.ShadowLight));
  50494. BABYLON.SpotLight = SpotLight;
  50495. })(BABYLON || (BABYLON = {}));
  50496. //# sourceMappingURL=babylon.spotLight.js.map
  50497. var BABYLON;
  50498. (function (BABYLON) {
  50499. /**
  50500. * Class used to override all child animations of a given target
  50501. */
  50502. var AnimationPropertiesOverride = /** @class */ (function () {
  50503. function AnimationPropertiesOverride() {
  50504. /**
  50505. * Gets or sets a value indicating if animation blending must be used
  50506. */
  50507. this.enableBlending = false;
  50508. /**
  50509. * Gets or sets the blending speed to use when enableBlending is true
  50510. */
  50511. this.blendingSpeed = 0.01;
  50512. /**
  50513. * Gets or sets the default loop mode to use
  50514. */
  50515. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50516. }
  50517. return AnimationPropertiesOverride;
  50518. }());
  50519. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50520. })(BABYLON || (BABYLON = {}));
  50521. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50522. var BABYLON;
  50523. (function (BABYLON) {
  50524. /**
  50525. * Represents the range of an animation
  50526. */
  50527. var AnimationRange = /** @class */ (function () {
  50528. /**
  50529. * Initializes the range of an animation
  50530. * @param name The name of the animation range
  50531. * @param from The starting frame of the animation
  50532. * @param to The ending frame of the animation
  50533. */
  50534. function AnimationRange(
  50535. /**The name of the animation range**/
  50536. name,
  50537. /**The starting frame of the animation */
  50538. from,
  50539. /**The ending frame of the animation*/
  50540. to) {
  50541. this.name = name;
  50542. this.from = from;
  50543. this.to = to;
  50544. }
  50545. /**
  50546. * Makes a copy of the animation range
  50547. * @returns A copy of the animation range
  50548. */
  50549. AnimationRange.prototype.clone = function () {
  50550. return new AnimationRange(this.name, this.from, this.to);
  50551. };
  50552. return AnimationRange;
  50553. }());
  50554. BABYLON.AnimationRange = AnimationRange;
  50555. /**
  50556. * Composed of a frame, and an action function
  50557. */
  50558. var AnimationEvent = /** @class */ (function () {
  50559. /**
  50560. * Initializes the animation event
  50561. * @param frame The frame for which the event is triggered
  50562. * @param action The event to perform when triggered
  50563. * @param onlyOnce Specifies if the event should be triggered only once
  50564. */
  50565. function AnimationEvent(
  50566. /** The frame for which the event is triggered **/
  50567. frame,
  50568. /** The event to perform when triggered **/
  50569. action,
  50570. /** Specifies if the event should be triggered only once**/
  50571. onlyOnce) {
  50572. this.frame = frame;
  50573. this.action = action;
  50574. this.onlyOnce = onlyOnce;
  50575. /**
  50576. * Specifies if the animation event is done
  50577. */
  50578. this.isDone = false;
  50579. }
  50580. /** @hidden */
  50581. AnimationEvent.prototype._clone = function () {
  50582. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50583. };
  50584. return AnimationEvent;
  50585. }());
  50586. BABYLON.AnimationEvent = AnimationEvent;
  50587. /**
  50588. * A cursor which tracks a point on a path
  50589. */
  50590. var PathCursor = /** @class */ (function () {
  50591. /**
  50592. * Initializes the path cursor
  50593. * @param path The path to track
  50594. */
  50595. function PathCursor(path) {
  50596. this.path = path;
  50597. /**
  50598. * Stores path cursor callbacks for when an onchange event is triggered
  50599. */
  50600. this._onchange = new Array();
  50601. /**
  50602. * The value of the path cursor
  50603. */
  50604. this.value = 0;
  50605. /**
  50606. * The animation array of the path cursor
  50607. */
  50608. this.animations = new Array();
  50609. }
  50610. /**
  50611. * Gets the cursor point on the path
  50612. * @returns A point on the path cursor at the cursor location
  50613. */
  50614. PathCursor.prototype.getPoint = function () {
  50615. var point = this.path.getPointAtLengthPosition(this.value);
  50616. return new BABYLON.Vector3(point.x, 0, point.y);
  50617. };
  50618. /**
  50619. * Moves the cursor ahead by the step amount
  50620. * @param step The amount to move the cursor forward
  50621. * @returns This path cursor
  50622. */
  50623. PathCursor.prototype.moveAhead = function (step) {
  50624. if (step === void 0) { step = 0.002; }
  50625. this.move(step);
  50626. return this;
  50627. };
  50628. /**
  50629. * Moves the cursor behind by the step amount
  50630. * @param step The amount to move the cursor back
  50631. * @returns This path cursor
  50632. */
  50633. PathCursor.prototype.moveBack = function (step) {
  50634. if (step === void 0) { step = 0.002; }
  50635. this.move(-step);
  50636. return this;
  50637. };
  50638. /**
  50639. * Moves the cursor by the step amount
  50640. * If the step amount is greater than one, an exception is thrown
  50641. * @param step The amount to move the cursor
  50642. * @returns This path cursor
  50643. */
  50644. PathCursor.prototype.move = function (step) {
  50645. if (Math.abs(step) > 1) {
  50646. throw "step size should be less than 1.";
  50647. }
  50648. this.value += step;
  50649. this.ensureLimits();
  50650. this.raiseOnChange();
  50651. return this;
  50652. };
  50653. /**
  50654. * Ensures that the value is limited between zero and one
  50655. * @returns This path cursor
  50656. */
  50657. PathCursor.prototype.ensureLimits = function () {
  50658. while (this.value > 1) {
  50659. this.value -= 1;
  50660. }
  50661. while (this.value < 0) {
  50662. this.value += 1;
  50663. }
  50664. return this;
  50665. };
  50666. /**
  50667. * Runs onchange callbacks on change (used by the animation engine)
  50668. * @returns This path cursor
  50669. */
  50670. PathCursor.prototype.raiseOnChange = function () {
  50671. var _this = this;
  50672. this._onchange.forEach(function (f) { return f(_this); });
  50673. return this;
  50674. };
  50675. /**
  50676. * Executes a function on change
  50677. * @param f A path cursor onchange callback
  50678. * @returns This path cursor
  50679. */
  50680. PathCursor.prototype.onchange = function (f) {
  50681. this._onchange.push(f);
  50682. return this;
  50683. };
  50684. return PathCursor;
  50685. }());
  50686. BABYLON.PathCursor = PathCursor;
  50687. /**
  50688. * Enum for the animation key frame interpolation type
  50689. */
  50690. var AnimationKeyInterpolation;
  50691. (function (AnimationKeyInterpolation) {
  50692. /**
  50693. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50694. */
  50695. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50696. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50697. /**
  50698. * Class used to store any kind of animation
  50699. */
  50700. var Animation = /** @class */ (function () {
  50701. /**
  50702. * Initializes the animation
  50703. * @param name Name of the animation
  50704. * @param targetProperty Property to animate
  50705. * @param framePerSecond The frames per second of the animation
  50706. * @param dataType The data type of the animation
  50707. * @param loopMode The loop mode of the animation
  50708. * @param enableBlendings Specifies if blending should be enabled
  50709. */
  50710. function Animation(
  50711. /**Name of the animation */
  50712. name,
  50713. /**Property to animate */
  50714. targetProperty,
  50715. /**The frames per second of the animation */
  50716. framePerSecond,
  50717. /**The data type of the animation */
  50718. dataType,
  50719. /**The loop mode of the animation */
  50720. loopMode,
  50721. /**Specifies if blending should be enabled */
  50722. enableBlending) {
  50723. this.name = name;
  50724. this.targetProperty = targetProperty;
  50725. this.framePerSecond = framePerSecond;
  50726. this.dataType = dataType;
  50727. this.loopMode = loopMode;
  50728. this.enableBlending = enableBlending;
  50729. /**
  50730. * @hidden Internal use only
  50731. */
  50732. this._runtimeAnimations = new Array();
  50733. /**
  50734. * The set of event that will be linked to this animation
  50735. */
  50736. this._events = new Array();
  50737. /**
  50738. * Stores the blending speed of the animation
  50739. */
  50740. this.blendingSpeed = 0.01;
  50741. /**
  50742. * Stores the animation ranges for the animation
  50743. */
  50744. this._ranges = {};
  50745. this.targetPropertyPath = targetProperty.split(".");
  50746. this.dataType = dataType;
  50747. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50748. }
  50749. /**
  50750. * @hidden Internal use
  50751. */
  50752. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50753. var dataType = undefined;
  50754. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50755. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50756. }
  50757. else if (from instanceof BABYLON.Quaternion) {
  50758. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50759. }
  50760. else if (from instanceof BABYLON.Vector3) {
  50761. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50762. }
  50763. else if (from instanceof BABYLON.Vector2) {
  50764. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50765. }
  50766. else if (from instanceof BABYLON.Color3) {
  50767. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50768. }
  50769. else if (from instanceof BABYLON.Size) {
  50770. dataType = Animation.ANIMATIONTYPE_SIZE;
  50771. }
  50772. if (dataType == undefined) {
  50773. return null;
  50774. }
  50775. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50776. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50777. animation.setKeys(keys);
  50778. if (easingFunction !== undefined) {
  50779. animation.setEasingFunction(easingFunction);
  50780. }
  50781. return animation;
  50782. };
  50783. /**
  50784. * Sets up an animation
  50785. * @param property The property to animate
  50786. * @param animationType The animation type to apply
  50787. * @param framePerSecond The frames per second of the animation
  50788. * @param easingFunction The easing function used in the animation
  50789. * @returns The created animation
  50790. */
  50791. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50792. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50793. animation.setEasingFunction(easingFunction);
  50794. return animation;
  50795. };
  50796. /**
  50797. * Create and start an animation on a node
  50798. * @param name defines the name of the global animation that will be run on all nodes
  50799. * @param node defines the root node where the animation will take place
  50800. * @param targetProperty defines property to animate
  50801. * @param framePerSecond defines the number of frame per second yo use
  50802. * @param totalFrame defines the number of frames in total
  50803. * @param from defines the initial value
  50804. * @param to defines the final value
  50805. * @param loopMode defines which loop mode you want to use (off by default)
  50806. * @param easingFunction defines the easing function to use (linear by default)
  50807. * @param onAnimationEnd defines the callback to call when animation end
  50808. * @returns the animatable created for this animation
  50809. */
  50810. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50811. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50812. if (!animation) {
  50813. return null;
  50814. }
  50815. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50816. };
  50817. /**
  50818. * Create and start an animation on a node and its descendants
  50819. * @param name defines the name of the global animation that will be run on all nodes
  50820. * @param node defines the root node where the animation will take place
  50821. * @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
  50822. * @param targetProperty defines property to animate
  50823. * @param framePerSecond defines the number of frame per second to use
  50824. * @param totalFrame defines the number of frames in total
  50825. * @param from defines the initial value
  50826. * @param to defines the final value
  50827. * @param loopMode defines which loop mode you want to use (off by default)
  50828. * @param easingFunction defines the easing function to use (linear by default)
  50829. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50830. * @returns the list of animatables created for all nodes
  50831. * @example https://www.babylonjs-playground.com/#MH0VLI
  50832. */
  50833. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50834. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50835. if (!animation) {
  50836. return null;
  50837. }
  50838. var scene = node.getScene();
  50839. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50840. };
  50841. /**
  50842. * Creates a new animation, merges it with the existing animations and starts it
  50843. * @param name Name of the animation
  50844. * @param node Node which contains the scene that begins the animations
  50845. * @param targetProperty Specifies which property to animate
  50846. * @param framePerSecond The frames per second of the animation
  50847. * @param totalFrame The total number of frames
  50848. * @param from The frame at the beginning of the animation
  50849. * @param to The frame at the end of the animation
  50850. * @param loopMode Specifies the loop mode of the animation
  50851. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50852. * @param onAnimationEnd Callback to run once the animation is complete
  50853. * @returns Nullable animation
  50854. */
  50855. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50856. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50857. if (!animation) {
  50858. return null;
  50859. }
  50860. node.animations.push(animation);
  50861. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50862. };
  50863. /**
  50864. * Transition property of an host to the target Value
  50865. * @param property The property to transition
  50866. * @param targetValue The target Value of the property
  50867. * @param host The object where the property to animate belongs
  50868. * @param scene Scene used to run the animation
  50869. * @param frameRate Framerate (in frame/s) to use
  50870. * @param transition The transition type we want to use
  50871. * @param duration The duration of the animation, in milliseconds
  50872. * @param onAnimationEnd Callback trigger at the end of the animation
  50873. * @returns Nullable animation
  50874. */
  50875. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50876. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50877. if (duration <= 0) {
  50878. host[property] = targetValue;
  50879. if (onAnimationEnd) {
  50880. onAnimationEnd();
  50881. }
  50882. return null;
  50883. }
  50884. var endFrame = frameRate * (duration / 1000);
  50885. transition.setKeys([{
  50886. frame: 0,
  50887. value: host[property].clone ? host[property].clone() : host[property]
  50888. },
  50889. {
  50890. frame: endFrame,
  50891. value: targetValue
  50892. }]);
  50893. if (!host.animations) {
  50894. host.animations = [];
  50895. }
  50896. host.animations.push(transition);
  50897. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50898. animation.onAnimationEnd = onAnimationEnd;
  50899. return animation;
  50900. };
  50901. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50902. /**
  50903. * Return the array of runtime animations currently using this animation
  50904. */
  50905. get: function () {
  50906. return this._runtimeAnimations;
  50907. },
  50908. enumerable: true,
  50909. configurable: true
  50910. });
  50911. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50912. /**
  50913. * Specifies if any of the runtime animations are currently running
  50914. */
  50915. get: function () {
  50916. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50917. var runtimeAnimation = _a[_i];
  50918. if (!runtimeAnimation.isStopped) {
  50919. return true;
  50920. }
  50921. }
  50922. return false;
  50923. },
  50924. enumerable: true,
  50925. configurable: true
  50926. });
  50927. // Methods
  50928. /**
  50929. * Converts the animation to a string
  50930. * @param fullDetails support for multiple levels of logging within scene loading
  50931. * @returns String form of the animation
  50932. */
  50933. Animation.prototype.toString = function (fullDetails) {
  50934. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50935. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50936. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50937. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50938. if (fullDetails) {
  50939. ret += ", Ranges: {";
  50940. var first = true;
  50941. for (var name in this._ranges) {
  50942. if (first) {
  50943. ret += ", ";
  50944. first = false;
  50945. }
  50946. ret += name;
  50947. }
  50948. ret += "}";
  50949. }
  50950. return ret;
  50951. };
  50952. /**
  50953. * Add an event to this animation
  50954. * @param event Event to add
  50955. */
  50956. Animation.prototype.addEvent = function (event) {
  50957. this._events.push(event);
  50958. };
  50959. /**
  50960. * Remove all events found at the given frame
  50961. * @param frame The frame to remove events from
  50962. */
  50963. Animation.prototype.removeEvents = function (frame) {
  50964. for (var index = 0; index < this._events.length; index++) {
  50965. if (this._events[index].frame === frame) {
  50966. this._events.splice(index, 1);
  50967. index--;
  50968. }
  50969. }
  50970. };
  50971. /**
  50972. * Retrieves all the events from the animation
  50973. * @returns Events from the animation
  50974. */
  50975. Animation.prototype.getEvents = function () {
  50976. return this._events;
  50977. };
  50978. /**
  50979. * Creates an animation range
  50980. * @param name Name of the animation range
  50981. * @param from Starting frame of the animation range
  50982. * @param to Ending frame of the animation
  50983. */
  50984. Animation.prototype.createRange = function (name, from, to) {
  50985. // check name not already in use; could happen for bones after serialized
  50986. if (!this._ranges[name]) {
  50987. this._ranges[name] = new AnimationRange(name, from, to);
  50988. }
  50989. };
  50990. /**
  50991. * Deletes an animation range by name
  50992. * @param name Name of the animation range to delete
  50993. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50994. */
  50995. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50996. if (deleteFrames === void 0) { deleteFrames = true; }
  50997. var range = this._ranges[name];
  50998. if (!range) {
  50999. return;
  51000. }
  51001. if (deleteFrames) {
  51002. var from = range.from;
  51003. var to = range.to;
  51004. // this loop MUST go high to low for multiple splices to work
  51005. for (var key = this._keys.length - 1; key >= 0; key--) {
  51006. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51007. this._keys.splice(key, 1);
  51008. }
  51009. }
  51010. }
  51011. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51012. };
  51013. /**
  51014. * Gets the animation range by name, or null if not defined
  51015. * @param name Name of the animation range
  51016. * @returns Nullable animation range
  51017. */
  51018. Animation.prototype.getRange = function (name) {
  51019. return this._ranges[name];
  51020. };
  51021. /**
  51022. * Gets the key frames from the animation
  51023. * @returns The key frames of the animation
  51024. */
  51025. Animation.prototype.getKeys = function () {
  51026. return this._keys;
  51027. };
  51028. /**
  51029. * Gets the highest frame rate of the animation
  51030. * @returns Highest frame rate of the animation
  51031. */
  51032. Animation.prototype.getHighestFrame = function () {
  51033. var ret = 0;
  51034. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51035. if (ret < this._keys[key].frame) {
  51036. ret = this._keys[key].frame;
  51037. }
  51038. }
  51039. return ret;
  51040. };
  51041. /**
  51042. * Gets the easing function of the animation
  51043. * @returns Easing function of the animation
  51044. */
  51045. Animation.prototype.getEasingFunction = function () {
  51046. return this._easingFunction;
  51047. };
  51048. /**
  51049. * Sets the easing function of the animation
  51050. * @param easingFunction A custom mathematical formula for animation
  51051. */
  51052. Animation.prototype.setEasingFunction = function (easingFunction) {
  51053. this._easingFunction = easingFunction;
  51054. };
  51055. /**
  51056. * Interpolates a scalar linearly
  51057. * @param startValue Start value of the animation curve
  51058. * @param endValue End value of the animation curve
  51059. * @param gradient Scalar amount to interpolate
  51060. * @returns Interpolated scalar value
  51061. */
  51062. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51063. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51064. };
  51065. /**
  51066. * Interpolates a scalar cubically
  51067. * @param startValue Start value of the animation curve
  51068. * @param outTangent End tangent of the animation
  51069. * @param endValue End value of the animation curve
  51070. * @param inTangent Start tangent of the animation curve
  51071. * @param gradient Scalar amount to interpolate
  51072. * @returns Interpolated scalar value
  51073. */
  51074. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51075. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51076. };
  51077. /**
  51078. * Interpolates a quaternion using a spherical linear interpolation
  51079. * @param startValue Start value of the animation curve
  51080. * @param endValue End value of the animation curve
  51081. * @param gradient Scalar amount to interpolate
  51082. * @returns Interpolated quaternion value
  51083. */
  51084. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51085. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51086. };
  51087. /**
  51088. * Interpolates a quaternion cubically
  51089. * @param startValue Start value of the animation curve
  51090. * @param outTangent End tangent of the animation curve
  51091. * @param endValue End value of the animation curve
  51092. * @param inTangent Start tangent of the animation curve
  51093. * @param gradient Scalar amount to interpolate
  51094. * @returns Interpolated quaternion value
  51095. */
  51096. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51097. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51098. };
  51099. /**
  51100. * Interpolates a Vector3 linearl
  51101. * @param startValue Start value of the animation curve
  51102. * @param endValue End value of the animation curve
  51103. * @param gradient Scalar amount to interpolate
  51104. * @returns Interpolated scalar value
  51105. */
  51106. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51107. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51108. };
  51109. /**
  51110. * Interpolates a Vector3 cubically
  51111. * @param startValue Start value of the animation curve
  51112. * @param outTangent End tangent of the animation
  51113. * @param endValue End value of the animation curve
  51114. * @param inTangent Start tangent of the animation curve
  51115. * @param gradient Scalar amount to interpolate
  51116. * @returns InterpolatedVector3 value
  51117. */
  51118. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51119. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51120. };
  51121. /**
  51122. * Interpolates a Vector2 linearly
  51123. * @param startValue Start value of the animation curve
  51124. * @param endValue End value of the animation curve
  51125. * @param gradient Scalar amount to interpolate
  51126. * @returns Interpolated Vector2 value
  51127. */
  51128. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51129. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51130. };
  51131. /**
  51132. * Interpolates a Vector2 cubically
  51133. * @param startValue Start value of the animation curve
  51134. * @param outTangent End tangent of the animation
  51135. * @param endValue End value of the animation curve
  51136. * @param inTangent Start tangent of the animation curve
  51137. * @param gradient Scalar amount to interpolate
  51138. * @returns Interpolated Vector2 value
  51139. */
  51140. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51141. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51142. };
  51143. /**
  51144. * Interpolates a size linearly
  51145. * @param startValue Start value of the animation curve
  51146. * @param endValue End value of the animation curve
  51147. * @param gradient Scalar amount to interpolate
  51148. * @returns Interpolated Size value
  51149. */
  51150. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51151. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51152. };
  51153. /**
  51154. * Interpolates a Color3 linearly
  51155. * @param startValue Start value of the animation curve
  51156. * @param endValue End value of the animation curve
  51157. * @param gradient Scalar amount to interpolate
  51158. * @returns Interpolated Color3 value
  51159. */
  51160. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51161. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51162. };
  51163. /**
  51164. * @hidden Internal use only
  51165. */
  51166. Animation.prototype._getKeyValue = function (value) {
  51167. if (typeof value === "function") {
  51168. return value();
  51169. }
  51170. return value;
  51171. };
  51172. /**
  51173. * @hidden Internal use only
  51174. */
  51175. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51176. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51177. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51178. }
  51179. var keys = this.getKeys();
  51180. // Try to get a hash to find the right key
  51181. 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));
  51182. if (keys[startKeyIndex].frame >= currentFrame) {
  51183. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51184. startKeyIndex--;
  51185. }
  51186. }
  51187. for (var key = startKeyIndex; key < keys.length; key++) {
  51188. var endKey = keys[key + 1];
  51189. if (endKey.frame >= currentFrame) {
  51190. var startKey = keys[key];
  51191. var startValue = this._getKeyValue(startKey.value);
  51192. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51193. return startValue;
  51194. }
  51195. var endValue = this._getKeyValue(endKey.value);
  51196. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51197. var frameDelta = endKey.frame - startKey.frame;
  51198. // gradient : percent of currentFrame between the frame inf and the frame sup
  51199. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51200. // check for easingFunction and correction of gradient
  51201. var easingFunction = this.getEasingFunction();
  51202. if (easingFunction != null) {
  51203. gradient = easingFunction.ease(gradient);
  51204. }
  51205. switch (this.dataType) {
  51206. // Float
  51207. case Animation.ANIMATIONTYPE_FLOAT:
  51208. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51209. switch (loopMode) {
  51210. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51211. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51212. return floatValue;
  51213. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51214. return offsetValue * repeatCount + floatValue;
  51215. }
  51216. break;
  51217. // Quaternion
  51218. case Animation.ANIMATIONTYPE_QUATERNION:
  51219. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51220. switch (loopMode) {
  51221. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51222. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51223. return quatValue;
  51224. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51225. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51226. }
  51227. return quatValue;
  51228. // Vector3
  51229. case Animation.ANIMATIONTYPE_VECTOR3:
  51230. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51231. switch (loopMode) {
  51232. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51233. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51234. return vec3Value;
  51235. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51236. return vec3Value.add(offsetValue.scale(repeatCount));
  51237. }
  51238. // Vector2
  51239. case Animation.ANIMATIONTYPE_VECTOR2:
  51240. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51241. switch (loopMode) {
  51242. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51243. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51244. return vec2Value;
  51245. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51246. return vec2Value.add(offsetValue.scale(repeatCount));
  51247. }
  51248. // Size
  51249. case Animation.ANIMATIONTYPE_SIZE:
  51250. switch (loopMode) {
  51251. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51252. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51253. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51254. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51255. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51256. }
  51257. // Color3
  51258. case Animation.ANIMATIONTYPE_COLOR3:
  51259. switch (loopMode) {
  51260. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51261. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51262. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51263. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51264. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51265. }
  51266. // Matrix
  51267. case Animation.ANIMATIONTYPE_MATRIX:
  51268. switch (loopMode) {
  51269. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51270. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51271. if (Animation.AllowMatricesInterpolation) {
  51272. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51273. }
  51274. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51275. return startValue;
  51276. }
  51277. default:
  51278. break;
  51279. }
  51280. break;
  51281. }
  51282. }
  51283. return this._getKeyValue(keys[keys.length - 1].value);
  51284. };
  51285. /**
  51286. * Defines the function to use to interpolate matrices
  51287. * @param startValue defines the start matrix
  51288. * @param endValue defines the end matrix
  51289. * @param gradient defines the gradient between both matrices
  51290. * @param result defines an optional target matrix where to store the interpolation
  51291. * @returns the interpolated matrix
  51292. */
  51293. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51294. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51295. if (result) {
  51296. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51297. return result;
  51298. }
  51299. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51300. }
  51301. if (result) {
  51302. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51303. return result;
  51304. }
  51305. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51306. };
  51307. /**
  51308. * Makes a copy of the animation
  51309. * @returns Cloned animation
  51310. */
  51311. Animation.prototype.clone = function () {
  51312. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51313. clone.enableBlending = this.enableBlending;
  51314. clone.blendingSpeed = this.blendingSpeed;
  51315. if (this._keys) {
  51316. clone.setKeys(this._keys);
  51317. }
  51318. if (this._ranges) {
  51319. clone._ranges = {};
  51320. for (var name in this._ranges) {
  51321. var range = this._ranges[name];
  51322. if (!range) {
  51323. continue;
  51324. }
  51325. clone._ranges[name] = range.clone();
  51326. }
  51327. }
  51328. return clone;
  51329. };
  51330. /**
  51331. * Sets the key frames of the animation
  51332. * @param values The animation key frames to set
  51333. */
  51334. Animation.prototype.setKeys = function (values) {
  51335. this._keys = values.slice(0);
  51336. };
  51337. /**
  51338. * Serializes the animation to an object
  51339. * @returns Serialized object
  51340. */
  51341. Animation.prototype.serialize = function () {
  51342. var serializationObject = {};
  51343. serializationObject.name = this.name;
  51344. serializationObject.property = this.targetProperty;
  51345. serializationObject.framePerSecond = this.framePerSecond;
  51346. serializationObject.dataType = this.dataType;
  51347. serializationObject.loopBehavior = this.loopMode;
  51348. serializationObject.enableBlending = this.enableBlending;
  51349. serializationObject.blendingSpeed = this.blendingSpeed;
  51350. var dataType = this.dataType;
  51351. serializationObject.keys = [];
  51352. var keys = this.getKeys();
  51353. for (var index = 0; index < keys.length; index++) {
  51354. var animationKey = keys[index];
  51355. var key = {};
  51356. key.frame = animationKey.frame;
  51357. switch (dataType) {
  51358. case Animation.ANIMATIONTYPE_FLOAT:
  51359. key.values = [animationKey.value];
  51360. break;
  51361. case Animation.ANIMATIONTYPE_QUATERNION:
  51362. case Animation.ANIMATIONTYPE_MATRIX:
  51363. case Animation.ANIMATIONTYPE_VECTOR3:
  51364. case Animation.ANIMATIONTYPE_COLOR3:
  51365. key.values = animationKey.value.asArray();
  51366. break;
  51367. }
  51368. serializationObject.keys.push(key);
  51369. }
  51370. serializationObject.ranges = [];
  51371. for (var name in this._ranges) {
  51372. var source = this._ranges[name];
  51373. if (!source) {
  51374. continue;
  51375. }
  51376. var range = {};
  51377. range.name = name;
  51378. range.from = source.from;
  51379. range.to = source.to;
  51380. serializationObject.ranges.push(range);
  51381. }
  51382. return serializationObject;
  51383. };
  51384. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51385. /**
  51386. * Get the float animation type
  51387. */
  51388. get: function () {
  51389. return Animation._ANIMATIONTYPE_FLOAT;
  51390. },
  51391. enumerable: true,
  51392. configurable: true
  51393. });
  51394. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51395. /**
  51396. * Get the Vector3 animation type
  51397. */
  51398. get: function () {
  51399. return Animation._ANIMATIONTYPE_VECTOR3;
  51400. },
  51401. enumerable: true,
  51402. configurable: true
  51403. });
  51404. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51405. /**
  51406. * Get the Vectpr2 animation type
  51407. */
  51408. get: function () {
  51409. return Animation._ANIMATIONTYPE_VECTOR2;
  51410. },
  51411. enumerable: true,
  51412. configurable: true
  51413. });
  51414. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51415. /**
  51416. * Get the Size animation type
  51417. */
  51418. get: function () {
  51419. return Animation._ANIMATIONTYPE_SIZE;
  51420. },
  51421. enumerable: true,
  51422. configurable: true
  51423. });
  51424. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51425. /**
  51426. * Get the Quaternion animation type
  51427. */
  51428. get: function () {
  51429. return Animation._ANIMATIONTYPE_QUATERNION;
  51430. },
  51431. enumerable: true,
  51432. configurable: true
  51433. });
  51434. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51435. /**
  51436. * Get the Matrix animation type
  51437. */
  51438. get: function () {
  51439. return Animation._ANIMATIONTYPE_MATRIX;
  51440. },
  51441. enumerable: true,
  51442. configurable: true
  51443. });
  51444. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51445. /**
  51446. * Get the Color3 animation type
  51447. */
  51448. get: function () {
  51449. return Animation._ANIMATIONTYPE_COLOR3;
  51450. },
  51451. enumerable: true,
  51452. configurable: true
  51453. });
  51454. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51455. /**
  51456. * Get the Relative Loop Mode
  51457. */
  51458. get: function () {
  51459. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51460. },
  51461. enumerable: true,
  51462. configurable: true
  51463. });
  51464. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51465. /**
  51466. * Get the Cycle Loop Mode
  51467. */
  51468. get: function () {
  51469. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51470. },
  51471. enumerable: true,
  51472. configurable: true
  51473. });
  51474. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51475. /**
  51476. * Get the Constant Loop Mode
  51477. */
  51478. get: function () {
  51479. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51480. },
  51481. enumerable: true,
  51482. configurable: true
  51483. });
  51484. /** @hidden */
  51485. Animation._UniversalLerp = function (left, right, amount) {
  51486. var constructor = left.constructor;
  51487. if (constructor.Lerp) { // Lerp supported
  51488. return constructor.Lerp(left, right, amount);
  51489. }
  51490. else if (constructor.Slerp) { // Slerp supported
  51491. return constructor.Slerp(left, right, amount);
  51492. }
  51493. else if (left.toFixed) { // Number
  51494. return left * (1.0 - amount) + amount * right;
  51495. }
  51496. else { // Blending not supported
  51497. return right;
  51498. }
  51499. };
  51500. /**
  51501. * Parses an animation object and creates an animation
  51502. * @param parsedAnimation Parsed animation object
  51503. * @returns Animation object
  51504. */
  51505. Animation.Parse = function (parsedAnimation) {
  51506. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51507. var dataType = parsedAnimation.dataType;
  51508. var keys = [];
  51509. var data;
  51510. var index;
  51511. if (parsedAnimation.enableBlending) {
  51512. animation.enableBlending = parsedAnimation.enableBlending;
  51513. }
  51514. if (parsedAnimation.blendingSpeed) {
  51515. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51516. }
  51517. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51518. var key = parsedAnimation.keys[index];
  51519. var inTangent;
  51520. var outTangent;
  51521. switch (dataType) {
  51522. case Animation.ANIMATIONTYPE_FLOAT:
  51523. data = key.values[0];
  51524. if (key.values.length >= 1) {
  51525. inTangent = key.values[1];
  51526. }
  51527. if (key.values.length >= 2) {
  51528. outTangent = key.values[2];
  51529. }
  51530. break;
  51531. case Animation.ANIMATIONTYPE_QUATERNION:
  51532. data = BABYLON.Quaternion.FromArray(key.values);
  51533. if (key.values.length >= 8) {
  51534. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51535. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51536. inTangent = _inTangent;
  51537. }
  51538. }
  51539. if (key.values.length >= 12) {
  51540. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51541. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51542. outTangent = _outTangent;
  51543. }
  51544. }
  51545. break;
  51546. case Animation.ANIMATIONTYPE_MATRIX:
  51547. data = BABYLON.Matrix.FromArray(key.values);
  51548. break;
  51549. case Animation.ANIMATIONTYPE_COLOR3:
  51550. data = BABYLON.Color3.FromArray(key.values);
  51551. break;
  51552. case Animation.ANIMATIONTYPE_VECTOR3:
  51553. default:
  51554. data = BABYLON.Vector3.FromArray(key.values);
  51555. break;
  51556. }
  51557. var keyData = {};
  51558. keyData.frame = key.frame;
  51559. keyData.value = data;
  51560. if (inTangent != undefined) {
  51561. keyData.inTangent = inTangent;
  51562. }
  51563. if (outTangent != undefined) {
  51564. keyData.outTangent = outTangent;
  51565. }
  51566. keys.push(keyData);
  51567. }
  51568. animation.setKeys(keys);
  51569. if (parsedAnimation.ranges) {
  51570. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51571. data = parsedAnimation.ranges[index];
  51572. animation.createRange(data.name, data.from, data.to);
  51573. }
  51574. }
  51575. return animation;
  51576. };
  51577. /**
  51578. * Appends the serialized animations from the source animations
  51579. * @param source Source containing the animations
  51580. * @param destination Target to store the animations
  51581. */
  51582. Animation.AppendSerializedAnimations = function (source, destination) {
  51583. if (source.animations) {
  51584. destination.animations = [];
  51585. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51586. var animation = source.animations[animationIndex];
  51587. destination.animations.push(animation.serialize());
  51588. }
  51589. }
  51590. };
  51591. /**
  51592. * Use matrix interpolation instead of using direct key value when animating matrices
  51593. */
  51594. Animation.AllowMatricesInterpolation = false;
  51595. /**
  51596. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51597. */
  51598. Animation.AllowMatrixDecomposeForInterpolation = true;
  51599. // Statics
  51600. /**
  51601. * Float animation type
  51602. */
  51603. Animation._ANIMATIONTYPE_FLOAT = 0;
  51604. /**
  51605. * Vector3 animation type
  51606. */
  51607. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51608. /**
  51609. * Quaternion animation type
  51610. */
  51611. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51612. /**
  51613. * Matrix animation type
  51614. */
  51615. Animation._ANIMATIONTYPE_MATRIX = 3;
  51616. /**
  51617. * Color3 animation type
  51618. */
  51619. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51620. /**
  51621. * Vector2 animation type
  51622. */
  51623. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51624. /**
  51625. * Size animation type
  51626. */
  51627. Animation._ANIMATIONTYPE_SIZE = 6;
  51628. /**
  51629. * Relative Loop Mode
  51630. */
  51631. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51632. /**
  51633. * Cycle Loop Mode
  51634. */
  51635. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51636. /**
  51637. * Constant Loop Mode
  51638. */
  51639. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51640. return Animation;
  51641. }());
  51642. BABYLON.Animation = Animation;
  51643. })(BABYLON || (BABYLON = {}));
  51644. //# sourceMappingURL=babylon.animation.js.map
  51645. var BABYLON;
  51646. (function (BABYLON) {
  51647. /**
  51648. * This class defines the direct association between an animation and a target
  51649. */
  51650. var TargetedAnimation = /** @class */ (function () {
  51651. function TargetedAnimation() {
  51652. }
  51653. return TargetedAnimation;
  51654. }());
  51655. BABYLON.TargetedAnimation = TargetedAnimation;
  51656. /**
  51657. * Use this class to create coordinated animations on multiple targets
  51658. */
  51659. var AnimationGroup = /** @class */ (function () {
  51660. function AnimationGroup(name, scene) {
  51661. if (scene === void 0) { scene = null; }
  51662. this.name = name;
  51663. this._targetedAnimations = new Array();
  51664. this._animatables = new Array();
  51665. this._from = Number.MAX_VALUE;
  51666. this._to = -Number.MAX_VALUE;
  51667. this._speedRatio = 1;
  51668. this.onAnimationEndObservable = new BABYLON.Observable();
  51669. /**
  51670. * This observable will notify when all animations have ended.
  51671. */
  51672. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51673. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51674. this._scene.animationGroups.push(this);
  51675. }
  51676. Object.defineProperty(AnimationGroup.prototype, "from", {
  51677. /**
  51678. * Gets the first frame
  51679. */
  51680. get: function () {
  51681. return this._from;
  51682. },
  51683. enumerable: true,
  51684. configurable: true
  51685. });
  51686. Object.defineProperty(AnimationGroup.prototype, "to", {
  51687. /**
  51688. * Gets the last frame
  51689. */
  51690. get: function () {
  51691. return this._to;
  51692. },
  51693. enumerable: true,
  51694. configurable: true
  51695. });
  51696. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51697. /**
  51698. * Define if the animations are started
  51699. */
  51700. get: function () {
  51701. return this._isStarted;
  51702. },
  51703. enumerable: true,
  51704. configurable: true
  51705. });
  51706. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51707. /**
  51708. * Gets or sets the speed ratio to use for all animations
  51709. */
  51710. get: function () {
  51711. return this._speedRatio;
  51712. },
  51713. /**
  51714. * Gets or sets the speed ratio to use for all animations
  51715. */
  51716. set: function (value) {
  51717. if (this._speedRatio === value) {
  51718. return;
  51719. }
  51720. this._speedRatio = value;
  51721. for (var index = 0; index < this._animatables.length; index++) {
  51722. var animatable = this._animatables[index];
  51723. animatable.speedRatio = this._speedRatio;
  51724. }
  51725. },
  51726. enumerable: true,
  51727. configurable: true
  51728. });
  51729. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51730. /**
  51731. * Gets the targeted animations for this animation group
  51732. */
  51733. get: function () {
  51734. return this._targetedAnimations;
  51735. },
  51736. enumerable: true,
  51737. configurable: true
  51738. });
  51739. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51740. /**
  51741. * returning the list of animatables controlled by this animation group.
  51742. */
  51743. get: function () {
  51744. return this._animatables;
  51745. },
  51746. enumerable: true,
  51747. configurable: true
  51748. });
  51749. /**
  51750. * Add an animation (with its target) in the group
  51751. * @param animation defines the animation we want to add
  51752. * @param target defines the target of the animation
  51753. * @returns the {BABYLON.TargetedAnimation} object
  51754. */
  51755. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51756. var targetedAnimation = {
  51757. animation: animation,
  51758. target: target
  51759. };
  51760. var keys = animation.getKeys();
  51761. if (this._from > keys[0].frame) {
  51762. this._from = keys[0].frame;
  51763. }
  51764. if (this._to < keys[keys.length - 1].frame) {
  51765. this._to = keys[keys.length - 1].frame;
  51766. }
  51767. this._targetedAnimations.push(targetedAnimation);
  51768. return targetedAnimation;
  51769. };
  51770. /**
  51771. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51772. * It can add constant keys at begin or end
  51773. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51774. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51775. */
  51776. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51777. if (beginFrame === void 0) { beginFrame = null; }
  51778. if (endFrame === void 0) { endFrame = null; }
  51779. if (beginFrame == null)
  51780. beginFrame = this._from;
  51781. if (endFrame == null)
  51782. endFrame = this._to;
  51783. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51784. var targetedAnimation = this._targetedAnimations[index];
  51785. var keys = targetedAnimation.animation.getKeys();
  51786. var startKey = keys[0];
  51787. var endKey = keys[keys.length - 1];
  51788. if (startKey.frame > beginFrame) {
  51789. var newKey = {
  51790. frame: beginFrame,
  51791. value: startKey.value,
  51792. inTangent: startKey.inTangent,
  51793. outTangent: startKey.outTangent,
  51794. interpolation: startKey.interpolation
  51795. };
  51796. keys.splice(0, 0, newKey);
  51797. }
  51798. if (endKey.frame < endFrame) {
  51799. var newKey = {
  51800. frame: endFrame,
  51801. value: endKey.value,
  51802. inTangent: endKey.outTangent,
  51803. outTangent: endKey.outTangent,
  51804. interpolation: endKey.interpolation
  51805. };
  51806. keys.push(newKey);
  51807. }
  51808. }
  51809. this._from = beginFrame;
  51810. this._to = endFrame;
  51811. return this;
  51812. };
  51813. /**
  51814. * Start all animations on given targets
  51815. * @param loop defines if animations must loop
  51816. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51817. * @param from defines the from key (optional)
  51818. * @param to defines the to key (optional)
  51819. * @returns the current animation group
  51820. */
  51821. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51822. var _this = this;
  51823. if (loop === void 0) { loop = false; }
  51824. if (speedRatio === void 0) { speedRatio = 1; }
  51825. if (this._isStarted || this._targetedAnimations.length === 0) {
  51826. return this;
  51827. }
  51828. var _loop_1 = function (targetedAnimation) {
  51829. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51830. animatable.onAnimationEnd = function () {
  51831. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51832. _this._checkAnimationGroupEnded(animatable);
  51833. };
  51834. this_1._animatables.push(animatable);
  51835. };
  51836. var this_1 = this;
  51837. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51838. var targetedAnimation = _a[_i];
  51839. _loop_1(targetedAnimation);
  51840. }
  51841. this._speedRatio = speedRatio;
  51842. this._isStarted = true;
  51843. return this;
  51844. };
  51845. /**
  51846. * Pause all animations
  51847. */
  51848. AnimationGroup.prototype.pause = function () {
  51849. if (!this._isStarted) {
  51850. return this;
  51851. }
  51852. for (var index = 0; index < this._animatables.length; index++) {
  51853. var animatable = this._animatables[index];
  51854. animatable.pause();
  51855. }
  51856. return this;
  51857. };
  51858. /**
  51859. * Play all animations to initial state
  51860. * This function will start() the animations if they were not started or will restart() them if they were paused
  51861. * @param loop defines if animations must loop
  51862. */
  51863. AnimationGroup.prototype.play = function (loop) {
  51864. // only if all animatables are ready and exist
  51865. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51866. if (loop !== undefined) {
  51867. for (var index = 0; index < this._animatables.length; index++) {
  51868. var animatable = this._animatables[index];
  51869. animatable.loopAnimation = loop;
  51870. }
  51871. }
  51872. this.restart();
  51873. }
  51874. else {
  51875. this.stop();
  51876. this.start(loop, this._speedRatio);
  51877. }
  51878. return this;
  51879. };
  51880. /**
  51881. * Reset all animations to initial state
  51882. */
  51883. AnimationGroup.prototype.reset = function () {
  51884. if (!this._isStarted) {
  51885. return this;
  51886. }
  51887. for (var index = 0; index < this._animatables.length; index++) {
  51888. var animatable = this._animatables[index];
  51889. animatable.reset();
  51890. }
  51891. return this;
  51892. };
  51893. /**
  51894. * Restart animations from key 0
  51895. */
  51896. AnimationGroup.prototype.restart = function () {
  51897. if (!this._isStarted) {
  51898. return this;
  51899. }
  51900. for (var index = 0; index < this._animatables.length; index++) {
  51901. var animatable = this._animatables[index];
  51902. animatable.restart();
  51903. }
  51904. return this;
  51905. };
  51906. /**
  51907. * Stop all animations
  51908. */
  51909. AnimationGroup.prototype.stop = function () {
  51910. if (!this._isStarted) {
  51911. return this;
  51912. }
  51913. for (var index = 0; index < this._animatables.length; index++) {
  51914. var animatable = this._animatables[index];
  51915. animatable.stop();
  51916. }
  51917. this._isStarted = false;
  51918. return this;
  51919. };
  51920. /**
  51921. * Set animation weight for all animatables
  51922. * @param weight defines the weight to use
  51923. * @return the animationGroup
  51924. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51925. */
  51926. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51927. for (var index = 0; index < this._animatables.length; index++) {
  51928. var animatable = this._animatables[index];
  51929. animatable.weight = weight;
  51930. }
  51931. return this;
  51932. };
  51933. /**
  51934. * Synchronize and normalize all animatables with a source animatable
  51935. * @param root defines the root animatable to synchronize with
  51936. * @return the animationGroup
  51937. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51938. */
  51939. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51940. for (var index = 0; index < this._animatables.length; index++) {
  51941. var animatable = this._animatables[index];
  51942. animatable.syncWith(root);
  51943. }
  51944. return this;
  51945. };
  51946. /**
  51947. * Goes to a specific frame in this animation group
  51948. * @param frame the frame number to go to
  51949. * @return the animationGroup
  51950. */
  51951. AnimationGroup.prototype.goToFrame = function (frame) {
  51952. if (!this._isStarted) {
  51953. return this;
  51954. }
  51955. for (var index = 0; index < this._animatables.length; index++) {
  51956. var animatable = this._animatables[index];
  51957. animatable.goToFrame(frame);
  51958. }
  51959. return this;
  51960. };
  51961. /**
  51962. * Dispose all associated resources
  51963. */
  51964. AnimationGroup.prototype.dispose = function () {
  51965. this._targetedAnimations = [];
  51966. this._animatables = [];
  51967. var index = this._scene.animationGroups.indexOf(this);
  51968. if (index > -1) {
  51969. this._scene.animationGroups.splice(index, 1);
  51970. }
  51971. };
  51972. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51973. // animatable should be taken out of the array
  51974. var idx = this._animatables.indexOf(animatable);
  51975. if (idx > -1) {
  51976. this._animatables.splice(idx, 1);
  51977. }
  51978. // all animatables were removed? animation group ended!
  51979. if (this._animatables.length === 0) {
  51980. this._isStarted = false;
  51981. this.onAnimationGroupEndObservable.notifyObservers(this);
  51982. }
  51983. };
  51984. return AnimationGroup;
  51985. }());
  51986. BABYLON.AnimationGroup = AnimationGroup;
  51987. })(BABYLON || (BABYLON = {}));
  51988. //# sourceMappingURL=babylon.animationGroup.js.map
  51989. var BABYLON;
  51990. (function (BABYLON) {
  51991. /**
  51992. * Defines a runtime animation
  51993. */
  51994. var RuntimeAnimation = /** @class */ (function () {
  51995. /**
  51996. * Create a new RuntimeAnimation object
  51997. * @param target defines the target of the animation
  51998. * @param animation defines the source animation object
  51999. * @param scene defines the hosting scene
  52000. * @param host defines the initiating Animatable
  52001. */
  52002. function RuntimeAnimation(target, animation, scene, host) {
  52003. var _this = this;
  52004. this._events = new Array();
  52005. /**
  52006. * The current frame of the runtime animation
  52007. */
  52008. this._currentFrame = 0;
  52009. /**
  52010. * The original value of the runtime animation
  52011. */
  52012. this._originalValue = new Array();
  52013. /**
  52014. * The offsets cache of the runtime animation
  52015. */
  52016. this._offsetsCache = {};
  52017. /**
  52018. * The high limits cache of the runtime animation
  52019. */
  52020. this._highLimitsCache = {};
  52021. /**
  52022. * Specifies if the runtime animation has been stopped
  52023. */
  52024. this._stopped = false;
  52025. /**
  52026. * The blending factor of the runtime animation
  52027. */
  52028. this._blendingFactor = 0;
  52029. /**
  52030. * The target path of the runtime animation
  52031. */
  52032. this._targetPath = "";
  52033. /**
  52034. * The weight of the runtime animation
  52035. */
  52036. this._weight = 1.0;
  52037. /**
  52038. * The ratio offset of the runtime animation
  52039. */
  52040. this._ratioOffset = 0;
  52041. /**
  52042. * The previous delay of the runtime animation
  52043. */
  52044. this._previousDelay = 0;
  52045. /**
  52046. * The previous ratio of the runtime animation
  52047. */
  52048. this._previousRatio = 0;
  52049. this._animation = animation;
  52050. this._target = target;
  52051. this._scene = scene;
  52052. this._host = host;
  52053. animation._runtimeAnimations.push(this);
  52054. // Cloning events locally
  52055. var events = animation.getEvents();
  52056. if (events && events.length > 0) {
  52057. events.forEach(function (e) {
  52058. _this._events.push(e._clone());
  52059. });
  52060. }
  52061. }
  52062. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52063. /**
  52064. * Gets the current frame of the runtime animation
  52065. */
  52066. get: function () {
  52067. return this._currentFrame;
  52068. },
  52069. enumerable: true,
  52070. configurable: true
  52071. });
  52072. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52073. /**
  52074. * Gets the weight of the runtime animation
  52075. */
  52076. get: function () {
  52077. return this._weight;
  52078. },
  52079. enumerable: true,
  52080. configurable: true
  52081. });
  52082. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52083. /**
  52084. * Gets the current value of the runtime animation
  52085. */
  52086. get: function () {
  52087. return this._currentValue;
  52088. },
  52089. enumerable: true,
  52090. configurable: true
  52091. });
  52092. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52093. /**
  52094. * Gets the target path of the runtime animation
  52095. */
  52096. get: function () {
  52097. return this._targetPath;
  52098. },
  52099. enumerable: true,
  52100. configurable: true
  52101. });
  52102. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52103. /**
  52104. * Gets the actual target of the runtime animation
  52105. */
  52106. get: function () {
  52107. return this._activeTarget;
  52108. },
  52109. enumerable: true,
  52110. configurable: true
  52111. });
  52112. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52113. /**
  52114. * Gets the animation from the runtime animation
  52115. */
  52116. get: function () {
  52117. return this._animation;
  52118. },
  52119. enumerable: true,
  52120. configurable: true
  52121. });
  52122. /**
  52123. * Resets the runtime animation to the beginning
  52124. * @param restoreOriginal defines whether to restore the target property to the original value
  52125. */
  52126. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52127. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52128. if (restoreOriginal) {
  52129. if (this._target instanceof Array) {
  52130. var index = 0;
  52131. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52132. var target = _a[_i];
  52133. if (this._originalValue[index] !== undefined) {
  52134. this._setValue(target, this._originalValue[index], -1);
  52135. }
  52136. index++;
  52137. }
  52138. }
  52139. else {
  52140. if (this._originalValue[0] !== undefined) {
  52141. this._setValue(this._target, this._originalValue[0], -1);
  52142. }
  52143. }
  52144. }
  52145. this._offsetsCache = {};
  52146. this._highLimitsCache = {};
  52147. this._currentFrame = 0;
  52148. this._blendingFactor = 0;
  52149. this._originalValue = new Array();
  52150. // Events
  52151. for (var index = 0; index < this._events.length; index++) {
  52152. this._events[index].isDone = false;
  52153. }
  52154. };
  52155. /**
  52156. * Specifies if the runtime animation is stopped
  52157. * @returns Boolean specifying if the runtime animation is stopped
  52158. */
  52159. RuntimeAnimation.prototype.isStopped = function () {
  52160. return this._stopped;
  52161. };
  52162. /**
  52163. * Disposes of the runtime animation
  52164. */
  52165. RuntimeAnimation.prototype.dispose = function () {
  52166. var index = this._animation.runtimeAnimations.indexOf(this);
  52167. if (index > -1) {
  52168. this._animation.runtimeAnimations.splice(index, 1);
  52169. }
  52170. };
  52171. /**
  52172. * Interpolates the animation from the current frame
  52173. * @param currentFrame The frame to interpolate the animation to
  52174. * @param repeatCount The number of times that the animation should loop
  52175. * @param loopMode The type of looping mode to use
  52176. * @param offsetValue Animation offset value
  52177. * @param highLimitValue The high limit value
  52178. * @returns The interpolated value
  52179. */
  52180. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52181. this._currentFrame = currentFrame;
  52182. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52183. this._workValue = BABYLON.Matrix.Zero();
  52184. }
  52185. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52186. };
  52187. /**
  52188. * Apply the interpolated value to the target
  52189. * @param currentValue defines the value computed by the animation
  52190. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52191. */
  52192. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52193. if (weight === void 0) { weight = 1.0; }
  52194. if (this._target instanceof Array) {
  52195. var index = 0;
  52196. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52197. var target = _a[_i];
  52198. this._setValue(target, currentValue, weight, index);
  52199. index++;
  52200. }
  52201. }
  52202. else {
  52203. this._setValue(this._target, currentValue, weight);
  52204. }
  52205. };
  52206. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52207. if (targetIndex === void 0) { targetIndex = 0; }
  52208. // Set value
  52209. var path;
  52210. var destination;
  52211. var targetPropertyPath = this._animation.targetPropertyPath;
  52212. if (targetPropertyPath.length > 1) {
  52213. var property = target[targetPropertyPath[0]];
  52214. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52215. property = property[targetPropertyPath[index]];
  52216. }
  52217. path = targetPropertyPath[targetPropertyPath.length - 1];
  52218. destination = property;
  52219. }
  52220. else {
  52221. path = targetPropertyPath[0];
  52222. destination = target;
  52223. }
  52224. this._targetPath = path;
  52225. this._activeTarget = destination;
  52226. this._weight = weight;
  52227. if (this._originalValue[targetIndex] === undefined) {
  52228. var originalValue = void 0;
  52229. if (destination.getRestPose && path === "_matrix") { // For bones
  52230. originalValue = destination.getRestPose();
  52231. }
  52232. else {
  52233. originalValue = destination[path];
  52234. }
  52235. if (originalValue && originalValue.clone) {
  52236. this._originalValue[targetIndex] = originalValue.clone();
  52237. }
  52238. else {
  52239. this._originalValue[targetIndex] = originalValue;
  52240. }
  52241. }
  52242. // Blending
  52243. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52244. if (enableBlending && this._blendingFactor <= 1.0) {
  52245. if (!this._originalBlendValue) {
  52246. var originalValue = destination[path];
  52247. if (originalValue.clone) {
  52248. this._originalBlendValue = originalValue.clone();
  52249. }
  52250. else {
  52251. this._originalBlendValue = originalValue;
  52252. }
  52253. }
  52254. if (this._originalBlendValue.m) { // Matrix
  52255. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52256. if (this._currentValue) {
  52257. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52258. }
  52259. else {
  52260. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52261. }
  52262. }
  52263. else {
  52264. if (this._currentValue) {
  52265. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52266. }
  52267. else {
  52268. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52269. }
  52270. }
  52271. }
  52272. else {
  52273. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52274. }
  52275. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52276. this._blendingFactor += blendingSpeed;
  52277. }
  52278. else {
  52279. this._currentValue = currentValue;
  52280. }
  52281. if (weight !== -1.0) {
  52282. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52283. }
  52284. else {
  52285. destination[path] = this._currentValue;
  52286. }
  52287. if (target.markAsDirty) {
  52288. target.markAsDirty(this._animation.targetProperty);
  52289. }
  52290. };
  52291. /**
  52292. * Gets the loop pmode of the runtime animation
  52293. * @returns Loop Mode
  52294. */
  52295. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52296. if (this._target && this._target.animationPropertiesOverride) {
  52297. return this._target.animationPropertiesOverride.loopMode;
  52298. }
  52299. return this._animation.loopMode;
  52300. };
  52301. /**
  52302. * Move the current animation to a given frame
  52303. * @param frame defines the frame to move to
  52304. */
  52305. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52306. var keys = this._animation.getKeys();
  52307. if (frame < keys[0].frame) {
  52308. frame = keys[0].frame;
  52309. }
  52310. else if (frame > keys[keys.length - 1].frame) {
  52311. frame = keys[keys.length - 1].frame;
  52312. }
  52313. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52314. this.setValue(currentValue, -1);
  52315. };
  52316. /**
  52317. * @hidden Internal use only
  52318. */
  52319. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52320. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52321. this._ratioOffset = this._previousRatio - newRatio;
  52322. };
  52323. /**
  52324. * Execute the current animation
  52325. * @param delay defines the delay to add to the current frame
  52326. * @param from defines the lower bound of the animation range
  52327. * @param to defines the upper bound of the animation range
  52328. * @param loop defines if the current animation must loop
  52329. * @param speedRatio defines the current speed ratio
  52330. * @param weight defines the weight of the animation (default is -1 so no weight)
  52331. * @returns a boolean indicating if the animation has ended
  52332. */
  52333. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52334. if (weight === void 0) { weight = -1.0; }
  52335. var targetPropertyPath = this._animation.targetPropertyPath;
  52336. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52337. this._stopped = true;
  52338. return false;
  52339. }
  52340. var returnValue = true;
  52341. var keys = this._animation.getKeys();
  52342. // Adding a start key at frame 0 if missing
  52343. if (keys[0].frame !== 0) {
  52344. var newKey = { frame: 0, value: keys[0].value };
  52345. keys.splice(0, 0, newKey);
  52346. }
  52347. // Check limits
  52348. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52349. from = keys[0].frame;
  52350. }
  52351. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52352. to = keys[keys.length - 1].frame;
  52353. }
  52354. //to and from cannot be the same key
  52355. if (from === to) {
  52356. if (from > keys[0].frame) {
  52357. from--;
  52358. }
  52359. else if (to < keys[keys.length - 1].frame) {
  52360. to++;
  52361. }
  52362. }
  52363. // Compute ratio
  52364. var range = to - from;
  52365. var offsetValue;
  52366. // ratio represents the frame delta between from and to
  52367. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52368. var highLimitValue = 0;
  52369. this._previousDelay = delay;
  52370. this._previousRatio = ratio;
  52371. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52372. returnValue = false;
  52373. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52374. }
  52375. else {
  52376. // Get max value if required
  52377. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52378. var keyOffset = to.toString() + from.toString();
  52379. if (!this._offsetsCache[keyOffset]) {
  52380. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52381. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52382. switch (this._animation.dataType) {
  52383. // Float
  52384. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52385. this._offsetsCache[keyOffset] = toValue - fromValue;
  52386. break;
  52387. // Quaternion
  52388. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52389. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52390. break;
  52391. // Vector3
  52392. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52393. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52394. // Vector2
  52395. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52396. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52397. // Size
  52398. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52399. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52400. // Color3
  52401. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52402. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52403. default:
  52404. break;
  52405. }
  52406. this._highLimitsCache[keyOffset] = toValue;
  52407. }
  52408. highLimitValue = this._highLimitsCache[keyOffset];
  52409. offsetValue = this._offsetsCache[keyOffset];
  52410. }
  52411. }
  52412. if (offsetValue === undefined) {
  52413. switch (this._animation.dataType) {
  52414. // Float
  52415. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52416. offsetValue = 0;
  52417. break;
  52418. // Quaternion
  52419. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52420. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52421. break;
  52422. // Vector3
  52423. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52424. offsetValue = BABYLON.Vector3.Zero();
  52425. break;
  52426. // Vector2
  52427. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52428. offsetValue = BABYLON.Vector2.Zero();
  52429. break;
  52430. // Size
  52431. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52432. offsetValue = BABYLON.Size.Zero();
  52433. break;
  52434. // Color3
  52435. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52436. offsetValue = BABYLON.Color3.Black();
  52437. }
  52438. }
  52439. // Compute value
  52440. var repeatCount = (ratio / range) >> 0;
  52441. var currentFrame = returnValue ? from + ratio % range : to;
  52442. // Need to normalize?
  52443. if (this._host && this._host.syncRoot) {
  52444. var syncRoot = this._host.syncRoot;
  52445. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52446. currentFrame = from + (to - from) * hostNormalizedFrame;
  52447. }
  52448. // Reset events if looping
  52449. var events = this._events;
  52450. if (range > 0 && this.currentFrame > currentFrame ||
  52451. range < 0 && this.currentFrame < currentFrame) {
  52452. // Need to reset animation events
  52453. for (var index = 0; index < events.length; index++) {
  52454. if (!events[index].onlyOnce) {
  52455. // reset event, the animation is looping
  52456. events[index].isDone = false;
  52457. }
  52458. }
  52459. }
  52460. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52461. // Set value
  52462. this.setValue(currentValue, weight);
  52463. // Check events
  52464. for (var index = 0; index < events.length; index++) {
  52465. // Make sure current frame has passed event frame and that event frame is within the current range
  52466. // Also, handle both forward and reverse animations
  52467. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52468. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52469. var event = events[index];
  52470. if (!event.isDone) {
  52471. // If event should be done only once, remove it.
  52472. if (event.onlyOnce) {
  52473. events.splice(index, 1);
  52474. index--;
  52475. }
  52476. event.isDone = true;
  52477. event.action();
  52478. } // Don't do anything if the event has already be done.
  52479. }
  52480. }
  52481. if (!returnValue) {
  52482. this._stopped = true;
  52483. }
  52484. return returnValue;
  52485. };
  52486. return RuntimeAnimation;
  52487. }());
  52488. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52489. })(BABYLON || (BABYLON = {}));
  52490. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52491. var BABYLON;
  52492. (function (BABYLON) {
  52493. var Animatable = /** @class */ (function () {
  52494. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52495. if (fromFrame === void 0) { fromFrame = 0; }
  52496. if (toFrame === void 0) { toFrame = 100; }
  52497. if (loopAnimation === void 0) { loopAnimation = false; }
  52498. if (speedRatio === void 0) { speedRatio = 1.0; }
  52499. this.target = target;
  52500. this.fromFrame = fromFrame;
  52501. this.toFrame = toFrame;
  52502. this.loopAnimation = loopAnimation;
  52503. this.onAnimationEnd = onAnimationEnd;
  52504. this._localDelayOffset = null;
  52505. this._pausedDelay = null;
  52506. this._runtimeAnimations = new Array();
  52507. this._paused = false;
  52508. this._speedRatio = 1;
  52509. this._weight = -1.0;
  52510. this.animationStarted = false;
  52511. /**
  52512. * Observer raised when the animation ends
  52513. */
  52514. this.onAnimationEndObservable = new BABYLON.Observable();
  52515. this._scene = scene;
  52516. if (animations) {
  52517. this.appendAnimations(target, animations);
  52518. }
  52519. this._speedRatio = speedRatio;
  52520. scene._activeAnimatables.push(this);
  52521. }
  52522. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52523. /**
  52524. * Gets the root Animatable used to synchronize and normalize animations
  52525. */
  52526. get: function () {
  52527. return this._syncRoot;
  52528. },
  52529. enumerable: true,
  52530. configurable: true
  52531. });
  52532. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52533. /**
  52534. * Gets the current frame of the first RuntimeAnimation
  52535. * Used to synchronize Animatables
  52536. */
  52537. get: function () {
  52538. if (this._runtimeAnimations.length === 0) {
  52539. return 0;
  52540. }
  52541. return this._runtimeAnimations[0].currentFrame;
  52542. },
  52543. enumerable: true,
  52544. configurable: true
  52545. });
  52546. Object.defineProperty(Animatable.prototype, "weight", {
  52547. /**
  52548. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52549. */
  52550. get: function () {
  52551. return this._weight;
  52552. },
  52553. set: function (value) {
  52554. if (value === -1) { // -1 is ok and means no weight
  52555. this._weight = -1;
  52556. return;
  52557. }
  52558. // Else weight must be in [0, 1] range
  52559. this._weight = Math.min(Math.max(value, 0), 1.0);
  52560. },
  52561. enumerable: true,
  52562. configurable: true
  52563. });
  52564. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52565. /**
  52566. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52567. */
  52568. get: function () {
  52569. return this._speedRatio;
  52570. },
  52571. set: function (value) {
  52572. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52573. var animation = this._runtimeAnimations[index];
  52574. animation._prepareForSpeedRatioChange(value);
  52575. }
  52576. this._speedRatio = value;
  52577. },
  52578. enumerable: true,
  52579. configurable: true
  52580. });
  52581. // Methods
  52582. /**
  52583. * Synchronize and normalize current Animatable with a source Animatable
  52584. * This is useful when using animation weights and when animations are not of the same length
  52585. * @param root defines the root Animatable to synchronize with
  52586. * @returns the current Animatable
  52587. */
  52588. Animatable.prototype.syncWith = function (root) {
  52589. this._syncRoot = root;
  52590. if (root) {
  52591. // Make sure this animatable will animate after the root
  52592. var index = this._scene._activeAnimatables.indexOf(this);
  52593. if (index > -1) {
  52594. this._scene._activeAnimatables.splice(index, 1);
  52595. this._scene._activeAnimatables.push(this);
  52596. }
  52597. }
  52598. return this;
  52599. };
  52600. Animatable.prototype.getAnimations = function () {
  52601. return this._runtimeAnimations;
  52602. };
  52603. Animatable.prototype.appendAnimations = function (target, animations) {
  52604. for (var index = 0; index < animations.length; index++) {
  52605. var animation = animations[index];
  52606. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52607. }
  52608. };
  52609. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52610. var runtimeAnimations = this._runtimeAnimations;
  52611. for (var index = 0; index < runtimeAnimations.length; index++) {
  52612. if (runtimeAnimations[index].animation.targetProperty === property) {
  52613. return runtimeAnimations[index].animation;
  52614. }
  52615. }
  52616. return null;
  52617. };
  52618. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52619. var runtimeAnimations = this._runtimeAnimations;
  52620. for (var index = 0; index < runtimeAnimations.length; index++) {
  52621. if (runtimeAnimations[index].animation.targetProperty === property) {
  52622. return runtimeAnimations[index];
  52623. }
  52624. }
  52625. return null;
  52626. };
  52627. Animatable.prototype.reset = function () {
  52628. var runtimeAnimations = this._runtimeAnimations;
  52629. for (var index = 0; index < runtimeAnimations.length; index++) {
  52630. runtimeAnimations[index].reset(true);
  52631. }
  52632. this._localDelayOffset = null;
  52633. this._pausedDelay = null;
  52634. };
  52635. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52636. var runtimeAnimations = this._runtimeAnimations;
  52637. for (var index = 0; index < runtimeAnimations.length; index++) {
  52638. runtimeAnimations[index].animation.enableBlending = true;
  52639. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52640. }
  52641. };
  52642. Animatable.prototype.disableBlending = function () {
  52643. var runtimeAnimations = this._runtimeAnimations;
  52644. for (var index = 0; index < runtimeAnimations.length; index++) {
  52645. runtimeAnimations[index].animation.enableBlending = false;
  52646. }
  52647. };
  52648. Animatable.prototype.goToFrame = function (frame) {
  52649. var runtimeAnimations = this._runtimeAnimations;
  52650. if (runtimeAnimations[0]) {
  52651. var fps = runtimeAnimations[0].animation.framePerSecond;
  52652. var currentFrame = runtimeAnimations[0].currentFrame;
  52653. var adjustTime = frame - currentFrame;
  52654. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52655. if (this._localDelayOffset === null) {
  52656. this._localDelayOffset = 0;
  52657. }
  52658. this._localDelayOffset -= delay;
  52659. }
  52660. for (var index = 0; index < runtimeAnimations.length; index++) {
  52661. runtimeAnimations[index].goToFrame(frame);
  52662. }
  52663. };
  52664. Animatable.prototype.pause = function () {
  52665. if (this._paused) {
  52666. return;
  52667. }
  52668. this._paused = true;
  52669. };
  52670. Animatable.prototype.restart = function () {
  52671. this._paused = false;
  52672. };
  52673. Animatable.prototype._raiseOnAnimationEnd = function () {
  52674. if (this.onAnimationEnd) {
  52675. this.onAnimationEnd();
  52676. }
  52677. this.onAnimationEndObservable.notifyObservers(this);
  52678. };
  52679. Animatable.prototype.stop = function (animationName) {
  52680. if (animationName) {
  52681. var idx = this._scene._activeAnimatables.indexOf(this);
  52682. if (idx > -1) {
  52683. var runtimeAnimations = this._runtimeAnimations;
  52684. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52685. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52686. continue;
  52687. }
  52688. runtimeAnimations[index].dispose();
  52689. runtimeAnimations.splice(index, 1);
  52690. }
  52691. if (runtimeAnimations.length == 0) {
  52692. this._scene._activeAnimatables.splice(idx, 1);
  52693. this._raiseOnAnimationEnd();
  52694. }
  52695. }
  52696. }
  52697. else {
  52698. var index = this._scene._activeAnimatables.indexOf(this);
  52699. if (index > -1) {
  52700. this._scene._activeAnimatables.splice(index, 1);
  52701. var runtimeAnimations = this._runtimeAnimations;
  52702. for (var index = 0; index < runtimeAnimations.length; index++) {
  52703. runtimeAnimations[index].dispose();
  52704. }
  52705. this._raiseOnAnimationEnd();
  52706. }
  52707. }
  52708. };
  52709. /**
  52710. * Wait asynchronously for the animation to end
  52711. * @returns a promise which will be fullfilled when the animation ends
  52712. */
  52713. Animatable.prototype.waitAsync = function () {
  52714. var _this = this;
  52715. return new Promise(function (resolve, reject) {
  52716. _this.onAnimationEndObservable.add(function () {
  52717. resolve(_this);
  52718. }, undefined, undefined, _this, true);
  52719. });
  52720. };
  52721. /** @hidden */
  52722. Animatable.prototype._animate = function (delay) {
  52723. if (this._paused) {
  52724. this.animationStarted = false;
  52725. if (this._pausedDelay === null) {
  52726. this._pausedDelay = delay;
  52727. }
  52728. return true;
  52729. }
  52730. if (this._localDelayOffset === null) {
  52731. this._localDelayOffset = delay;
  52732. this._pausedDelay = null;
  52733. }
  52734. else if (this._pausedDelay !== null) {
  52735. this._localDelayOffset += delay - this._pausedDelay;
  52736. this._pausedDelay = null;
  52737. }
  52738. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52739. return true;
  52740. }
  52741. // Animating
  52742. var running = false;
  52743. var runtimeAnimations = this._runtimeAnimations;
  52744. var index;
  52745. for (index = 0; index < runtimeAnimations.length; index++) {
  52746. var animation = runtimeAnimations[index];
  52747. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52748. running = running || isRunning;
  52749. }
  52750. this.animationStarted = running;
  52751. if (!running) {
  52752. // Remove from active animatables
  52753. index = this._scene._activeAnimatables.indexOf(this);
  52754. this._scene._activeAnimatables.splice(index, 1);
  52755. // Dispose all runtime animations
  52756. for (index = 0; index < runtimeAnimations.length; index++) {
  52757. runtimeAnimations[index].dispose();
  52758. }
  52759. this._raiseOnAnimationEnd();
  52760. this.onAnimationEnd = null;
  52761. this.onAnimationEndObservable.clear();
  52762. }
  52763. return running;
  52764. };
  52765. return Animatable;
  52766. }());
  52767. BABYLON.Animatable = Animatable;
  52768. })(BABYLON || (BABYLON = {}));
  52769. //# sourceMappingURL=babylon.animatable.js.map
  52770. var BABYLON;
  52771. (function (BABYLON) {
  52772. var EasingFunction = /** @class */ (function () {
  52773. function EasingFunction() {
  52774. // Properties
  52775. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52776. }
  52777. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52778. get: function () {
  52779. return EasingFunction._EASINGMODE_EASEIN;
  52780. },
  52781. enumerable: true,
  52782. configurable: true
  52783. });
  52784. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52785. get: function () {
  52786. return EasingFunction._EASINGMODE_EASEOUT;
  52787. },
  52788. enumerable: true,
  52789. configurable: true
  52790. });
  52791. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52792. get: function () {
  52793. return EasingFunction._EASINGMODE_EASEINOUT;
  52794. },
  52795. enumerable: true,
  52796. configurable: true
  52797. });
  52798. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52799. var n = Math.min(Math.max(easingMode, 0), 2);
  52800. this._easingMode = n;
  52801. };
  52802. EasingFunction.prototype.getEasingMode = function () {
  52803. return this._easingMode;
  52804. };
  52805. EasingFunction.prototype.easeInCore = function (gradient) {
  52806. throw new Error('You must implement this method');
  52807. };
  52808. EasingFunction.prototype.ease = function (gradient) {
  52809. switch (this._easingMode) {
  52810. case EasingFunction.EASINGMODE_EASEIN:
  52811. return this.easeInCore(gradient);
  52812. case EasingFunction.EASINGMODE_EASEOUT:
  52813. return (1 - this.easeInCore(1 - gradient));
  52814. }
  52815. if (gradient >= 0.5) {
  52816. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52817. }
  52818. return (this.easeInCore(gradient * 2) * 0.5);
  52819. };
  52820. //Statics
  52821. EasingFunction._EASINGMODE_EASEIN = 0;
  52822. EasingFunction._EASINGMODE_EASEOUT = 1;
  52823. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52824. return EasingFunction;
  52825. }());
  52826. BABYLON.EasingFunction = EasingFunction;
  52827. var CircleEase = /** @class */ (function (_super) {
  52828. __extends(CircleEase, _super);
  52829. function CircleEase() {
  52830. return _super !== null && _super.apply(this, arguments) || this;
  52831. }
  52832. CircleEase.prototype.easeInCore = function (gradient) {
  52833. gradient = Math.max(0, Math.min(1, gradient));
  52834. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52835. };
  52836. return CircleEase;
  52837. }(EasingFunction));
  52838. BABYLON.CircleEase = CircleEase;
  52839. var BackEase = /** @class */ (function (_super) {
  52840. __extends(BackEase, _super);
  52841. function BackEase(amplitude) {
  52842. if (amplitude === void 0) { amplitude = 1; }
  52843. var _this = _super.call(this) || this;
  52844. _this.amplitude = amplitude;
  52845. return _this;
  52846. }
  52847. BackEase.prototype.easeInCore = function (gradient) {
  52848. var num = Math.max(0, this.amplitude);
  52849. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52850. };
  52851. return BackEase;
  52852. }(EasingFunction));
  52853. BABYLON.BackEase = BackEase;
  52854. var BounceEase = /** @class */ (function (_super) {
  52855. __extends(BounceEase, _super);
  52856. function BounceEase(bounces, bounciness) {
  52857. if (bounces === void 0) { bounces = 3; }
  52858. if (bounciness === void 0) { bounciness = 2; }
  52859. var _this = _super.call(this) || this;
  52860. _this.bounces = bounces;
  52861. _this.bounciness = bounciness;
  52862. return _this;
  52863. }
  52864. BounceEase.prototype.easeInCore = function (gradient) {
  52865. var y = Math.max(0.0, this.bounces);
  52866. var bounciness = this.bounciness;
  52867. if (bounciness <= 1.0) {
  52868. bounciness = 1.001;
  52869. }
  52870. var num9 = Math.pow(bounciness, y);
  52871. var num5 = 1.0 - bounciness;
  52872. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52873. var num15 = gradient * num4;
  52874. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52875. var num3 = Math.floor(num65);
  52876. var num13 = num3 + 1.0;
  52877. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52878. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52879. var num7 = (num8 + num12) * 0.5;
  52880. var num6 = gradient - num7;
  52881. var num2 = num7 - num8;
  52882. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52883. };
  52884. return BounceEase;
  52885. }(EasingFunction));
  52886. BABYLON.BounceEase = BounceEase;
  52887. var CubicEase = /** @class */ (function (_super) {
  52888. __extends(CubicEase, _super);
  52889. function CubicEase() {
  52890. return _super !== null && _super.apply(this, arguments) || this;
  52891. }
  52892. CubicEase.prototype.easeInCore = function (gradient) {
  52893. return (gradient * gradient * gradient);
  52894. };
  52895. return CubicEase;
  52896. }(EasingFunction));
  52897. BABYLON.CubicEase = CubicEase;
  52898. var ElasticEase = /** @class */ (function (_super) {
  52899. __extends(ElasticEase, _super);
  52900. function ElasticEase(oscillations, springiness) {
  52901. if (oscillations === void 0) { oscillations = 3; }
  52902. if (springiness === void 0) { springiness = 3; }
  52903. var _this = _super.call(this) || this;
  52904. _this.oscillations = oscillations;
  52905. _this.springiness = springiness;
  52906. return _this;
  52907. }
  52908. ElasticEase.prototype.easeInCore = function (gradient) {
  52909. var num2;
  52910. var num3 = Math.max(0.0, this.oscillations);
  52911. var num = Math.max(0.0, this.springiness);
  52912. if (num == 0) {
  52913. num2 = gradient;
  52914. }
  52915. else {
  52916. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52917. }
  52918. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52919. };
  52920. return ElasticEase;
  52921. }(EasingFunction));
  52922. BABYLON.ElasticEase = ElasticEase;
  52923. var ExponentialEase = /** @class */ (function (_super) {
  52924. __extends(ExponentialEase, _super);
  52925. function ExponentialEase(exponent) {
  52926. if (exponent === void 0) { exponent = 2; }
  52927. var _this = _super.call(this) || this;
  52928. _this.exponent = exponent;
  52929. return _this;
  52930. }
  52931. ExponentialEase.prototype.easeInCore = function (gradient) {
  52932. if (this.exponent <= 0) {
  52933. return gradient;
  52934. }
  52935. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52936. };
  52937. return ExponentialEase;
  52938. }(EasingFunction));
  52939. BABYLON.ExponentialEase = ExponentialEase;
  52940. var PowerEase = /** @class */ (function (_super) {
  52941. __extends(PowerEase, _super);
  52942. function PowerEase(power) {
  52943. if (power === void 0) { power = 2; }
  52944. var _this = _super.call(this) || this;
  52945. _this.power = power;
  52946. return _this;
  52947. }
  52948. PowerEase.prototype.easeInCore = function (gradient) {
  52949. var y = Math.max(0.0, this.power);
  52950. return Math.pow(gradient, y);
  52951. };
  52952. return PowerEase;
  52953. }(EasingFunction));
  52954. BABYLON.PowerEase = PowerEase;
  52955. var QuadraticEase = /** @class */ (function (_super) {
  52956. __extends(QuadraticEase, _super);
  52957. function QuadraticEase() {
  52958. return _super !== null && _super.apply(this, arguments) || this;
  52959. }
  52960. QuadraticEase.prototype.easeInCore = function (gradient) {
  52961. return (gradient * gradient);
  52962. };
  52963. return QuadraticEase;
  52964. }(EasingFunction));
  52965. BABYLON.QuadraticEase = QuadraticEase;
  52966. var QuarticEase = /** @class */ (function (_super) {
  52967. __extends(QuarticEase, _super);
  52968. function QuarticEase() {
  52969. return _super !== null && _super.apply(this, arguments) || this;
  52970. }
  52971. QuarticEase.prototype.easeInCore = function (gradient) {
  52972. return (gradient * gradient * gradient * gradient);
  52973. };
  52974. return QuarticEase;
  52975. }(EasingFunction));
  52976. BABYLON.QuarticEase = QuarticEase;
  52977. var QuinticEase = /** @class */ (function (_super) {
  52978. __extends(QuinticEase, _super);
  52979. function QuinticEase() {
  52980. return _super !== null && _super.apply(this, arguments) || this;
  52981. }
  52982. QuinticEase.prototype.easeInCore = function (gradient) {
  52983. return (gradient * gradient * gradient * gradient * gradient);
  52984. };
  52985. return QuinticEase;
  52986. }(EasingFunction));
  52987. BABYLON.QuinticEase = QuinticEase;
  52988. var SineEase = /** @class */ (function (_super) {
  52989. __extends(SineEase, _super);
  52990. function SineEase() {
  52991. return _super !== null && _super.apply(this, arguments) || this;
  52992. }
  52993. SineEase.prototype.easeInCore = function (gradient) {
  52994. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52995. };
  52996. return SineEase;
  52997. }(EasingFunction));
  52998. BABYLON.SineEase = SineEase;
  52999. var BezierCurveEase = /** @class */ (function (_super) {
  53000. __extends(BezierCurveEase, _super);
  53001. function BezierCurveEase(x1, y1, x2, y2) {
  53002. if (x1 === void 0) { x1 = 0; }
  53003. if (y1 === void 0) { y1 = 0; }
  53004. if (x2 === void 0) { x2 = 1; }
  53005. if (y2 === void 0) { y2 = 1; }
  53006. var _this = _super.call(this) || this;
  53007. _this.x1 = x1;
  53008. _this.y1 = y1;
  53009. _this.x2 = x2;
  53010. _this.y2 = y2;
  53011. return _this;
  53012. }
  53013. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53014. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53015. };
  53016. return BezierCurveEase;
  53017. }(EasingFunction));
  53018. BABYLON.BezierCurveEase = BezierCurveEase;
  53019. })(BABYLON || (BABYLON = {}));
  53020. //# sourceMappingURL=babylon.easing.js.map
  53021. var BABYLON;
  53022. (function (BABYLON) {
  53023. /**
  53024. * A Condition applied to an Action
  53025. */
  53026. var Condition = /** @class */ (function () {
  53027. /**
  53028. * Creates a new Condition
  53029. * @param actionManager the manager of the action the condition is applied to
  53030. */
  53031. function Condition(actionManager) {
  53032. this._actionManager = actionManager;
  53033. }
  53034. /**
  53035. * Check if the current condition is valid
  53036. * @returns a boolean
  53037. */
  53038. Condition.prototype.isValid = function () {
  53039. return true;
  53040. };
  53041. /**
  53042. * Internal only
  53043. * @hidden
  53044. */
  53045. Condition.prototype._getProperty = function (propertyPath) {
  53046. return this._actionManager._getProperty(propertyPath);
  53047. };
  53048. /**
  53049. * Internal only
  53050. * @hidden
  53051. */
  53052. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53053. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53054. };
  53055. /**
  53056. * Serialize placeholder for child classes
  53057. * @returns the serialized object
  53058. */
  53059. Condition.prototype.serialize = function () {
  53060. };
  53061. /**
  53062. * Internal only
  53063. * @hidden
  53064. */
  53065. Condition.prototype._serialize = function (serializedCondition) {
  53066. return {
  53067. type: 2,
  53068. children: [],
  53069. name: serializedCondition.name,
  53070. properties: serializedCondition.properties
  53071. };
  53072. };
  53073. return Condition;
  53074. }());
  53075. BABYLON.Condition = Condition;
  53076. /**
  53077. * Defines specific conditional operators as extensions of Condition
  53078. */
  53079. var ValueCondition = /** @class */ (function (_super) {
  53080. __extends(ValueCondition, _super);
  53081. /**
  53082. * Creates a new ValueCondition
  53083. * @param actionManager manager for the action the condition applies to
  53084. * @param target for the action
  53085. * @param propertyPath path to specify the property of the target the conditional operator uses
  53086. * @param value the value compared by the conditional operator against the current value of the property
  53087. * @param operator the conditional operator, default ValueCondition.IsEqual
  53088. */
  53089. function ValueCondition(actionManager, target,
  53090. /** path to specify the property of the target the conditional operator uses */
  53091. propertyPath,
  53092. /** the value compared by the conditional operator against the current value of the property */
  53093. value,
  53094. /** the conditional operator, default ValueCondition.IsEqual */
  53095. operator) {
  53096. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53097. var _this = _super.call(this, actionManager) || this;
  53098. _this.propertyPath = propertyPath;
  53099. _this.value = value;
  53100. _this.operator = operator;
  53101. _this._target = target;
  53102. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53103. _this._property = _this._getProperty(_this.propertyPath);
  53104. return _this;
  53105. }
  53106. Object.defineProperty(ValueCondition, "IsEqual", {
  53107. /**
  53108. * returns the number for IsEqual
  53109. */
  53110. get: function () {
  53111. return ValueCondition._IsEqual;
  53112. },
  53113. enumerable: true,
  53114. configurable: true
  53115. });
  53116. Object.defineProperty(ValueCondition, "IsDifferent", {
  53117. /**
  53118. * Returns the number for IsDifferent
  53119. */
  53120. get: function () {
  53121. return ValueCondition._IsDifferent;
  53122. },
  53123. enumerable: true,
  53124. configurable: true
  53125. });
  53126. Object.defineProperty(ValueCondition, "IsGreater", {
  53127. /**
  53128. * Returns the number for IsGreater
  53129. */
  53130. get: function () {
  53131. return ValueCondition._IsGreater;
  53132. },
  53133. enumerable: true,
  53134. configurable: true
  53135. });
  53136. Object.defineProperty(ValueCondition, "IsLesser", {
  53137. /**
  53138. * Returns the number for IsLesser
  53139. */
  53140. get: function () {
  53141. return ValueCondition._IsLesser;
  53142. },
  53143. enumerable: true,
  53144. configurable: true
  53145. });
  53146. /**
  53147. * Compares the given value with the property value for the specified conditional operator
  53148. * @returns the result of the comparison
  53149. */
  53150. ValueCondition.prototype.isValid = function () {
  53151. switch (this.operator) {
  53152. case ValueCondition.IsGreater:
  53153. return this._effectiveTarget[this._property] > this.value;
  53154. case ValueCondition.IsLesser:
  53155. return this._effectiveTarget[this._property] < this.value;
  53156. case ValueCondition.IsEqual:
  53157. case ValueCondition.IsDifferent:
  53158. var check;
  53159. if (this.value.equals) {
  53160. check = this.value.equals(this._effectiveTarget[this._property]);
  53161. }
  53162. else {
  53163. check = this.value === this._effectiveTarget[this._property];
  53164. }
  53165. return this.operator === ValueCondition.IsEqual ? check : !check;
  53166. }
  53167. return false;
  53168. };
  53169. /**
  53170. * Serialize the ValueCondition into a JSON compatible object
  53171. * @returns serialization object
  53172. */
  53173. ValueCondition.prototype.serialize = function () {
  53174. return this._serialize({
  53175. name: "ValueCondition",
  53176. properties: [
  53177. BABYLON.Action._GetTargetProperty(this._target),
  53178. { name: "propertyPath", value: this.propertyPath },
  53179. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53180. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53181. ]
  53182. });
  53183. };
  53184. /**
  53185. * Gets the name of the conditional operator for the ValueCondition
  53186. * @param operator the conditional operator
  53187. * @returns the name
  53188. */
  53189. ValueCondition.GetOperatorName = function (operator) {
  53190. switch (operator) {
  53191. case ValueCondition._IsEqual: return "IsEqual";
  53192. case ValueCondition._IsDifferent: return "IsDifferent";
  53193. case ValueCondition._IsGreater: return "IsGreater";
  53194. case ValueCondition._IsLesser: return "IsLesser";
  53195. default: return "";
  53196. }
  53197. };
  53198. /**
  53199. * Internal only
  53200. * @hidden
  53201. */
  53202. ValueCondition._IsEqual = 0;
  53203. /**
  53204. * Internal only
  53205. * @hidden
  53206. */
  53207. ValueCondition._IsDifferent = 1;
  53208. /**
  53209. * Internal only
  53210. * @hidden
  53211. */
  53212. ValueCondition._IsGreater = 2;
  53213. /**
  53214. * Internal only
  53215. * @hidden
  53216. */
  53217. ValueCondition._IsLesser = 3;
  53218. return ValueCondition;
  53219. }(Condition));
  53220. BABYLON.ValueCondition = ValueCondition;
  53221. /**
  53222. * Defines a predicate condition as an extension of Condition
  53223. */
  53224. var PredicateCondition = /** @class */ (function (_super) {
  53225. __extends(PredicateCondition, _super);
  53226. /**
  53227. * Creates a new PredicateCondition
  53228. * @param actionManager manager for the action the condition applies to
  53229. * @param predicate defines the predicate function used to validate the condition
  53230. */
  53231. function PredicateCondition(actionManager,
  53232. /** defines the predicate function used to validate the condition */
  53233. predicate) {
  53234. var _this = _super.call(this, actionManager) || this;
  53235. _this.predicate = predicate;
  53236. return _this;
  53237. }
  53238. /**
  53239. * @returns the validity of the predicate condition
  53240. */
  53241. PredicateCondition.prototype.isValid = function () {
  53242. return this.predicate();
  53243. };
  53244. return PredicateCondition;
  53245. }(Condition));
  53246. BABYLON.PredicateCondition = PredicateCondition;
  53247. /**
  53248. * Defines a state condition as an extension of Condition
  53249. */
  53250. var StateCondition = /** @class */ (function (_super) {
  53251. __extends(StateCondition, _super);
  53252. /**
  53253. * Creates a new StateCondition
  53254. * @param actionManager manager for the action the condition applies to
  53255. * @param target of the condition
  53256. * @param value to compare with target state
  53257. */
  53258. function StateCondition(actionManager, target, value) {
  53259. var _this = _super.call(this, actionManager) || this;
  53260. _this.value = value;
  53261. _this._target = target;
  53262. return _this;
  53263. }
  53264. /**
  53265. * @returns the validity of the state
  53266. */
  53267. StateCondition.prototype.isValid = function () {
  53268. return this._target.state === this.value;
  53269. };
  53270. /**
  53271. * Serialize the StateCondition into a JSON compatible object
  53272. * @returns serialization object
  53273. */
  53274. StateCondition.prototype.serialize = function () {
  53275. return this._serialize({
  53276. name: "StateCondition",
  53277. properties: [
  53278. BABYLON.Action._GetTargetProperty(this._target),
  53279. { name: "value", value: this.value }
  53280. ]
  53281. });
  53282. };
  53283. return StateCondition;
  53284. }(Condition));
  53285. BABYLON.StateCondition = StateCondition;
  53286. })(BABYLON || (BABYLON = {}));
  53287. //# sourceMappingURL=babylon.condition.js.map
  53288. var BABYLON;
  53289. (function (BABYLON) {
  53290. /**
  53291. * The action to be carried out following a trigger
  53292. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53293. */
  53294. var Action = /** @class */ (function () {
  53295. /**
  53296. * Creates a new Action
  53297. * @param triggerOptions the trigger, with or without parameters, for the action
  53298. * @param condition an optional determinant of action
  53299. */
  53300. function Action(
  53301. /** the trigger, with or without parameters, for the action */
  53302. triggerOptions, condition) {
  53303. this.triggerOptions = triggerOptions;
  53304. /**
  53305. * An event triggered prior to action being executed.
  53306. */
  53307. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53308. if (triggerOptions.parameter) {
  53309. this.trigger = triggerOptions.trigger;
  53310. this._triggerParameter = triggerOptions.parameter;
  53311. }
  53312. else {
  53313. this.trigger = triggerOptions;
  53314. }
  53315. this._nextActiveAction = this;
  53316. this._condition = condition;
  53317. }
  53318. /**
  53319. * Internal only
  53320. * @hidden
  53321. */
  53322. Action.prototype._prepare = function () {
  53323. };
  53324. /**
  53325. * Gets the trigger parameters
  53326. * @returns the trigger parameters
  53327. */
  53328. Action.prototype.getTriggerParameter = function () {
  53329. return this._triggerParameter;
  53330. };
  53331. /**
  53332. * Internal only - executes current action event
  53333. * @hidden
  53334. */
  53335. Action.prototype._executeCurrent = function (evt) {
  53336. if (this._nextActiveAction._condition) {
  53337. var condition = this._nextActiveAction._condition;
  53338. var currentRenderId = this._actionManager.getScene().getRenderId();
  53339. // We cache the current evaluation for the current frame
  53340. if (condition._evaluationId === currentRenderId) {
  53341. if (!condition._currentResult) {
  53342. return;
  53343. }
  53344. }
  53345. else {
  53346. condition._evaluationId = currentRenderId;
  53347. if (!condition.isValid()) {
  53348. condition._currentResult = false;
  53349. return;
  53350. }
  53351. condition._currentResult = true;
  53352. }
  53353. }
  53354. this.onBeforeExecuteObservable.notifyObservers(this);
  53355. this._nextActiveAction.execute(evt);
  53356. this.skipToNextActiveAction();
  53357. };
  53358. /**
  53359. * Execute placeholder for child classes
  53360. * @param evt optional action event
  53361. */
  53362. Action.prototype.execute = function (evt) {
  53363. };
  53364. /**
  53365. * Skips to next active action
  53366. */
  53367. Action.prototype.skipToNextActiveAction = function () {
  53368. if (this._nextActiveAction._child) {
  53369. if (!this._nextActiveAction._child._actionManager) {
  53370. this._nextActiveAction._child._actionManager = this._actionManager;
  53371. }
  53372. this._nextActiveAction = this._nextActiveAction._child;
  53373. }
  53374. else {
  53375. this._nextActiveAction = this;
  53376. }
  53377. };
  53378. /**
  53379. * Adds action to chain of actions, may be a DoNothingAction
  53380. * @param action defines the next action to execute
  53381. * @returns The action passed in
  53382. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53383. */
  53384. Action.prototype.then = function (action) {
  53385. this._child = action;
  53386. action._actionManager = this._actionManager;
  53387. action._prepare();
  53388. return action;
  53389. };
  53390. /**
  53391. * Internal only
  53392. * @hidden
  53393. */
  53394. Action.prototype._getProperty = function (propertyPath) {
  53395. return this._actionManager._getProperty(propertyPath);
  53396. };
  53397. /**
  53398. * Internal only
  53399. * @hidden
  53400. */
  53401. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53402. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53403. };
  53404. /**
  53405. * Serialize placeholder for child classes
  53406. * @param parent of child
  53407. * @returns the serialized object
  53408. */
  53409. Action.prototype.serialize = function (parent) {
  53410. };
  53411. /**
  53412. * Internal only called by serialize
  53413. * @hidden
  53414. */
  53415. Action.prototype._serialize = function (serializedAction, parent) {
  53416. var serializationObject = {
  53417. type: 1,
  53418. children: [],
  53419. name: serializedAction.name,
  53420. properties: serializedAction.properties || []
  53421. };
  53422. // Serialize child
  53423. if (this._child) {
  53424. this._child.serialize(serializationObject);
  53425. }
  53426. // Check if "this" has a condition
  53427. if (this._condition) {
  53428. var serializedCondition = this._condition.serialize();
  53429. serializedCondition.children.push(serializationObject);
  53430. if (parent) {
  53431. parent.children.push(serializedCondition);
  53432. }
  53433. return serializedCondition;
  53434. }
  53435. if (parent) {
  53436. parent.children.push(serializationObject);
  53437. }
  53438. return serializationObject;
  53439. };
  53440. /**
  53441. * Internal only
  53442. * @hidden
  53443. */
  53444. Action._SerializeValueAsString = function (value) {
  53445. if (typeof value === "number") {
  53446. return value.toString();
  53447. }
  53448. if (typeof value === "boolean") {
  53449. return value ? "true" : "false";
  53450. }
  53451. if (value instanceof BABYLON.Vector2) {
  53452. return value.x + ", " + value.y;
  53453. }
  53454. if (value instanceof BABYLON.Vector3) {
  53455. return value.x + ", " + value.y + ", " + value.z;
  53456. }
  53457. if (value instanceof BABYLON.Color3) {
  53458. return value.r + ", " + value.g + ", " + value.b;
  53459. }
  53460. if (value instanceof BABYLON.Color4) {
  53461. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53462. }
  53463. return value; // string
  53464. };
  53465. /**
  53466. * Internal only
  53467. * @hidden
  53468. */
  53469. Action._GetTargetProperty = function (target) {
  53470. return {
  53471. name: "target",
  53472. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53473. : target instanceof BABYLON.Light ? "LightProperties"
  53474. : target instanceof BABYLON.Camera ? "CameraProperties"
  53475. : "SceneProperties",
  53476. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53477. };
  53478. };
  53479. return Action;
  53480. }());
  53481. BABYLON.Action = Action;
  53482. })(BABYLON || (BABYLON = {}));
  53483. //# sourceMappingURL=babylon.action.js.map
  53484. var BABYLON;
  53485. (function (BABYLON) {
  53486. /**
  53487. * ActionEvent is the event being sent when an action is triggered.
  53488. */
  53489. var ActionEvent = /** @class */ (function () {
  53490. /**
  53491. * Creates a new ActionEvent
  53492. * @param source The mesh or sprite that triggered the action
  53493. * @param pointerX The X mouse cursor position at the time of the event
  53494. * @param pointerY The Y mouse cursor position at the time of the event
  53495. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53496. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53497. * @param additionalData additional data for the event
  53498. */
  53499. function ActionEvent(
  53500. /** The mesh or sprite that triggered the action */
  53501. source,
  53502. /** The X mouse cursor position at the time of the event */
  53503. pointerX,
  53504. /** The Y mouse cursor position at the time of the event */
  53505. pointerY,
  53506. /** The mesh that is currently pointed at (can be null) */
  53507. meshUnderPointer,
  53508. /** the original (browser) event that triggered the ActionEvent */
  53509. sourceEvent,
  53510. /** additional data for the event */
  53511. additionalData) {
  53512. this.source = source;
  53513. this.pointerX = pointerX;
  53514. this.pointerY = pointerY;
  53515. this.meshUnderPointer = meshUnderPointer;
  53516. this.sourceEvent = sourceEvent;
  53517. this.additionalData = additionalData;
  53518. }
  53519. /**
  53520. * Helper function to auto-create an ActionEvent from a source mesh.
  53521. * @param source The source mesh that triggered the event
  53522. * @param evt The original (browser) event
  53523. * @param additionalData additional data for the event
  53524. * @returns the new ActionEvent
  53525. */
  53526. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53527. var scene = source.getScene();
  53528. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53529. };
  53530. /**
  53531. * Helper function to auto-create an ActionEvent from a source sprite
  53532. * @param source The source sprite that triggered the event
  53533. * @param scene Scene associated with the sprite
  53534. * @param evt The original (browser) event
  53535. * @param additionalData additional data for the event
  53536. * @returns the new ActionEvent
  53537. */
  53538. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53539. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53540. };
  53541. /**
  53542. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53543. * @param scene the scene where the event occurred
  53544. * @param evt The original (browser) event
  53545. * @returns the new ActionEvent
  53546. */
  53547. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53548. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53549. };
  53550. /**
  53551. * Helper function to auto-create an ActionEvent from a primitive
  53552. * @param prim defines the target primitive
  53553. * @param pointerPos defines the pointer position
  53554. * @param evt The original (browser) event
  53555. * @param additionalData additional data for the event
  53556. * @returns the new ActionEvent
  53557. */
  53558. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53559. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53560. };
  53561. return ActionEvent;
  53562. }());
  53563. BABYLON.ActionEvent = ActionEvent;
  53564. /**
  53565. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53566. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53567. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53568. */
  53569. var ActionManager = /** @class */ (function () {
  53570. /**
  53571. * Creates a new action manager
  53572. * @param scene defines the hosting scene
  53573. */
  53574. function ActionManager(scene) {
  53575. // Members
  53576. /** Gets the list of actions */
  53577. this.actions = new Array();
  53578. /** Gets the cursor to use when hovering items */
  53579. this.hoverCursor = '';
  53580. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53581. scene._actionManagers.push(this);
  53582. }
  53583. Object.defineProperty(ActionManager, "NothingTrigger", {
  53584. /**
  53585. * Nothing
  53586. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53587. */
  53588. get: function () {
  53589. return ActionManager._NothingTrigger;
  53590. },
  53591. enumerable: true,
  53592. configurable: true
  53593. });
  53594. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53595. /**
  53596. * On pick
  53597. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53598. */
  53599. get: function () {
  53600. return ActionManager._OnPickTrigger;
  53601. },
  53602. enumerable: true,
  53603. configurable: true
  53604. });
  53605. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53606. /**
  53607. * On left pick
  53608. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53609. */
  53610. get: function () {
  53611. return ActionManager._OnLeftPickTrigger;
  53612. },
  53613. enumerable: true,
  53614. configurable: true
  53615. });
  53616. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53617. /**
  53618. * On right pick
  53619. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53620. */
  53621. get: function () {
  53622. return ActionManager._OnRightPickTrigger;
  53623. },
  53624. enumerable: true,
  53625. configurable: true
  53626. });
  53627. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53628. /**
  53629. * On center pick
  53630. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53631. */
  53632. get: function () {
  53633. return ActionManager._OnCenterPickTrigger;
  53634. },
  53635. enumerable: true,
  53636. configurable: true
  53637. });
  53638. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53639. /**
  53640. * On pick down
  53641. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53642. */
  53643. get: function () {
  53644. return ActionManager._OnPickDownTrigger;
  53645. },
  53646. enumerable: true,
  53647. configurable: true
  53648. });
  53649. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53650. /**
  53651. * On double pick
  53652. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53653. */
  53654. get: function () {
  53655. return ActionManager._OnDoublePickTrigger;
  53656. },
  53657. enumerable: true,
  53658. configurable: true
  53659. });
  53660. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53661. /**
  53662. * On pick up
  53663. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53664. */
  53665. get: function () {
  53666. return ActionManager._OnPickUpTrigger;
  53667. },
  53668. enumerable: true,
  53669. configurable: true
  53670. });
  53671. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53672. /**
  53673. * On pick out.
  53674. * This trigger will only be raised if you also declared a OnPickDown
  53675. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53676. */
  53677. get: function () {
  53678. return ActionManager._OnPickOutTrigger;
  53679. },
  53680. enumerable: true,
  53681. configurable: true
  53682. });
  53683. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53684. /**
  53685. * On long press
  53686. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53687. */
  53688. get: function () {
  53689. return ActionManager._OnLongPressTrigger;
  53690. },
  53691. enumerable: true,
  53692. configurable: true
  53693. });
  53694. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53695. /**
  53696. * On pointer over
  53697. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53698. */
  53699. get: function () {
  53700. return ActionManager._OnPointerOverTrigger;
  53701. },
  53702. enumerable: true,
  53703. configurable: true
  53704. });
  53705. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53706. /**
  53707. * On pointer out
  53708. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53709. */
  53710. get: function () {
  53711. return ActionManager._OnPointerOutTrigger;
  53712. },
  53713. enumerable: true,
  53714. configurable: true
  53715. });
  53716. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53717. /**
  53718. * On every frame
  53719. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53720. */
  53721. get: function () {
  53722. return ActionManager._OnEveryFrameTrigger;
  53723. },
  53724. enumerable: true,
  53725. configurable: true
  53726. });
  53727. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53728. /**
  53729. * On intersection enter
  53730. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53731. */
  53732. get: function () {
  53733. return ActionManager._OnIntersectionEnterTrigger;
  53734. },
  53735. enumerable: true,
  53736. configurable: true
  53737. });
  53738. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53739. /**
  53740. * On intersection exit
  53741. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53742. */
  53743. get: function () {
  53744. return ActionManager._OnIntersectionExitTrigger;
  53745. },
  53746. enumerable: true,
  53747. configurable: true
  53748. });
  53749. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53750. /**
  53751. * On key down
  53752. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53753. */
  53754. get: function () {
  53755. return ActionManager._OnKeyDownTrigger;
  53756. },
  53757. enumerable: true,
  53758. configurable: true
  53759. });
  53760. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53761. /**
  53762. * On key up
  53763. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53764. */
  53765. get: function () {
  53766. return ActionManager._OnKeyUpTrigger;
  53767. },
  53768. enumerable: true,
  53769. configurable: true
  53770. });
  53771. // Methods
  53772. /**
  53773. * Releases all associated resources
  53774. */
  53775. ActionManager.prototype.dispose = function () {
  53776. var index = this._scene._actionManagers.indexOf(this);
  53777. for (var i = 0; i < this.actions.length; i++) {
  53778. var action = this.actions[i];
  53779. ActionManager.Triggers[action.trigger]--;
  53780. if (ActionManager.Triggers[action.trigger] === 0) {
  53781. delete ActionManager.Triggers[action.trigger];
  53782. }
  53783. }
  53784. if (index > -1) {
  53785. this._scene._actionManagers.splice(index, 1);
  53786. }
  53787. };
  53788. /**
  53789. * Gets hosting scene
  53790. * @returns the hosting scene
  53791. */
  53792. ActionManager.prototype.getScene = function () {
  53793. return this._scene;
  53794. };
  53795. /**
  53796. * Does this action manager handles actions of any of the given triggers
  53797. * @param triggers defines the triggers to be tested
  53798. * @return a boolean indicating whether one (or more) of the triggers is handled
  53799. */
  53800. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53801. for (var index = 0; index < this.actions.length; index++) {
  53802. var action = this.actions[index];
  53803. if (triggers.indexOf(action.trigger) > -1) {
  53804. return true;
  53805. }
  53806. }
  53807. return false;
  53808. };
  53809. /**
  53810. * Does this action manager handles actions of a given trigger
  53811. * @param trigger defines the trigger to be tested
  53812. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53813. * @return whether the trigger is handled
  53814. */
  53815. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53816. for (var index = 0; index < this.actions.length; index++) {
  53817. var action = this.actions[index];
  53818. if (action.trigger === trigger) {
  53819. if (parameterPredicate) {
  53820. if (parameterPredicate(action.getTriggerParameter())) {
  53821. return true;
  53822. }
  53823. }
  53824. else {
  53825. return true;
  53826. }
  53827. }
  53828. }
  53829. return false;
  53830. };
  53831. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53832. /**
  53833. * Does this action manager has pointer triggers
  53834. */
  53835. get: function () {
  53836. for (var index = 0; index < this.actions.length; index++) {
  53837. var action = this.actions[index];
  53838. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53839. return true;
  53840. }
  53841. }
  53842. return false;
  53843. },
  53844. enumerable: true,
  53845. configurable: true
  53846. });
  53847. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53848. /**
  53849. * Does this action manager has pick triggers
  53850. */
  53851. get: function () {
  53852. for (var index = 0; index < this.actions.length; index++) {
  53853. var action = this.actions[index];
  53854. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53855. return true;
  53856. }
  53857. }
  53858. return false;
  53859. },
  53860. enumerable: true,
  53861. configurable: true
  53862. });
  53863. Object.defineProperty(ActionManager, "HasTriggers", {
  53864. /**
  53865. * Does exist one action manager with at least one trigger
  53866. **/
  53867. get: function () {
  53868. for (var t in ActionManager.Triggers) {
  53869. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53870. return true;
  53871. }
  53872. }
  53873. return false;
  53874. },
  53875. enumerable: true,
  53876. configurable: true
  53877. });
  53878. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53879. /**
  53880. * Does exist one action manager with at least one pick trigger
  53881. **/
  53882. get: function () {
  53883. for (var t in ActionManager.Triggers) {
  53884. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53885. var t_int = parseInt(t);
  53886. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53887. return true;
  53888. }
  53889. }
  53890. }
  53891. return false;
  53892. },
  53893. enumerable: true,
  53894. configurable: true
  53895. });
  53896. /**
  53897. * Does exist one action manager that handles actions of a given trigger
  53898. * @param trigger defines the trigger to be tested
  53899. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53900. **/
  53901. ActionManager.HasSpecificTrigger = function (trigger) {
  53902. for (var t in ActionManager.Triggers) {
  53903. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53904. var t_int = parseInt(t);
  53905. if (t_int === trigger) {
  53906. return true;
  53907. }
  53908. }
  53909. }
  53910. return false;
  53911. };
  53912. /**
  53913. * Registers an action to this action manager
  53914. * @param action defines the action to be registered
  53915. * @return the action amended (prepared) after registration
  53916. */
  53917. ActionManager.prototype.registerAction = function (action) {
  53918. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53919. if (this.getScene().actionManager !== this) {
  53920. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53921. return null;
  53922. }
  53923. }
  53924. this.actions.push(action);
  53925. if (ActionManager.Triggers[action.trigger]) {
  53926. ActionManager.Triggers[action.trigger]++;
  53927. }
  53928. else {
  53929. ActionManager.Triggers[action.trigger] = 1;
  53930. }
  53931. action._actionManager = this;
  53932. action._prepare();
  53933. return action;
  53934. };
  53935. /**
  53936. * Unregisters an action to this action manager
  53937. * @param action defines the action to be unregistered
  53938. * @return a boolean indicating whether the action has been unregistered
  53939. */
  53940. ActionManager.prototype.unregisterAction = function (action) {
  53941. var index = this.actions.indexOf(action);
  53942. if (index !== -1) {
  53943. this.actions.splice(index, 1);
  53944. ActionManager.Triggers[action.trigger] -= 1;
  53945. if (ActionManager.Triggers[action.trigger] === 0) {
  53946. delete ActionManager.Triggers[action.trigger];
  53947. }
  53948. delete action._actionManager;
  53949. return true;
  53950. }
  53951. return false;
  53952. };
  53953. /**
  53954. * Process a specific trigger
  53955. * @param trigger defines the trigger to process
  53956. * @param evt defines the event details to be processed
  53957. */
  53958. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53959. for (var index = 0; index < this.actions.length; index++) {
  53960. var action = this.actions[index];
  53961. if (action.trigger === trigger) {
  53962. if (evt) {
  53963. if (trigger === ActionManager.OnKeyUpTrigger
  53964. || trigger === ActionManager.OnKeyDownTrigger) {
  53965. var parameter = action.getTriggerParameter();
  53966. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53967. if (!parameter.toLowerCase) {
  53968. continue;
  53969. }
  53970. var lowerCase = parameter.toLowerCase();
  53971. if (lowerCase !== evt.sourceEvent.key) {
  53972. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53973. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53974. if (actualkey !== lowerCase) {
  53975. continue;
  53976. }
  53977. }
  53978. }
  53979. }
  53980. }
  53981. action._executeCurrent(evt);
  53982. }
  53983. }
  53984. };
  53985. /** @hidden */
  53986. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53987. var properties = propertyPath.split(".");
  53988. for (var index = 0; index < properties.length - 1; index++) {
  53989. target = target[properties[index]];
  53990. }
  53991. return target;
  53992. };
  53993. /** @hidden */
  53994. ActionManager.prototype._getProperty = function (propertyPath) {
  53995. var properties = propertyPath.split(".");
  53996. return properties[properties.length - 1];
  53997. };
  53998. /**
  53999. * Serialize this manager to a JSON object
  54000. * @param name defines the property name to store this manager
  54001. * @returns a JSON representation of this manager
  54002. */
  54003. ActionManager.prototype.serialize = function (name) {
  54004. var root = {
  54005. children: new Array(),
  54006. name: name,
  54007. type: 3,
  54008. properties: new Array() // Empty for root but required
  54009. };
  54010. for (var i = 0; i < this.actions.length; i++) {
  54011. var triggerObject = {
  54012. type: 0,
  54013. children: new Array(),
  54014. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54015. properties: new Array()
  54016. };
  54017. var triggerOptions = this.actions[i].triggerOptions;
  54018. if (triggerOptions && typeof triggerOptions !== "number") {
  54019. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54020. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54021. }
  54022. else {
  54023. var parameter = {};
  54024. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54025. if (triggerOptions.parameter.mesh) {
  54026. parameter._meshId = triggerOptions.parameter.mesh.id;
  54027. }
  54028. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54029. }
  54030. }
  54031. // Serialize child action, recursively
  54032. this.actions[i].serialize(triggerObject);
  54033. // Add serialized trigger
  54034. root.children.push(triggerObject);
  54035. }
  54036. return root;
  54037. };
  54038. /**
  54039. * Creates a new ActionManager from a JSON data
  54040. * @param parsedActions defines the JSON data to read from
  54041. * @param object defines the hosting mesh
  54042. * @param scene defines the hosting scene
  54043. */
  54044. ActionManager.Parse = function (parsedActions, object, scene) {
  54045. var actionManager = new ActionManager(scene);
  54046. if (object === null)
  54047. scene.actionManager = actionManager;
  54048. else
  54049. object.actionManager = actionManager;
  54050. // instanciate a new object
  54051. var instanciate = function (name, params) {
  54052. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54053. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54054. newInstance.constructor.apply(newInstance, params);
  54055. return newInstance;
  54056. };
  54057. var parseParameter = function (name, value, target, propertyPath) {
  54058. if (propertyPath === null) {
  54059. // String, boolean or float
  54060. var floatValue = parseFloat(value);
  54061. if (value === "true" || value === "false")
  54062. return value === "true";
  54063. else
  54064. return isNaN(floatValue) ? value : floatValue;
  54065. }
  54066. var effectiveTarget = propertyPath.split(".");
  54067. var values = value.split(",");
  54068. // Get effective Target
  54069. for (var i = 0; i < effectiveTarget.length; i++) {
  54070. target = target[effectiveTarget[i]];
  54071. }
  54072. // Return appropriate value with its type
  54073. if (typeof (target) === "boolean")
  54074. return values[0] === "true";
  54075. if (typeof (target) === "string")
  54076. return values[0];
  54077. // Parameters with multiple values such as Vector3 etc.
  54078. var split = new Array();
  54079. for (var i = 0; i < values.length; i++)
  54080. split.push(parseFloat(values[i]));
  54081. if (target instanceof BABYLON.Vector3)
  54082. return BABYLON.Vector3.FromArray(split);
  54083. if (target instanceof BABYLON.Vector4)
  54084. return BABYLON.Vector4.FromArray(split);
  54085. if (target instanceof BABYLON.Color3)
  54086. return BABYLON.Color3.FromArray(split);
  54087. if (target instanceof BABYLON.Color4)
  54088. return BABYLON.Color4.FromArray(split);
  54089. return parseFloat(values[0]);
  54090. };
  54091. // traverse graph per trigger
  54092. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54093. if (combineArray === void 0) { combineArray = null; }
  54094. if (parsedAction.detached)
  54095. return;
  54096. var parameters = new Array();
  54097. var target = null;
  54098. var propertyPath = null;
  54099. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54100. // Parameters
  54101. if (parsedAction.type === 2)
  54102. parameters.push(actionManager);
  54103. else
  54104. parameters.push(trigger);
  54105. if (combine) {
  54106. var actions = new Array();
  54107. for (var j = 0; j < parsedAction.combine.length; j++) {
  54108. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54109. }
  54110. parameters.push(actions);
  54111. }
  54112. else {
  54113. for (var i = 0; i < parsedAction.properties.length; i++) {
  54114. var value = parsedAction.properties[i].value;
  54115. var name = parsedAction.properties[i].name;
  54116. var targetType = parsedAction.properties[i].targetType;
  54117. if (name === "target")
  54118. if (targetType !== null && targetType === "SceneProperties")
  54119. value = target = scene;
  54120. else
  54121. value = target = scene.getNodeByName(value);
  54122. else if (name === "parent")
  54123. value = scene.getNodeByName(value);
  54124. else if (name === "sound")
  54125. value = scene.getSoundByName(value);
  54126. else if (name !== "propertyPath") {
  54127. if (parsedAction.type === 2 && name === "operator")
  54128. value = BABYLON.ValueCondition[value];
  54129. else
  54130. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54131. }
  54132. else {
  54133. propertyPath = value;
  54134. }
  54135. parameters.push(value);
  54136. }
  54137. }
  54138. if (combineArray === null) {
  54139. parameters.push(condition);
  54140. }
  54141. else {
  54142. parameters.push(null);
  54143. }
  54144. // If interpolate value action
  54145. if (parsedAction.name === "InterpolateValueAction") {
  54146. var param = parameters[parameters.length - 2];
  54147. parameters[parameters.length - 1] = param;
  54148. parameters[parameters.length - 2] = condition;
  54149. }
  54150. // Action or condition(s) and not CombineAction
  54151. var newAction = instanciate(parsedAction.name, parameters);
  54152. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54153. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54154. if (action)
  54155. action.then(nothing);
  54156. else
  54157. actionManager.registerAction(nothing);
  54158. action = nothing;
  54159. }
  54160. if (combineArray === null) {
  54161. if (newAction instanceof BABYLON.Condition) {
  54162. condition = newAction;
  54163. newAction = action;
  54164. }
  54165. else {
  54166. condition = null;
  54167. if (action)
  54168. action.then(newAction);
  54169. else
  54170. actionManager.registerAction(newAction);
  54171. }
  54172. }
  54173. else {
  54174. combineArray.push(newAction);
  54175. }
  54176. for (var i = 0; i < parsedAction.children.length; i++)
  54177. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54178. };
  54179. // triggers
  54180. for (var i = 0; i < parsedActions.children.length; i++) {
  54181. var triggerParams;
  54182. var trigger = parsedActions.children[i];
  54183. if (trigger.properties.length > 0) {
  54184. var param = trigger.properties[0].value;
  54185. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54186. if (value._meshId) {
  54187. value.mesh = scene.getMeshByID(value._meshId);
  54188. }
  54189. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54190. }
  54191. else
  54192. triggerParams = ActionManager[trigger.name];
  54193. for (var j = 0; j < trigger.children.length; j++) {
  54194. if (!trigger.detached)
  54195. traverse(trigger.children[j], triggerParams, null, null);
  54196. }
  54197. }
  54198. };
  54199. /**
  54200. * Get a trigger name by index
  54201. * @param trigger defines the trigger index
  54202. * @returns a trigger name
  54203. */
  54204. ActionManager.GetTriggerName = function (trigger) {
  54205. switch (trigger) {
  54206. case 0: return "NothingTrigger";
  54207. case 1: return "OnPickTrigger";
  54208. case 2: return "OnLeftPickTrigger";
  54209. case 3: return "OnRightPickTrigger";
  54210. case 4: return "OnCenterPickTrigger";
  54211. case 5: return "OnPickDownTrigger";
  54212. case 6: return "OnPickUpTrigger";
  54213. case 7: return "OnLongPressTrigger";
  54214. case 8: return "OnPointerOverTrigger";
  54215. case 9: return "OnPointerOutTrigger";
  54216. case 10: return "OnEveryFrameTrigger";
  54217. case 11: return "OnIntersectionEnterTrigger";
  54218. case 12: return "OnIntersectionExitTrigger";
  54219. case 13: return "OnKeyDownTrigger";
  54220. case 14: return "OnKeyUpTrigger";
  54221. case 15: return "OnPickOutTrigger";
  54222. default: return "";
  54223. }
  54224. };
  54225. // Statics
  54226. ActionManager._NothingTrigger = 0;
  54227. ActionManager._OnPickTrigger = 1;
  54228. ActionManager._OnLeftPickTrigger = 2;
  54229. ActionManager._OnRightPickTrigger = 3;
  54230. ActionManager._OnCenterPickTrigger = 4;
  54231. ActionManager._OnPickDownTrigger = 5;
  54232. ActionManager._OnDoublePickTrigger = 6;
  54233. ActionManager._OnPickUpTrigger = 7;
  54234. ActionManager._OnLongPressTrigger = 8;
  54235. ActionManager._OnPointerOverTrigger = 9;
  54236. ActionManager._OnPointerOutTrigger = 10;
  54237. ActionManager._OnEveryFrameTrigger = 11;
  54238. ActionManager._OnIntersectionEnterTrigger = 12;
  54239. ActionManager._OnIntersectionExitTrigger = 13;
  54240. ActionManager._OnKeyDownTrigger = 14;
  54241. ActionManager._OnKeyUpTrigger = 15;
  54242. ActionManager._OnPickOutTrigger = 16;
  54243. /** Gets the list of active triggers */
  54244. ActionManager.Triggers = {};
  54245. return ActionManager;
  54246. }());
  54247. BABYLON.ActionManager = ActionManager;
  54248. })(BABYLON || (BABYLON = {}));
  54249. //# sourceMappingURL=babylon.actionManager.js.map
  54250. var BABYLON;
  54251. (function (BABYLON) {
  54252. var InterpolateValueAction = /** @class */ (function (_super) {
  54253. __extends(InterpolateValueAction, _super);
  54254. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54255. if (duration === void 0) { duration = 1000; }
  54256. var _this = _super.call(this, triggerOptions, condition) || this;
  54257. _this.propertyPath = propertyPath;
  54258. _this.value = value;
  54259. _this.duration = duration;
  54260. _this.stopOtherAnimations = stopOtherAnimations;
  54261. _this.onInterpolationDone = onInterpolationDone;
  54262. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54263. _this._target = _this._effectiveTarget = target;
  54264. return _this;
  54265. }
  54266. InterpolateValueAction.prototype._prepare = function () {
  54267. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54268. this._property = this._getProperty(this.propertyPath);
  54269. };
  54270. InterpolateValueAction.prototype.execute = function () {
  54271. var _this = this;
  54272. var scene = this._actionManager.getScene();
  54273. var keys = [
  54274. {
  54275. frame: 0,
  54276. value: this._effectiveTarget[this._property]
  54277. }, {
  54278. frame: 100,
  54279. value: this.value
  54280. }
  54281. ];
  54282. var dataType;
  54283. if (typeof this.value === "number") {
  54284. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54285. }
  54286. else if (this.value instanceof BABYLON.Color3) {
  54287. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54288. }
  54289. else if (this.value instanceof BABYLON.Vector3) {
  54290. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54291. }
  54292. else if (this.value instanceof BABYLON.Matrix) {
  54293. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54294. }
  54295. else if (this.value instanceof BABYLON.Quaternion) {
  54296. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54297. }
  54298. else {
  54299. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54300. return;
  54301. }
  54302. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54303. animation.setKeys(keys);
  54304. if (this.stopOtherAnimations) {
  54305. scene.stopAnimation(this._effectiveTarget);
  54306. }
  54307. var wrapper = function () {
  54308. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54309. if (_this.onInterpolationDone) {
  54310. _this.onInterpolationDone();
  54311. }
  54312. };
  54313. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54314. };
  54315. InterpolateValueAction.prototype.serialize = function (parent) {
  54316. return _super.prototype._serialize.call(this, {
  54317. name: "InterpolateValueAction",
  54318. properties: [
  54319. BABYLON.Action._GetTargetProperty(this._target),
  54320. { name: "propertyPath", value: this.propertyPath },
  54321. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54322. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54323. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54324. ]
  54325. }, parent);
  54326. };
  54327. return InterpolateValueAction;
  54328. }(BABYLON.Action));
  54329. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54330. })(BABYLON || (BABYLON = {}));
  54331. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54332. var BABYLON;
  54333. (function (BABYLON) {
  54334. var SwitchBooleanAction = /** @class */ (function (_super) {
  54335. __extends(SwitchBooleanAction, _super);
  54336. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54337. var _this = _super.call(this, triggerOptions, condition) || this;
  54338. _this.propertyPath = propertyPath;
  54339. _this._target = _this._effectiveTarget = target;
  54340. return _this;
  54341. }
  54342. SwitchBooleanAction.prototype._prepare = function () {
  54343. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54344. this._property = this._getProperty(this.propertyPath);
  54345. };
  54346. SwitchBooleanAction.prototype.execute = function () {
  54347. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54348. };
  54349. SwitchBooleanAction.prototype.serialize = function (parent) {
  54350. return _super.prototype._serialize.call(this, {
  54351. name: "SwitchBooleanAction",
  54352. properties: [
  54353. BABYLON.Action._GetTargetProperty(this._target),
  54354. { name: "propertyPath", value: this.propertyPath }
  54355. ]
  54356. }, parent);
  54357. };
  54358. return SwitchBooleanAction;
  54359. }(BABYLON.Action));
  54360. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54361. var SetStateAction = /** @class */ (function (_super) {
  54362. __extends(SetStateAction, _super);
  54363. function SetStateAction(triggerOptions, target, value, condition) {
  54364. var _this = _super.call(this, triggerOptions, condition) || this;
  54365. _this.value = value;
  54366. _this._target = target;
  54367. return _this;
  54368. }
  54369. SetStateAction.prototype.execute = function () {
  54370. this._target.state = this.value;
  54371. };
  54372. SetStateAction.prototype.serialize = function (parent) {
  54373. return _super.prototype._serialize.call(this, {
  54374. name: "SetStateAction",
  54375. properties: [
  54376. BABYLON.Action._GetTargetProperty(this._target),
  54377. { name: "value", value: this.value }
  54378. ]
  54379. }, parent);
  54380. };
  54381. return SetStateAction;
  54382. }(BABYLON.Action));
  54383. BABYLON.SetStateAction = SetStateAction;
  54384. var SetValueAction = /** @class */ (function (_super) {
  54385. __extends(SetValueAction, _super);
  54386. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54387. var _this = _super.call(this, triggerOptions, condition) || this;
  54388. _this.propertyPath = propertyPath;
  54389. _this.value = value;
  54390. _this._target = _this._effectiveTarget = target;
  54391. return _this;
  54392. }
  54393. SetValueAction.prototype._prepare = function () {
  54394. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54395. this._property = this._getProperty(this.propertyPath);
  54396. };
  54397. SetValueAction.prototype.execute = function () {
  54398. this._effectiveTarget[this._property] = this.value;
  54399. if (this._target.markAsDirty) {
  54400. this._target.markAsDirty(this._property);
  54401. }
  54402. };
  54403. SetValueAction.prototype.serialize = function (parent) {
  54404. return _super.prototype._serialize.call(this, {
  54405. name: "SetValueAction",
  54406. properties: [
  54407. BABYLON.Action._GetTargetProperty(this._target),
  54408. { name: "propertyPath", value: this.propertyPath },
  54409. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54410. ]
  54411. }, parent);
  54412. };
  54413. return SetValueAction;
  54414. }(BABYLON.Action));
  54415. BABYLON.SetValueAction = SetValueAction;
  54416. var IncrementValueAction = /** @class */ (function (_super) {
  54417. __extends(IncrementValueAction, _super);
  54418. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54419. var _this = _super.call(this, triggerOptions, condition) || this;
  54420. _this.propertyPath = propertyPath;
  54421. _this.value = value;
  54422. _this._target = _this._effectiveTarget = target;
  54423. return _this;
  54424. }
  54425. IncrementValueAction.prototype._prepare = function () {
  54426. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54427. this._property = this._getProperty(this.propertyPath);
  54428. if (typeof this._effectiveTarget[this._property] !== "number") {
  54429. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54430. }
  54431. };
  54432. IncrementValueAction.prototype.execute = function () {
  54433. this._effectiveTarget[this._property] += this.value;
  54434. if (this._target.markAsDirty) {
  54435. this._target.markAsDirty(this._property);
  54436. }
  54437. };
  54438. IncrementValueAction.prototype.serialize = function (parent) {
  54439. return _super.prototype._serialize.call(this, {
  54440. name: "IncrementValueAction",
  54441. properties: [
  54442. BABYLON.Action._GetTargetProperty(this._target),
  54443. { name: "propertyPath", value: this.propertyPath },
  54444. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54445. ]
  54446. }, parent);
  54447. };
  54448. return IncrementValueAction;
  54449. }(BABYLON.Action));
  54450. BABYLON.IncrementValueAction = IncrementValueAction;
  54451. var PlayAnimationAction = /** @class */ (function (_super) {
  54452. __extends(PlayAnimationAction, _super);
  54453. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54454. var _this = _super.call(this, triggerOptions, condition) || this;
  54455. _this.from = from;
  54456. _this.to = to;
  54457. _this.loop = loop;
  54458. _this._target = target;
  54459. return _this;
  54460. }
  54461. PlayAnimationAction.prototype._prepare = function () {
  54462. };
  54463. PlayAnimationAction.prototype.execute = function () {
  54464. var scene = this._actionManager.getScene();
  54465. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54466. };
  54467. PlayAnimationAction.prototype.serialize = function (parent) {
  54468. return _super.prototype._serialize.call(this, {
  54469. name: "PlayAnimationAction",
  54470. properties: [
  54471. BABYLON.Action._GetTargetProperty(this._target),
  54472. { name: "from", value: String(this.from) },
  54473. { name: "to", value: String(this.to) },
  54474. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54475. ]
  54476. }, parent);
  54477. };
  54478. return PlayAnimationAction;
  54479. }(BABYLON.Action));
  54480. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54481. var StopAnimationAction = /** @class */ (function (_super) {
  54482. __extends(StopAnimationAction, _super);
  54483. function StopAnimationAction(triggerOptions, target, condition) {
  54484. var _this = _super.call(this, triggerOptions, condition) || this;
  54485. _this._target = target;
  54486. return _this;
  54487. }
  54488. StopAnimationAction.prototype._prepare = function () {
  54489. };
  54490. StopAnimationAction.prototype.execute = function () {
  54491. var scene = this._actionManager.getScene();
  54492. scene.stopAnimation(this._target);
  54493. };
  54494. StopAnimationAction.prototype.serialize = function (parent) {
  54495. return _super.prototype._serialize.call(this, {
  54496. name: "StopAnimationAction",
  54497. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54498. }, parent);
  54499. };
  54500. return StopAnimationAction;
  54501. }(BABYLON.Action));
  54502. BABYLON.StopAnimationAction = StopAnimationAction;
  54503. var DoNothingAction = /** @class */ (function (_super) {
  54504. __extends(DoNothingAction, _super);
  54505. function DoNothingAction(triggerOptions, condition) {
  54506. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54507. return _super.call(this, triggerOptions, condition) || this;
  54508. }
  54509. DoNothingAction.prototype.execute = function () {
  54510. };
  54511. DoNothingAction.prototype.serialize = function (parent) {
  54512. return _super.prototype._serialize.call(this, {
  54513. name: "DoNothingAction",
  54514. properties: []
  54515. }, parent);
  54516. };
  54517. return DoNothingAction;
  54518. }(BABYLON.Action));
  54519. BABYLON.DoNothingAction = DoNothingAction;
  54520. var CombineAction = /** @class */ (function (_super) {
  54521. __extends(CombineAction, _super);
  54522. function CombineAction(triggerOptions, children, condition) {
  54523. var _this = _super.call(this, triggerOptions, condition) || this;
  54524. _this.children = children;
  54525. return _this;
  54526. }
  54527. CombineAction.prototype._prepare = function () {
  54528. for (var index = 0; index < this.children.length; index++) {
  54529. this.children[index]._actionManager = this._actionManager;
  54530. this.children[index]._prepare();
  54531. }
  54532. };
  54533. CombineAction.prototype.execute = function (evt) {
  54534. for (var index = 0; index < this.children.length; index++) {
  54535. this.children[index].execute(evt);
  54536. }
  54537. };
  54538. CombineAction.prototype.serialize = function (parent) {
  54539. var serializationObject = _super.prototype._serialize.call(this, {
  54540. name: "CombineAction",
  54541. properties: [],
  54542. combine: []
  54543. }, parent);
  54544. for (var i = 0; i < this.children.length; i++) {
  54545. serializationObject.combine.push(this.children[i].serialize(null));
  54546. }
  54547. return serializationObject;
  54548. };
  54549. return CombineAction;
  54550. }(BABYLON.Action));
  54551. BABYLON.CombineAction = CombineAction;
  54552. var ExecuteCodeAction = /** @class */ (function (_super) {
  54553. __extends(ExecuteCodeAction, _super);
  54554. function ExecuteCodeAction(triggerOptions, func, condition) {
  54555. var _this = _super.call(this, triggerOptions, condition) || this;
  54556. _this.func = func;
  54557. return _this;
  54558. }
  54559. ExecuteCodeAction.prototype.execute = function (evt) {
  54560. this.func(evt);
  54561. };
  54562. return ExecuteCodeAction;
  54563. }(BABYLON.Action));
  54564. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54565. var SetParentAction = /** @class */ (function (_super) {
  54566. __extends(SetParentAction, _super);
  54567. function SetParentAction(triggerOptions, target, parent, condition) {
  54568. var _this = _super.call(this, triggerOptions, condition) || this;
  54569. _this._target = target;
  54570. _this._parent = parent;
  54571. return _this;
  54572. }
  54573. SetParentAction.prototype._prepare = function () {
  54574. };
  54575. SetParentAction.prototype.execute = function () {
  54576. if (this._target.parent === this._parent) {
  54577. return;
  54578. }
  54579. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54580. invertParentWorldMatrix.invert();
  54581. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54582. this._target.parent = this._parent;
  54583. };
  54584. SetParentAction.prototype.serialize = function (parent) {
  54585. return _super.prototype._serialize.call(this, {
  54586. name: "SetParentAction",
  54587. properties: [
  54588. BABYLON.Action._GetTargetProperty(this._target),
  54589. BABYLON.Action._GetTargetProperty(this._parent),
  54590. ]
  54591. }, parent);
  54592. };
  54593. return SetParentAction;
  54594. }(BABYLON.Action));
  54595. BABYLON.SetParentAction = SetParentAction;
  54596. var PlaySoundAction = /** @class */ (function (_super) {
  54597. __extends(PlaySoundAction, _super);
  54598. function PlaySoundAction(triggerOptions, sound, condition) {
  54599. var _this = _super.call(this, triggerOptions, condition) || this;
  54600. _this._sound = sound;
  54601. return _this;
  54602. }
  54603. PlaySoundAction.prototype._prepare = function () {
  54604. };
  54605. PlaySoundAction.prototype.execute = function () {
  54606. if (this._sound !== undefined)
  54607. this._sound.play();
  54608. };
  54609. PlaySoundAction.prototype.serialize = function (parent) {
  54610. return _super.prototype._serialize.call(this, {
  54611. name: "PlaySoundAction",
  54612. properties: [{ name: "sound", value: this._sound.name }]
  54613. }, parent);
  54614. };
  54615. return PlaySoundAction;
  54616. }(BABYLON.Action));
  54617. BABYLON.PlaySoundAction = PlaySoundAction;
  54618. var StopSoundAction = /** @class */ (function (_super) {
  54619. __extends(StopSoundAction, _super);
  54620. function StopSoundAction(triggerOptions, sound, condition) {
  54621. var _this = _super.call(this, triggerOptions, condition) || this;
  54622. _this._sound = sound;
  54623. return _this;
  54624. }
  54625. StopSoundAction.prototype._prepare = function () {
  54626. };
  54627. StopSoundAction.prototype.execute = function () {
  54628. if (this._sound !== undefined)
  54629. this._sound.stop();
  54630. };
  54631. StopSoundAction.prototype.serialize = function (parent) {
  54632. return _super.prototype._serialize.call(this, {
  54633. name: "StopSoundAction",
  54634. properties: [{ name: "sound", value: this._sound.name }]
  54635. }, parent);
  54636. };
  54637. return StopSoundAction;
  54638. }(BABYLON.Action));
  54639. BABYLON.StopSoundAction = StopSoundAction;
  54640. })(BABYLON || (BABYLON = {}));
  54641. //# sourceMappingURL=babylon.directActions.js.map
  54642. var BABYLON;
  54643. (function (BABYLON) {
  54644. var SpriteManager = /** @class */ (function () {
  54645. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54646. if (epsilon === void 0) { epsilon = 0.01; }
  54647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54648. this.name = name;
  54649. this.sprites = new Array();
  54650. this.renderingGroupId = 0;
  54651. this.layerMask = 0x0FFFFFFF;
  54652. this.fogEnabled = true;
  54653. this.isPickable = false;
  54654. /**
  54655. * An event triggered when the manager is disposed.
  54656. */
  54657. this.onDisposeObservable = new BABYLON.Observable();
  54658. this._vertexBuffers = {};
  54659. this._capacity = capacity;
  54660. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54661. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54662. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54663. if (cellSize.width && cellSize.height) {
  54664. this.cellWidth = cellSize.width;
  54665. this.cellHeight = cellSize.height;
  54666. }
  54667. else if (cellSize !== undefined) {
  54668. this.cellWidth = cellSize;
  54669. this.cellHeight = cellSize;
  54670. }
  54671. else {
  54672. return;
  54673. }
  54674. this._epsilon = epsilon;
  54675. this._scene = scene;
  54676. this._scene.spriteManagers.push(this);
  54677. var indices = [];
  54678. var index = 0;
  54679. for (var count = 0; count < capacity; count++) {
  54680. indices.push(index);
  54681. indices.push(index + 1);
  54682. indices.push(index + 2);
  54683. indices.push(index);
  54684. indices.push(index + 2);
  54685. indices.push(index + 3);
  54686. index += 4;
  54687. }
  54688. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54689. // VBO
  54690. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54691. this._vertexData = new Float32Array(capacity * 16 * 4);
  54692. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54693. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54694. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54695. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54696. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54697. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54698. this._vertexBuffers["options"] = options;
  54699. this._vertexBuffers["cellInfo"] = cellInfo;
  54700. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54701. // Effects
  54702. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54703. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54704. }
  54705. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54706. set: function (callback) {
  54707. if (this._onDisposeObserver) {
  54708. this.onDisposeObservable.remove(this._onDisposeObserver);
  54709. }
  54710. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54711. },
  54712. enumerable: true,
  54713. configurable: true
  54714. });
  54715. Object.defineProperty(SpriteManager.prototype, "texture", {
  54716. get: function () {
  54717. return this._spriteTexture;
  54718. },
  54719. set: function (value) {
  54720. this._spriteTexture = value;
  54721. },
  54722. enumerable: true,
  54723. configurable: true
  54724. });
  54725. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54726. var arrayOffset = index * 16;
  54727. if (offsetX === 0)
  54728. offsetX = this._epsilon;
  54729. else if (offsetX === 1)
  54730. offsetX = 1 - this._epsilon;
  54731. if (offsetY === 0)
  54732. offsetY = this._epsilon;
  54733. else if (offsetY === 1)
  54734. offsetY = 1 - this._epsilon;
  54735. this._vertexData[arrayOffset] = sprite.position.x;
  54736. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54737. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54738. this._vertexData[arrayOffset + 3] = sprite.angle;
  54739. this._vertexData[arrayOffset + 4] = sprite.width;
  54740. this._vertexData[arrayOffset + 5] = sprite.height;
  54741. this._vertexData[arrayOffset + 6] = offsetX;
  54742. this._vertexData[arrayOffset + 7] = offsetY;
  54743. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54744. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54745. var offset = (sprite.cellIndex / rowSize) >> 0;
  54746. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54747. this._vertexData[arrayOffset + 11] = offset;
  54748. // Color
  54749. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54750. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54751. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54752. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54753. };
  54754. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54755. var count = Math.min(this._capacity, this.sprites.length);
  54756. var min = BABYLON.Vector3.Zero();
  54757. var max = BABYLON.Vector3.Zero();
  54758. var distance = Number.MAX_VALUE;
  54759. var currentSprite = null;
  54760. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54761. var cameraView = camera.getViewMatrix();
  54762. for (var index = 0; index < count; index++) {
  54763. var sprite = this.sprites[index];
  54764. if (!sprite) {
  54765. continue;
  54766. }
  54767. if (predicate) {
  54768. if (!predicate(sprite)) {
  54769. continue;
  54770. }
  54771. }
  54772. else if (!sprite.isPickable) {
  54773. continue;
  54774. }
  54775. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54776. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54777. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54778. if (ray.intersectsBoxMinMax(min, max)) {
  54779. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54780. if (distance > currentDistance) {
  54781. distance = currentDistance;
  54782. currentSprite = sprite;
  54783. if (fastCheck) {
  54784. break;
  54785. }
  54786. }
  54787. }
  54788. }
  54789. if (currentSprite) {
  54790. var result = new BABYLON.PickingInfo();
  54791. result.hit = true;
  54792. result.pickedSprite = currentSprite;
  54793. result.distance = distance;
  54794. return result;
  54795. }
  54796. return null;
  54797. };
  54798. SpriteManager.prototype.render = function () {
  54799. // Check
  54800. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54801. return;
  54802. var engine = this._scene.getEngine();
  54803. var baseSize = this._spriteTexture.getBaseSize();
  54804. // Sprites
  54805. var deltaTime = engine.getDeltaTime();
  54806. var max = Math.min(this._capacity, this.sprites.length);
  54807. var rowSize = baseSize.width / this.cellWidth;
  54808. var offset = 0;
  54809. for (var index = 0; index < max; index++) {
  54810. var sprite = this.sprites[index];
  54811. if (!sprite) {
  54812. continue;
  54813. }
  54814. sprite._animate(deltaTime);
  54815. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54816. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54817. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54818. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54819. }
  54820. this._buffer.update(this._vertexData);
  54821. // Render
  54822. var effect = this._effectBase;
  54823. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54824. effect = this._effectFog;
  54825. }
  54826. engine.enableEffect(effect);
  54827. var viewMatrix = this._scene.getViewMatrix();
  54828. effect.setTexture("diffuseSampler", this._spriteTexture);
  54829. effect.setMatrix("view", viewMatrix);
  54830. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54831. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54832. // Fog
  54833. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54834. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54835. effect.setColor3("vFogColor", this._scene.fogColor);
  54836. }
  54837. // VBOs
  54838. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54839. // Draw order
  54840. engine.setDepthFunctionToLessOrEqual();
  54841. effect.setBool("alphaTest", true);
  54842. engine.setColorWrite(false);
  54843. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54844. engine.setColorWrite(true);
  54845. effect.setBool("alphaTest", false);
  54846. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54847. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54848. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54849. };
  54850. SpriteManager.prototype.dispose = function () {
  54851. if (this._buffer) {
  54852. this._buffer.dispose();
  54853. this._buffer = null;
  54854. }
  54855. if (this._indexBuffer) {
  54856. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54857. this._indexBuffer = null;
  54858. }
  54859. if (this._spriteTexture) {
  54860. this._spriteTexture.dispose();
  54861. this._spriteTexture = null;
  54862. }
  54863. // Remove from scene
  54864. var index = this._scene.spriteManagers.indexOf(this);
  54865. this._scene.spriteManagers.splice(index, 1);
  54866. // Callback
  54867. this.onDisposeObservable.notifyObservers(this);
  54868. this.onDisposeObservable.clear();
  54869. };
  54870. return SpriteManager;
  54871. }());
  54872. BABYLON.SpriteManager = SpriteManager;
  54873. })(BABYLON || (BABYLON = {}));
  54874. //# sourceMappingURL=babylon.spriteManager.js.map
  54875. var BABYLON;
  54876. (function (BABYLON) {
  54877. var Sprite = /** @class */ (function () {
  54878. function Sprite(name, manager) {
  54879. this.name = name;
  54880. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54881. this.width = 1.0;
  54882. this.height = 1.0;
  54883. this.angle = 0;
  54884. this.cellIndex = 0;
  54885. this.invertU = 0;
  54886. this.invertV = 0;
  54887. this.animations = new Array();
  54888. this.isPickable = false;
  54889. this._animationStarted = false;
  54890. this._loopAnimation = false;
  54891. this._fromIndex = 0;
  54892. this._toIndex = 0;
  54893. this._delay = 0;
  54894. this._direction = 1;
  54895. this._time = 0;
  54896. this._manager = manager;
  54897. this._manager.sprites.push(this);
  54898. this.position = BABYLON.Vector3.Zero();
  54899. }
  54900. Object.defineProperty(Sprite.prototype, "size", {
  54901. get: function () {
  54902. return this.width;
  54903. },
  54904. set: function (value) {
  54905. this.width = value;
  54906. this.height = value;
  54907. },
  54908. enumerable: true,
  54909. configurable: true
  54910. });
  54911. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54912. this._fromIndex = from;
  54913. this._toIndex = to;
  54914. this._loopAnimation = loop;
  54915. this._delay = delay;
  54916. this._animationStarted = true;
  54917. this._direction = from < to ? 1 : -1;
  54918. this.cellIndex = from;
  54919. this._time = 0;
  54920. this._onAnimationEnd = onAnimationEnd;
  54921. };
  54922. Sprite.prototype.stopAnimation = function () {
  54923. this._animationStarted = false;
  54924. };
  54925. Sprite.prototype._animate = function (deltaTime) {
  54926. if (!this._animationStarted)
  54927. return;
  54928. this._time += deltaTime;
  54929. if (this._time > this._delay) {
  54930. this._time = this._time % this._delay;
  54931. this.cellIndex += this._direction;
  54932. if (this.cellIndex > this._toIndex) {
  54933. if (this._loopAnimation) {
  54934. this.cellIndex = this._fromIndex;
  54935. }
  54936. else {
  54937. this.cellIndex = this._toIndex;
  54938. this._animationStarted = false;
  54939. if (this._onAnimationEnd) {
  54940. this._onAnimationEnd();
  54941. }
  54942. if (this.disposeWhenFinishedAnimating) {
  54943. this.dispose();
  54944. }
  54945. }
  54946. }
  54947. }
  54948. };
  54949. Sprite.prototype.dispose = function () {
  54950. for (var i = 0; i < this._manager.sprites.length; i++) {
  54951. if (this._manager.sprites[i] == this) {
  54952. this._manager.sprites.splice(i, 1);
  54953. }
  54954. }
  54955. };
  54956. return Sprite;
  54957. }());
  54958. BABYLON.Sprite = Sprite;
  54959. })(BABYLON || (BABYLON = {}));
  54960. //# sourceMappingURL=babylon.sprite.js.map
  54961. var BABYLON;
  54962. (function (BABYLON) {
  54963. var IntersectionInfo = /** @class */ (function () {
  54964. function IntersectionInfo(bu, bv, distance) {
  54965. this.bu = bu;
  54966. this.bv = bv;
  54967. this.distance = distance;
  54968. this.faceId = 0;
  54969. this.subMeshId = 0;
  54970. }
  54971. return IntersectionInfo;
  54972. }());
  54973. BABYLON.IntersectionInfo = IntersectionInfo;
  54974. /**
  54975. * Information about the result of picking within a scene
  54976. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54977. */
  54978. var PickingInfo = /** @class */ (function () {
  54979. function PickingInfo() {
  54980. /**
  54981. * If the pick collided with an object
  54982. */
  54983. this.hit = false;
  54984. /**
  54985. * Distance away where the pick collided
  54986. */
  54987. this.distance = 0;
  54988. /**
  54989. * The location of pick collision
  54990. */
  54991. this.pickedPoint = null;
  54992. /**
  54993. * The mesh corrisponding the the pick collision
  54994. */
  54995. this.pickedMesh = null;
  54996. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54997. this.bu = 0;
  54998. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54999. this.bv = 0;
  55000. /** The id of the face on the mesh that was picked */
  55001. this.faceId = -1;
  55002. /** Id of the the submesh that was picked */
  55003. this.subMeshId = 0;
  55004. /** If a sprite was picked, this will be the sprite the pick collided with */
  55005. this.pickedSprite = null;
  55006. /**
  55007. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55008. */
  55009. this.originMesh = null;
  55010. /**
  55011. * The ray that was used to perform the picking.
  55012. */
  55013. this.ray = null;
  55014. }
  55015. /**
  55016. * Gets the normal corrispodning to the face the pick collided with
  55017. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55018. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55019. * @returns The normal corrispodning to the face the pick collided with
  55020. */
  55021. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55022. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55023. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55024. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55025. return null;
  55026. }
  55027. var indices = this.pickedMesh.getIndices();
  55028. if (!indices) {
  55029. return null;
  55030. }
  55031. var result;
  55032. if (useVerticesNormals) {
  55033. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55034. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55035. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55036. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55037. normal0 = normal0.scale(this.bu);
  55038. normal1 = normal1.scale(this.bv);
  55039. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55040. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55041. }
  55042. else {
  55043. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55044. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55045. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55046. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55047. var p1p2 = vertex1.subtract(vertex2);
  55048. var p3p2 = vertex3.subtract(vertex2);
  55049. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55050. }
  55051. if (useWorldCoordinates) {
  55052. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55053. }
  55054. return BABYLON.Vector3.Normalize(result);
  55055. };
  55056. /**
  55057. * Gets the texture coordinates of where the pick occured
  55058. * @returns the vector containing the coordnates of the texture
  55059. */
  55060. PickingInfo.prototype.getTextureCoordinates = function () {
  55061. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55062. return null;
  55063. }
  55064. var indices = this.pickedMesh.getIndices();
  55065. if (!indices) {
  55066. return null;
  55067. }
  55068. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55069. if (!uvs) {
  55070. return null;
  55071. }
  55072. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55073. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55074. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55075. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55076. uv1 = uv1.scale(this.bu);
  55077. uv2 = uv2.scale(this.bv);
  55078. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55079. };
  55080. return PickingInfo;
  55081. }());
  55082. BABYLON.PickingInfo = PickingInfo;
  55083. })(BABYLON || (BABYLON = {}));
  55084. //# sourceMappingURL=babylon.pickingInfo.js.map
  55085. var BABYLON;
  55086. (function (BABYLON) {
  55087. var Ray = /** @class */ (function () {
  55088. function Ray(origin, direction, length) {
  55089. if (length === void 0) { length = Number.MAX_VALUE; }
  55090. this.origin = origin;
  55091. this.direction = direction;
  55092. this.length = length;
  55093. }
  55094. // Methods
  55095. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55096. var d = 0.0;
  55097. var maxValue = Number.MAX_VALUE;
  55098. var inv;
  55099. var min;
  55100. var max;
  55101. var temp;
  55102. if (Math.abs(this.direction.x) < 0.0000001) {
  55103. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55104. return false;
  55105. }
  55106. }
  55107. else {
  55108. inv = 1.0 / this.direction.x;
  55109. min = (minimum.x - this.origin.x) * inv;
  55110. max = (maximum.x - this.origin.x) * inv;
  55111. if (max === -Infinity) {
  55112. max = Infinity;
  55113. }
  55114. if (min > max) {
  55115. temp = min;
  55116. min = max;
  55117. max = temp;
  55118. }
  55119. d = Math.max(min, d);
  55120. maxValue = Math.min(max, maxValue);
  55121. if (d > maxValue) {
  55122. return false;
  55123. }
  55124. }
  55125. if (Math.abs(this.direction.y) < 0.0000001) {
  55126. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55127. return false;
  55128. }
  55129. }
  55130. else {
  55131. inv = 1.0 / this.direction.y;
  55132. min = (minimum.y - this.origin.y) * inv;
  55133. max = (maximum.y - this.origin.y) * inv;
  55134. if (max === -Infinity) {
  55135. max = Infinity;
  55136. }
  55137. if (min > max) {
  55138. temp = min;
  55139. min = max;
  55140. max = temp;
  55141. }
  55142. d = Math.max(min, d);
  55143. maxValue = Math.min(max, maxValue);
  55144. if (d > maxValue) {
  55145. return false;
  55146. }
  55147. }
  55148. if (Math.abs(this.direction.z) < 0.0000001) {
  55149. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55150. return false;
  55151. }
  55152. }
  55153. else {
  55154. inv = 1.0 / this.direction.z;
  55155. min = (minimum.z - this.origin.z) * inv;
  55156. max = (maximum.z - this.origin.z) * inv;
  55157. if (max === -Infinity) {
  55158. max = Infinity;
  55159. }
  55160. if (min > max) {
  55161. temp = min;
  55162. min = max;
  55163. max = temp;
  55164. }
  55165. d = Math.max(min, d);
  55166. maxValue = Math.min(max, maxValue);
  55167. if (d > maxValue) {
  55168. return false;
  55169. }
  55170. }
  55171. return true;
  55172. };
  55173. Ray.prototype.intersectsBox = function (box) {
  55174. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55175. };
  55176. Ray.prototype.intersectsSphere = function (sphere) {
  55177. var x = sphere.center.x - this.origin.x;
  55178. var y = sphere.center.y - this.origin.y;
  55179. var z = sphere.center.z - this.origin.z;
  55180. var pyth = (x * x) + (y * y) + (z * z);
  55181. var rr = sphere.radius * sphere.radius;
  55182. if (pyth <= rr) {
  55183. return true;
  55184. }
  55185. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55186. if (dot < 0.0) {
  55187. return false;
  55188. }
  55189. var temp = pyth - (dot * dot);
  55190. return temp <= rr;
  55191. };
  55192. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55193. if (!this._edge1) {
  55194. this._edge1 = BABYLON.Vector3.Zero();
  55195. this._edge2 = BABYLON.Vector3.Zero();
  55196. this._pvec = BABYLON.Vector3.Zero();
  55197. this._tvec = BABYLON.Vector3.Zero();
  55198. this._qvec = BABYLON.Vector3.Zero();
  55199. }
  55200. vertex1.subtractToRef(vertex0, this._edge1);
  55201. vertex2.subtractToRef(vertex0, this._edge2);
  55202. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55203. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55204. if (det === 0) {
  55205. return null;
  55206. }
  55207. var invdet = 1 / det;
  55208. this.origin.subtractToRef(vertex0, this._tvec);
  55209. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55210. if (bu < 0 || bu > 1.0) {
  55211. return null;
  55212. }
  55213. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55214. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55215. if (bv < 0 || bu + bv > 1.0) {
  55216. return null;
  55217. }
  55218. //check if the distance is longer than the predefined length.
  55219. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55220. if (distance > this.length) {
  55221. return null;
  55222. }
  55223. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55224. };
  55225. Ray.prototype.intersectsPlane = function (plane) {
  55226. var distance;
  55227. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55228. if (Math.abs(result1) < 9.99999997475243E-07) {
  55229. return null;
  55230. }
  55231. else {
  55232. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55233. distance = (-plane.d - result2) / result1;
  55234. if (distance < 0.0) {
  55235. if (distance < -9.99999997475243E-07) {
  55236. return null;
  55237. }
  55238. else {
  55239. return 0;
  55240. }
  55241. }
  55242. return distance;
  55243. }
  55244. };
  55245. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55246. var tm = BABYLON.Tmp.Matrix[0];
  55247. mesh.getWorldMatrix().invertToRef(tm);
  55248. if (this._tmpRay) {
  55249. Ray.TransformToRef(this, tm, this._tmpRay);
  55250. }
  55251. else {
  55252. this._tmpRay = Ray.Transform(this, tm);
  55253. }
  55254. return mesh.intersects(this._tmpRay, fastCheck);
  55255. };
  55256. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55257. if (results) {
  55258. results.length = 0;
  55259. }
  55260. else {
  55261. results = [];
  55262. }
  55263. for (var i = 0; i < meshes.length; i++) {
  55264. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55265. if (pickInfo.hit) {
  55266. results.push(pickInfo);
  55267. }
  55268. }
  55269. results.sort(this._comparePickingInfo);
  55270. return results;
  55271. };
  55272. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55273. if (pickingInfoA.distance < pickingInfoB.distance) {
  55274. return -1;
  55275. }
  55276. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55277. return 1;
  55278. }
  55279. else {
  55280. return 0;
  55281. }
  55282. };
  55283. /**
  55284. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55285. * @param sega the first point of the segment to test the intersection against
  55286. * @param segb the second point of the segment to test the intersection against
  55287. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55288. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55289. */
  55290. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55291. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55292. var u = segb.subtract(sega);
  55293. var v = rsegb.subtract(this.origin);
  55294. var w = sega.subtract(this.origin);
  55295. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55296. var b = BABYLON.Vector3.Dot(u, v);
  55297. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55298. var d = BABYLON.Vector3.Dot(u, w);
  55299. var e = BABYLON.Vector3.Dot(v, w);
  55300. var D = a * c - b * b; // always >= 0
  55301. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55302. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55303. // compute the line parameters of the two closest points
  55304. if (D < Ray.smallnum) { // the lines are almost parallel
  55305. sN = 0.0; // force using point P0 on segment S1
  55306. sD = 1.0; // to prevent possible division by 0.0 later
  55307. tN = e;
  55308. tD = c;
  55309. }
  55310. else { // get the closest points on the infinite lines
  55311. sN = (b * e - c * d);
  55312. tN = (a * e - b * d);
  55313. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55314. sN = 0.0;
  55315. tN = e;
  55316. tD = c;
  55317. }
  55318. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55319. sN = sD;
  55320. tN = e + b;
  55321. tD = c;
  55322. }
  55323. }
  55324. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55325. tN = 0.0;
  55326. // recompute sc for this edge
  55327. if (-d < 0.0) {
  55328. sN = 0.0;
  55329. }
  55330. else if (-d > a)
  55331. sN = sD;
  55332. else {
  55333. sN = -d;
  55334. sD = a;
  55335. }
  55336. }
  55337. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55338. tN = tD;
  55339. // recompute sc for this edge
  55340. if ((-d + b) < 0.0) {
  55341. sN = 0;
  55342. }
  55343. else if ((-d + b) > a) {
  55344. sN = sD;
  55345. }
  55346. else {
  55347. sN = (-d + b);
  55348. sD = a;
  55349. }
  55350. }
  55351. // finally do the division to get sc and tc
  55352. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55353. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55354. // get the difference of the two closest points
  55355. var qtc = v.multiplyByFloats(tc, tc, tc);
  55356. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55357. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55358. if (isIntersected) {
  55359. return qtc.length();
  55360. }
  55361. return -1;
  55362. };
  55363. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55364. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55365. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55366. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55367. this.direction.normalize();
  55368. return this;
  55369. };
  55370. // Statics
  55371. Ray.Zero = function () {
  55372. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55373. };
  55374. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55375. var result = Ray.Zero();
  55376. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55377. };
  55378. /**
  55379. * 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
  55380. * transformed to the given world matrix.
  55381. * @param origin The origin point
  55382. * @param end The end point
  55383. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55384. */
  55385. Ray.CreateNewFromTo = function (origin, end, world) {
  55386. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55387. var direction = end.subtract(origin);
  55388. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55389. direction.normalize();
  55390. return Ray.Transform(new Ray(origin, direction, length), world);
  55391. };
  55392. Ray.Transform = function (ray, matrix) {
  55393. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55394. Ray.TransformToRef(ray, matrix, result);
  55395. return result;
  55396. };
  55397. Ray.TransformToRef = function (ray, matrix, result) {
  55398. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55399. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55400. result.length = ray.length;
  55401. var dir = result.direction;
  55402. var len = dir.length();
  55403. if (!(len === 0 || len === 1)) {
  55404. var num = 1.0 / len;
  55405. dir.x *= num;
  55406. dir.y *= num;
  55407. dir.z *= num;
  55408. result.length *= len;
  55409. }
  55410. };
  55411. Ray.smallnum = 0.00000001;
  55412. Ray.rayl = 10e8;
  55413. return Ray;
  55414. }());
  55415. BABYLON.Ray = Ray;
  55416. })(BABYLON || (BABYLON = {}));
  55417. //# sourceMappingURL=babylon.ray.js.map
  55418. var BABYLON;
  55419. (function (BABYLON) {
  55420. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55421. if (boxMin.x > sphereCenter.x + sphereRadius)
  55422. return false;
  55423. if (sphereCenter.x - sphereRadius > boxMax.x)
  55424. return false;
  55425. if (boxMin.y > sphereCenter.y + sphereRadius)
  55426. return false;
  55427. if (sphereCenter.y - sphereRadius > boxMax.y)
  55428. return false;
  55429. if (boxMin.z > sphereCenter.z + sphereRadius)
  55430. return false;
  55431. if (sphereCenter.z - sphereRadius > boxMax.z)
  55432. return false;
  55433. return true;
  55434. };
  55435. var getLowestRoot = (function () {
  55436. var result = { root: 0, found: false };
  55437. return function (a, b, c, maxR) {
  55438. result.root = 0;
  55439. result.found = false;
  55440. var determinant = b * b - 4.0 * a * c;
  55441. if (determinant < 0)
  55442. return result;
  55443. var sqrtD = Math.sqrt(determinant);
  55444. var r1 = (-b - sqrtD) / (2.0 * a);
  55445. var r2 = (-b + sqrtD) / (2.0 * a);
  55446. if (r1 > r2) {
  55447. var temp = r2;
  55448. r2 = r1;
  55449. r1 = temp;
  55450. }
  55451. if (r1 > 0 && r1 < maxR) {
  55452. result.root = r1;
  55453. result.found = true;
  55454. return result;
  55455. }
  55456. if (r2 > 0 && r2 < maxR) {
  55457. result.root = r2;
  55458. result.found = true;
  55459. return result;
  55460. }
  55461. return result;
  55462. };
  55463. })();
  55464. var Collider = /** @class */ (function () {
  55465. function Collider() {
  55466. this._collisionPoint = BABYLON.Vector3.Zero();
  55467. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55468. this._tempVector = BABYLON.Vector3.Zero();
  55469. this._tempVector2 = BABYLON.Vector3.Zero();
  55470. this._tempVector3 = BABYLON.Vector3.Zero();
  55471. this._tempVector4 = BABYLON.Vector3.Zero();
  55472. this._edge = BABYLON.Vector3.Zero();
  55473. this._baseToVertex = BABYLON.Vector3.Zero();
  55474. this._destinationPoint = BABYLON.Vector3.Zero();
  55475. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55476. this._displacementVector = BABYLON.Vector3.Zero();
  55477. this._radius = BABYLON.Vector3.One();
  55478. this._retry = 0;
  55479. this._basePointWorld = BABYLON.Vector3.Zero();
  55480. this._velocityWorld = BABYLON.Vector3.Zero();
  55481. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55482. this._collisionMask = -1;
  55483. }
  55484. Object.defineProperty(Collider.prototype, "collisionMask", {
  55485. get: function () {
  55486. return this._collisionMask;
  55487. },
  55488. set: function (mask) {
  55489. this._collisionMask = !isNaN(mask) ? mask : -1;
  55490. },
  55491. enumerable: true,
  55492. configurable: true
  55493. });
  55494. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55495. /**
  55496. * Gets the plane normal used to compute the sliding response (in local space)
  55497. */
  55498. get: function () {
  55499. return this._slidePlaneNormal;
  55500. },
  55501. enumerable: true,
  55502. configurable: true
  55503. });
  55504. // Methods
  55505. Collider.prototype._initialize = function (source, dir, e) {
  55506. this._velocity = dir;
  55507. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55508. this._basePoint = source;
  55509. source.multiplyToRef(this._radius, this._basePointWorld);
  55510. dir.multiplyToRef(this._radius, this._velocityWorld);
  55511. this._velocityWorldLength = this._velocityWorld.length();
  55512. this._epsilon = e;
  55513. this.collisionFound = false;
  55514. };
  55515. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55516. pa.subtractToRef(point, this._tempVector);
  55517. pb.subtractToRef(point, this._tempVector2);
  55518. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55519. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55520. if (d < 0)
  55521. return false;
  55522. pc.subtractToRef(point, this._tempVector3);
  55523. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55524. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55525. if (d < 0)
  55526. return false;
  55527. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55528. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55529. return d >= 0;
  55530. };
  55531. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55532. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55533. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55534. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55535. return false;
  55536. }
  55537. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55538. return false;
  55539. return true;
  55540. };
  55541. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55542. var t0;
  55543. var embeddedInPlane = false;
  55544. //defensive programming, actually not needed.
  55545. if (!trianglePlaneArray) {
  55546. trianglePlaneArray = [];
  55547. }
  55548. if (!trianglePlaneArray[faceIndex]) {
  55549. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55550. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55551. }
  55552. var trianglePlane = trianglePlaneArray[faceIndex];
  55553. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55554. return;
  55555. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55556. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55557. if (normalDotVelocity == 0) {
  55558. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55559. return;
  55560. embeddedInPlane = true;
  55561. t0 = 0;
  55562. }
  55563. else {
  55564. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55565. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55566. if (t0 > t1) {
  55567. var temp = t1;
  55568. t1 = t0;
  55569. t0 = temp;
  55570. }
  55571. if (t0 > 1.0 || t1 < 0.0)
  55572. return;
  55573. if (t0 < 0)
  55574. t0 = 0;
  55575. if (t0 > 1.0)
  55576. t0 = 1.0;
  55577. }
  55578. this._collisionPoint.copyFromFloats(0, 0, 0);
  55579. var found = false;
  55580. var t = 1.0;
  55581. if (!embeddedInPlane) {
  55582. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55583. this._velocity.scaleToRef(t0, this._tempVector);
  55584. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55585. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55586. found = true;
  55587. t = t0;
  55588. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55589. }
  55590. }
  55591. if (!found) {
  55592. var velocitySquaredLength = this._velocity.lengthSquared();
  55593. var a = velocitySquaredLength;
  55594. this._basePoint.subtractToRef(p1, this._tempVector);
  55595. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55596. var c = this._tempVector.lengthSquared() - 1.0;
  55597. var lowestRoot = getLowestRoot(a, b, c, t);
  55598. if (lowestRoot.found) {
  55599. t = lowestRoot.root;
  55600. found = true;
  55601. this._collisionPoint.copyFrom(p1);
  55602. }
  55603. this._basePoint.subtractToRef(p2, this._tempVector);
  55604. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55605. c = this._tempVector.lengthSquared() - 1.0;
  55606. lowestRoot = getLowestRoot(a, b, c, t);
  55607. if (lowestRoot.found) {
  55608. t = lowestRoot.root;
  55609. found = true;
  55610. this._collisionPoint.copyFrom(p2);
  55611. }
  55612. this._basePoint.subtractToRef(p3, this._tempVector);
  55613. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55614. c = this._tempVector.lengthSquared() - 1.0;
  55615. lowestRoot = getLowestRoot(a, b, c, t);
  55616. if (lowestRoot.found) {
  55617. t = lowestRoot.root;
  55618. found = true;
  55619. this._collisionPoint.copyFrom(p3);
  55620. }
  55621. p2.subtractToRef(p1, this._edge);
  55622. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55623. var edgeSquaredLength = this._edge.lengthSquared();
  55624. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55625. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55626. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55627. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55628. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55629. lowestRoot = getLowestRoot(a, b, c, t);
  55630. if (lowestRoot.found) {
  55631. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55632. if (f >= 0.0 && f <= 1.0) {
  55633. t = lowestRoot.root;
  55634. found = true;
  55635. this._edge.scaleInPlace(f);
  55636. p1.addToRef(this._edge, this._collisionPoint);
  55637. }
  55638. }
  55639. p3.subtractToRef(p2, this._edge);
  55640. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55641. edgeSquaredLength = this._edge.lengthSquared();
  55642. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55643. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55644. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55645. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55646. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55647. lowestRoot = getLowestRoot(a, b, c, t);
  55648. if (lowestRoot.found) {
  55649. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55650. if (f >= 0.0 && f <= 1.0) {
  55651. t = lowestRoot.root;
  55652. found = true;
  55653. this._edge.scaleInPlace(f);
  55654. p2.addToRef(this._edge, this._collisionPoint);
  55655. }
  55656. }
  55657. p1.subtractToRef(p3, this._edge);
  55658. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55659. edgeSquaredLength = this._edge.lengthSquared();
  55660. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55661. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55662. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55663. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55664. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55665. lowestRoot = getLowestRoot(a, b, c, t);
  55666. if (lowestRoot.found) {
  55667. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55668. if (f >= 0.0 && f <= 1.0) {
  55669. t = lowestRoot.root;
  55670. found = true;
  55671. this._edge.scaleInPlace(f);
  55672. p3.addToRef(this._edge, this._collisionPoint);
  55673. }
  55674. }
  55675. }
  55676. if (found) {
  55677. var distToCollision = t * this._velocity.length();
  55678. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55679. if (!this.intersectionPoint) {
  55680. this.intersectionPoint = this._collisionPoint.clone();
  55681. }
  55682. else {
  55683. this.intersectionPoint.copyFrom(this._collisionPoint);
  55684. }
  55685. this._nearestDistance = distToCollision;
  55686. this.collisionFound = true;
  55687. }
  55688. }
  55689. };
  55690. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55691. for (var i = indexStart; i < indexEnd; i += 3) {
  55692. var p1 = pts[indices[i] - decal];
  55693. var p2 = pts[indices[i + 1] - decal];
  55694. var p3 = pts[indices[i + 2] - decal];
  55695. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55696. }
  55697. };
  55698. Collider.prototype._getResponse = function (pos, vel) {
  55699. pos.addToRef(vel, this._destinationPoint);
  55700. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55701. this._basePoint.addToRef(vel, pos);
  55702. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55703. this._slidePlaneNormal.normalize();
  55704. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55705. pos.addInPlace(this._displacementVector);
  55706. this.intersectionPoint.addInPlace(this._displacementVector);
  55707. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55708. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55709. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55710. };
  55711. return Collider;
  55712. }());
  55713. BABYLON.Collider = Collider;
  55714. })(BABYLON || (BABYLON = {}));
  55715. //# sourceMappingURL=babylon.collider.js.map
  55716. var BABYLON;
  55717. (function (BABYLON) {
  55718. //WebWorker code will be inserted to this variable.
  55719. BABYLON.CollisionWorker = "";
  55720. /** Defines supported task for worker process */
  55721. var WorkerTaskType;
  55722. (function (WorkerTaskType) {
  55723. /** Initialization */
  55724. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55725. /** Update of geometry */
  55726. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55727. /** Evaluate collision */
  55728. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55729. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55730. /** Defines kind of replies returned by worker */
  55731. var WorkerReplyType;
  55732. (function (WorkerReplyType) {
  55733. /** Success */
  55734. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55735. /** Unkown error */
  55736. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55737. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55738. var CollisionCoordinatorWorker = /** @class */ (function () {
  55739. function CollisionCoordinatorWorker() {
  55740. var _this = this;
  55741. this._scaledPosition = BABYLON.Vector3.Zero();
  55742. this._scaledVelocity = BABYLON.Vector3.Zero();
  55743. this.onMeshUpdated = function (transformNode) {
  55744. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55745. };
  55746. this.onGeometryUpdated = function (geometry) {
  55747. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55748. };
  55749. this._afterRender = function () {
  55750. if (!_this._init)
  55751. return;
  55752. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55753. return;
  55754. }
  55755. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55756. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55757. if (_this._runningUpdated > 4) {
  55758. return;
  55759. }
  55760. ++_this._runningUpdated;
  55761. var payload = {
  55762. updatedMeshes: _this._addUpdateMeshesList,
  55763. updatedGeometries: _this._addUpdateGeometriesList,
  55764. removedGeometries: _this._toRemoveGeometryArray,
  55765. removedMeshes: _this._toRemoveMeshesArray
  55766. };
  55767. var message = {
  55768. payload: payload,
  55769. taskType: WorkerTaskType.UPDATE
  55770. };
  55771. var serializable = [];
  55772. for (var id in payload.updatedGeometries) {
  55773. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55774. //prepare transferables
  55775. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55776. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55777. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55778. }
  55779. }
  55780. _this._worker.postMessage(message, serializable);
  55781. _this._addUpdateMeshesList = {};
  55782. _this._addUpdateGeometriesList = {};
  55783. _this._toRemoveGeometryArray = [];
  55784. _this._toRemoveMeshesArray = [];
  55785. };
  55786. this._onMessageFromWorker = function (e) {
  55787. var returnData = e.data;
  55788. if (returnData.error != WorkerReplyType.SUCCESS) {
  55789. //TODO what errors can be returned from the worker?
  55790. BABYLON.Tools.Warn("error returned from worker!");
  55791. return;
  55792. }
  55793. switch (returnData.taskType) {
  55794. case WorkerTaskType.INIT:
  55795. _this._init = true;
  55796. //Update the worked with ALL of the scene's current state
  55797. _this._scene.meshes.forEach(function (mesh) {
  55798. _this.onMeshAdded(mesh);
  55799. });
  55800. _this._scene.getGeometries().forEach(function (geometry) {
  55801. _this.onGeometryAdded(geometry);
  55802. });
  55803. break;
  55804. case WorkerTaskType.UPDATE:
  55805. _this._runningUpdated--;
  55806. break;
  55807. case WorkerTaskType.COLLIDE:
  55808. var returnPayload = returnData.payload;
  55809. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55810. return;
  55811. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55812. if (callback) {
  55813. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55814. if (mesh) {
  55815. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55816. }
  55817. }
  55818. //cleanup
  55819. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55820. break;
  55821. }
  55822. };
  55823. this._collisionsCallbackArray = [];
  55824. this._init = false;
  55825. this._runningUpdated = 0;
  55826. this._addUpdateMeshesList = {};
  55827. this._addUpdateGeometriesList = {};
  55828. this._toRemoveGeometryArray = [];
  55829. this._toRemoveMeshesArray = [];
  55830. }
  55831. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55832. if (!this._init)
  55833. return;
  55834. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55835. return;
  55836. position.divideToRef(collider._radius, this._scaledPosition);
  55837. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55838. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55839. var payload = {
  55840. collider: {
  55841. position: this._scaledPosition.asArray(),
  55842. velocity: this._scaledVelocity.asArray(),
  55843. radius: collider._radius.asArray()
  55844. },
  55845. collisionId: collisionIndex,
  55846. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55847. maximumRetry: maximumRetry
  55848. };
  55849. var message = {
  55850. payload: payload,
  55851. taskType: WorkerTaskType.COLLIDE
  55852. };
  55853. this._worker.postMessage(message);
  55854. };
  55855. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55856. this._scene = scene;
  55857. this._scene.registerAfterRender(this._afterRender);
  55858. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55859. this._worker = new Worker(workerUrl);
  55860. this._worker.onmessage = this._onMessageFromWorker;
  55861. var message = {
  55862. payload: {},
  55863. taskType: WorkerTaskType.INIT
  55864. };
  55865. this._worker.postMessage(message);
  55866. };
  55867. CollisionCoordinatorWorker.prototype.destroy = function () {
  55868. this._scene.unregisterAfterRender(this._afterRender);
  55869. this._worker.terminate();
  55870. };
  55871. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55872. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55873. this.onMeshUpdated(mesh);
  55874. };
  55875. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55876. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55877. };
  55878. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55879. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55880. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55881. this.onGeometryUpdated(geometry);
  55882. };
  55883. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55884. this._toRemoveGeometryArray.push(geometry.id);
  55885. };
  55886. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55887. var submeshes = [];
  55888. if (mesh.subMeshes) {
  55889. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55890. var boundingInfo = sm.getBoundingInfo();
  55891. return {
  55892. position: idx,
  55893. verticesStart: sm.verticesStart,
  55894. verticesCount: sm.verticesCount,
  55895. indexStart: sm.indexStart,
  55896. indexCount: sm.indexCount,
  55897. hasMaterial: !!sm.getMaterial(),
  55898. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55899. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55900. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55901. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55902. };
  55903. });
  55904. }
  55905. var geometryId = null;
  55906. if (mesh instanceof BABYLON.Mesh) {
  55907. var geometry = mesh.geometry;
  55908. geometryId = geometry ? geometry.id : null;
  55909. }
  55910. else if (mesh instanceof BABYLON.InstancedMesh) {
  55911. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55912. geometryId = geometry ? geometry.id : null;
  55913. }
  55914. var boundingInfo = mesh.getBoundingInfo();
  55915. return {
  55916. uniqueId: mesh.uniqueId,
  55917. id: mesh.id,
  55918. name: mesh.name,
  55919. geometryId: geometryId,
  55920. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55921. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55922. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55923. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55924. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55925. subMeshes: submeshes,
  55926. checkCollisions: mesh.checkCollisions
  55927. };
  55928. };
  55929. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55930. return {
  55931. id: geometry.id,
  55932. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55933. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55934. indices: new Uint32Array(geometry.getIndices() || []),
  55935. };
  55936. };
  55937. return CollisionCoordinatorWorker;
  55938. }());
  55939. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55940. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55941. function CollisionCoordinatorLegacy() {
  55942. this._scaledPosition = BABYLON.Vector3.Zero();
  55943. this._scaledVelocity = BABYLON.Vector3.Zero();
  55944. this._finalPosition = BABYLON.Vector3.Zero();
  55945. }
  55946. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55947. position.divideToRef(collider._radius, this._scaledPosition);
  55948. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55949. collider.collidedMesh = null;
  55950. collider._retry = 0;
  55951. collider._initialVelocity = this._scaledVelocity;
  55952. collider._initialPosition = this._scaledPosition;
  55953. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55954. this._finalPosition.multiplyInPlace(collider._radius);
  55955. //run the callback
  55956. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55957. };
  55958. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55959. this._scene = scene;
  55960. };
  55961. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55962. //Legacy need no destruction method.
  55963. };
  55964. //No update in legacy mode
  55965. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55966. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55967. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55968. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55969. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55970. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55971. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55972. if (excludedMesh === void 0) { excludedMesh = null; }
  55973. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55974. if (collider._retry >= maximumRetry) {
  55975. finalPosition.copyFrom(position);
  55976. return;
  55977. }
  55978. // Check if this is a mesh else camera or -1
  55979. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55980. collider._initialize(position, velocity, closeDistance);
  55981. // Check all meshes
  55982. for (var index = 0; index < this._scene.meshes.length; index++) {
  55983. var mesh = this._scene.meshes[index];
  55984. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55985. mesh._checkCollision(collider);
  55986. }
  55987. }
  55988. if (!collider.collisionFound) {
  55989. position.addToRef(velocity, finalPosition);
  55990. return;
  55991. }
  55992. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55993. collider._getResponse(position, velocity);
  55994. }
  55995. if (velocity.length() <= closeDistance) {
  55996. finalPosition.copyFrom(position);
  55997. return;
  55998. }
  55999. collider._retry++;
  56000. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56001. };
  56002. return CollisionCoordinatorLegacy;
  56003. }());
  56004. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56005. })(BABYLON || (BABYLON = {}));
  56006. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56007. var BABYLON;
  56008. (function (BABYLON) {
  56009. /**
  56010. * A particle represents one of the element emitted by a particle system.
  56011. * This is mainly define by its coordinates, direction, velocity and age.
  56012. */
  56013. var Particle = /** @class */ (function () {
  56014. /**
  56015. * Creates a new instance Particle
  56016. * @param particleSystem the particle system the particle belongs to
  56017. */
  56018. function Particle(
  56019. /**
  56020. * particleSystem the particle system the particle belongs to.
  56021. */
  56022. particleSystem) {
  56023. this.particleSystem = particleSystem;
  56024. /**
  56025. * The world position of the particle in the scene.
  56026. */
  56027. this.position = BABYLON.Vector3.Zero();
  56028. /**
  56029. * The world direction of the particle in the scene.
  56030. */
  56031. this.direction = BABYLON.Vector3.Zero();
  56032. /**
  56033. * The color of the particle.
  56034. */
  56035. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56036. /**
  56037. * The color change of the particle per step.
  56038. */
  56039. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56040. /**
  56041. * Defines how long will the life of the particle be.
  56042. */
  56043. this.lifeTime = 1.0;
  56044. /**
  56045. * The current age of the particle.
  56046. */
  56047. this.age = 0;
  56048. /**
  56049. * The current size of the particle.
  56050. */
  56051. this.size = 0;
  56052. /**
  56053. * The current angle of the particle.
  56054. */
  56055. this.angle = 0;
  56056. /**
  56057. * Defines how fast is the angle changing.
  56058. */
  56059. this.angularSpeed = 0;
  56060. /**
  56061. * Defines the cell index used by the particle to be rendered from a sprite.
  56062. */
  56063. this.cellIndex = 0;
  56064. this._currentFrameCounter = 0;
  56065. if (!this.particleSystem.isAnimationSheetEnabled) {
  56066. return;
  56067. }
  56068. this.updateCellInfoFromSystem();
  56069. }
  56070. Particle.prototype.updateCellInfoFromSystem = function () {
  56071. this.cellIndex = this.particleSystem.startSpriteCellID;
  56072. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56073. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56074. }
  56075. else {
  56076. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56077. }
  56078. };
  56079. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56080. // (ageOffset / scaledUpdateSpeed) / available cells
  56081. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56082. this._currentFrameCounter += scaledUpdateSpeed;
  56083. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56084. this._currentFrameCounter = 0;
  56085. this.cellIndex++;
  56086. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56087. this.cellIndex = this.particleSystem.endSpriteCellID;
  56088. }
  56089. }
  56090. };
  56091. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56092. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56093. this.cellIndex++;
  56094. this._currentFrameCounter = 0;
  56095. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56096. if (this.particleSystem.spriteCellLoop) {
  56097. this.cellIndex = this.particleSystem.startSpriteCellID;
  56098. }
  56099. else {
  56100. this.cellIndex = this.particleSystem.endSpriteCellID;
  56101. }
  56102. }
  56103. }
  56104. else {
  56105. this._currentFrameCounter++;
  56106. }
  56107. };
  56108. /**
  56109. * Copy the properties of particle to another one.
  56110. * @param other the particle to copy the information to.
  56111. */
  56112. Particle.prototype.copyTo = function (other) {
  56113. other.position.copyFrom(this.position);
  56114. other.direction.copyFrom(this.direction);
  56115. other.color.copyFrom(this.color);
  56116. other.colorStep.copyFrom(this.colorStep);
  56117. other.lifeTime = this.lifeTime;
  56118. other.age = this.age;
  56119. other.size = this.size;
  56120. other.angle = this.angle;
  56121. other.angularSpeed = this.angularSpeed;
  56122. other.particleSystem = this.particleSystem;
  56123. other.cellIndex = this.cellIndex;
  56124. };
  56125. return Particle;
  56126. }());
  56127. BABYLON.Particle = Particle;
  56128. })(BABYLON || (BABYLON = {}));
  56129. //# sourceMappingURL=babylon.particle.js.map
  56130. var BABYLON;
  56131. (function (BABYLON) {
  56132. /**
  56133. * This represents a particle system in Babylon.
  56134. * 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.
  56135. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56136. * @example https://doc.babylonjs.com/babylon101/particles
  56137. */
  56138. var ParticleSystem = /** @class */ (function () {
  56139. /**
  56140. * Instantiates a particle system.
  56141. * 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.
  56142. * @param name The name of the particle system
  56143. * @param capacity The max number of particles alive at the same time
  56144. * @param scene The scene the particle system belongs to
  56145. * @param customEffect a custom effect used to change the way particles are rendered by default
  56146. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56147. * @param epsilon Offset used to render the particles
  56148. */
  56149. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56150. if (customEffect === void 0) { customEffect = null; }
  56151. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56152. if (epsilon === void 0) { epsilon = 0.01; }
  56153. var _this = this;
  56154. /**
  56155. * List of animations used by the particle system.
  56156. */
  56157. this.animations = [];
  56158. /**
  56159. * The rendering group used by the Particle system to chose when to render.
  56160. */
  56161. this.renderingGroupId = 0;
  56162. /**
  56163. * The emitter represents the Mesh or position we are attaching the particle system to.
  56164. */
  56165. this.emitter = null;
  56166. /**
  56167. * The maximum number of particles to emit per frame
  56168. */
  56169. this.emitRate = 10;
  56170. /**
  56171. * If you want to launch only a few particles at once, that can be done, as well.
  56172. */
  56173. this.manualEmitCount = -1;
  56174. /**
  56175. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56176. */
  56177. this.updateSpeed = 0.01;
  56178. /**
  56179. * The amount of time the particle system is running (depends of the overall update speed).
  56180. */
  56181. this.targetStopDuration = 0;
  56182. /**
  56183. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56184. */
  56185. this.disposeOnStop = false;
  56186. /**
  56187. * Minimum power of emitting particles.
  56188. */
  56189. this.minEmitPower = 1;
  56190. /**
  56191. * Maximum power of emitting particles.
  56192. */
  56193. this.maxEmitPower = 1;
  56194. /**
  56195. * Minimum life time of emitting particles.
  56196. */
  56197. this.minLifeTime = 1;
  56198. /**
  56199. * Maximum life time of emitting particles.
  56200. */
  56201. this.maxLifeTime = 1;
  56202. /**
  56203. * Minimum Size of emitting particles.
  56204. */
  56205. this.minSize = 1;
  56206. /**
  56207. * Maximum Size of emitting particles.
  56208. */
  56209. this.maxSize = 1;
  56210. /**
  56211. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56212. */
  56213. this.minAngularSpeed = 0;
  56214. /**
  56215. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56216. */
  56217. this.maxAngularSpeed = 0;
  56218. /**
  56219. * The layer mask we are rendering the particles through.
  56220. */
  56221. this.layerMask = 0x0FFFFFFF;
  56222. /**
  56223. * This can help using your own shader to render the particle system.
  56224. * The according effect will be created
  56225. */
  56226. this.customShader = null;
  56227. /**
  56228. * By default particle system starts as soon as they are created. This prevents the
  56229. * automatic start to happen and let you decide when to start emitting particles.
  56230. */
  56231. this.preventAutoStart = false;
  56232. /**
  56233. * Callback triggered when the particle animation is ending.
  56234. */
  56235. this.onAnimationEnd = null;
  56236. /**
  56237. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56238. */
  56239. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56240. /**
  56241. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56242. * to override the particles.
  56243. */
  56244. this.forceDepthWrite = false;
  56245. /**
  56246. * You can use gravity if you want to give an orientation to your particles.
  56247. */
  56248. this.gravity = BABYLON.Vector3.Zero();
  56249. /**
  56250. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56251. */
  56252. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56253. /**
  56254. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56255. */
  56256. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56257. /**
  56258. * Color the particle will have at the end of its lifetime.
  56259. */
  56260. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56261. /**
  56262. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56263. */
  56264. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56265. /**
  56266. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56267. */
  56268. this.spriteCellLoop = true;
  56269. /**
  56270. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56271. */
  56272. this.spriteCellChangeSpeed = 0;
  56273. /**
  56274. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56275. */
  56276. this.startSpriteCellID = 0;
  56277. /**
  56278. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56279. */
  56280. this.endSpriteCellID = 0;
  56281. /**
  56282. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56283. */
  56284. this.spriteCellWidth = 0;
  56285. /**
  56286. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56287. */
  56288. this.spriteCellHeight = 0;
  56289. /**
  56290. * An event triggered when the system is disposed.
  56291. */
  56292. this.onDisposeObservable = new BABYLON.Observable();
  56293. this._particles = new Array();
  56294. this._stockParticles = new Array();
  56295. this._newPartsExcess = 0;
  56296. this._vertexBuffers = {};
  56297. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56298. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56299. this._scaledDirection = BABYLON.Vector3.Zero();
  56300. this._scaledGravity = BABYLON.Vector3.Zero();
  56301. this._currentRenderId = -1;
  56302. this._started = false;
  56303. this._stopped = false;
  56304. this._actualFrame = 0;
  56305. this._vertexBufferSize = 11;
  56306. // start of sub system methods
  56307. /**
  56308. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56309. * Its lifetime will start back at 0.
  56310. */
  56311. this.recycleParticle = function (particle) {
  56312. var lastParticle = _this._particles.pop();
  56313. if (lastParticle !== particle) {
  56314. lastParticle.copyTo(particle);
  56315. }
  56316. _this._stockParticles.push(lastParticle);
  56317. };
  56318. this._createParticle = function () {
  56319. var particle;
  56320. if (_this._stockParticles.length !== 0) {
  56321. particle = _this._stockParticles.pop();
  56322. particle.age = 0;
  56323. particle.cellIndex = _this.startSpriteCellID;
  56324. }
  56325. else {
  56326. particle = new BABYLON.Particle(_this);
  56327. }
  56328. return particle;
  56329. };
  56330. this._emitFromParticle = function (particle) {
  56331. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56332. return;
  56333. }
  56334. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56335. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56336. subSystem._rootParticleSystem = _this;
  56337. _this.activeSubSystems.push(subSystem);
  56338. subSystem.start();
  56339. };
  56340. this._appendParticleVertexes = null;
  56341. this.id = name;
  56342. this.name = name;
  56343. this._capacity = capacity;
  56344. this._epsilon = epsilon;
  56345. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56346. if (isAnimationSheetEnabled) {
  56347. this._vertexBufferSize = 12;
  56348. }
  56349. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56350. this._customEffect = customEffect;
  56351. scene.particleSystems.push(this);
  56352. this._createIndexBuffer();
  56353. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56354. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56355. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56356. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56357. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56358. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56359. if (this._isAnimationSheetEnabled) {
  56360. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56361. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56362. }
  56363. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56364. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56365. this._vertexBuffers["options"] = options;
  56366. // Default emitter type
  56367. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56368. this.updateFunction = function (particles) {
  56369. for (var index = 0; index < particles.length; index++) {
  56370. var particle = particles[index];
  56371. particle.age += _this._scaledUpdateSpeed;
  56372. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56373. _this._emitFromParticle(particle);
  56374. _this.recycleParticle(particle);
  56375. index--;
  56376. continue;
  56377. }
  56378. else {
  56379. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56380. particle.color.addInPlace(_this._scaledColorStep);
  56381. if (particle.color.a < 0)
  56382. particle.color.a = 0;
  56383. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56384. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56385. particle.position.addInPlace(_this._scaledDirection);
  56386. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56387. particle.direction.addInPlace(_this._scaledGravity);
  56388. if (_this._isAnimationSheetEnabled) {
  56389. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56390. }
  56391. }
  56392. }
  56393. };
  56394. }
  56395. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56396. /**
  56397. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56398. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56399. */
  56400. get: function () {
  56401. if (this.particleEmitterType.direction1) {
  56402. return this.particleEmitterType.direction1;
  56403. }
  56404. return BABYLON.Vector3.Zero();
  56405. },
  56406. set: function (value) {
  56407. if (this.particleEmitterType.direction1) {
  56408. this.particleEmitterType.direction1 = value;
  56409. }
  56410. },
  56411. enumerable: true,
  56412. configurable: true
  56413. });
  56414. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56415. /**
  56416. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56417. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56418. */
  56419. get: function () {
  56420. if (this.particleEmitterType.direction2) {
  56421. return this.particleEmitterType.direction2;
  56422. }
  56423. return BABYLON.Vector3.Zero();
  56424. },
  56425. set: function (value) {
  56426. if (this.particleEmitterType.direction2) {
  56427. this.particleEmitterType.direction2 = value;
  56428. }
  56429. },
  56430. enumerable: true,
  56431. configurable: true
  56432. });
  56433. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56434. /**
  56435. * 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.
  56436. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56437. */
  56438. get: function () {
  56439. if (this.particleEmitterType.minEmitBox) {
  56440. return this.particleEmitterType.minEmitBox;
  56441. }
  56442. return BABYLON.Vector3.Zero();
  56443. },
  56444. set: function (value) {
  56445. if (this.particleEmitterType.minEmitBox) {
  56446. this.particleEmitterType.minEmitBox = value;
  56447. }
  56448. },
  56449. enumerable: true,
  56450. configurable: true
  56451. });
  56452. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56453. /**
  56454. * 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.
  56455. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56456. */
  56457. get: function () {
  56458. if (this.particleEmitterType.maxEmitBox) {
  56459. return this.particleEmitterType.maxEmitBox;
  56460. }
  56461. return BABYLON.Vector3.Zero();
  56462. },
  56463. set: function (value) {
  56464. if (this.particleEmitterType.maxEmitBox) {
  56465. this.particleEmitterType.maxEmitBox = value;
  56466. }
  56467. },
  56468. enumerable: true,
  56469. configurable: true
  56470. });
  56471. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56472. /**
  56473. * Sets a callback that will be triggered when the system is disposed.
  56474. */
  56475. set: function (callback) {
  56476. if (this._onDisposeObserver) {
  56477. this.onDisposeObservable.remove(this._onDisposeObserver);
  56478. }
  56479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56480. },
  56481. enumerable: true,
  56482. configurable: true
  56483. });
  56484. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56485. /**
  56486. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56487. */
  56488. get: function () {
  56489. return this._isAnimationSheetEnabled;
  56490. },
  56491. enumerable: true,
  56492. configurable: true
  56493. });
  56494. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56495. //end of Sub-emitter
  56496. /**
  56497. * Gets the current list of active particles
  56498. */
  56499. get: function () {
  56500. return this._particles;
  56501. },
  56502. enumerable: true,
  56503. configurable: true
  56504. });
  56505. /**
  56506. * Returns the string "ParticleSystem"
  56507. * @returns a string containing the class name
  56508. */
  56509. ParticleSystem.prototype.getClassName = function () {
  56510. return "ParticleSystem";
  56511. };
  56512. ParticleSystem.prototype._createIndexBuffer = function () {
  56513. var indices = [];
  56514. var index = 0;
  56515. for (var count = 0; count < this._capacity; count++) {
  56516. indices.push(index);
  56517. indices.push(index + 1);
  56518. indices.push(index + 2);
  56519. indices.push(index);
  56520. indices.push(index + 2);
  56521. indices.push(index + 3);
  56522. index += 4;
  56523. }
  56524. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56525. };
  56526. /**
  56527. * Gets the maximum number of particles active at the same time.
  56528. * @returns The max number of active particles.
  56529. */
  56530. ParticleSystem.prototype.getCapacity = function () {
  56531. return this._capacity;
  56532. };
  56533. /**
  56534. * Gets Wether there are still active particles in the system.
  56535. * @returns True if it is alive, otherwise false.
  56536. */
  56537. ParticleSystem.prototype.isAlive = function () {
  56538. return this._alive;
  56539. };
  56540. /**
  56541. * Gets Wether the system has been started.
  56542. * @returns True if it has been started, otherwise false.
  56543. */
  56544. ParticleSystem.prototype.isStarted = function () {
  56545. return this._started;
  56546. };
  56547. /**
  56548. * Starts the particle system and begins to emit.
  56549. */
  56550. ParticleSystem.prototype.start = function () {
  56551. this._started = true;
  56552. this._stopped = false;
  56553. this._actualFrame = 0;
  56554. if (this.subEmitters && this.subEmitters.length != 0) {
  56555. this.activeSubSystems = new Array();
  56556. }
  56557. };
  56558. /**
  56559. * Stops the particle system.
  56560. * @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.
  56561. */
  56562. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56563. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56564. this._stopped = true;
  56565. if (stopSubEmitters) {
  56566. this._stopSubEmitters();
  56567. }
  56568. };
  56569. // animation sheet
  56570. /**
  56571. * Remove all active particles
  56572. */
  56573. ParticleSystem.prototype.reset = function () {
  56574. this._stockParticles = [];
  56575. this._particles = [];
  56576. };
  56577. /**
  56578. * @hidden (for internal use only)
  56579. */
  56580. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56581. var offset = index * this._vertexBufferSize;
  56582. this._vertexData[offset] = particle.position.x;
  56583. this._vertexData[offset + 1] = particle.position.y;
  56584. this._vertexData[offset + 2] = particle.position.z;
  56585. this._vertexData[offset + 3] = particle.color.r;
  56586. this._vertexData[offset + 4] = particle.color.g;
  56587. this._vertexData[offset + 5] = particle.color.b;
  56588. this._vertexData[offset + 6] = particle.color.a;
  56589. this._vertexData[offset + 7] = particle.angle;
  56590. this._vertexData[offset + 8] = particle.size;
  56591. this._vertexData[offset + 9] = offsetX;
  56592. this._vertexData[offset + 10] = offsetY;
  56593. };
  56594. /**
  56595. * @hidden (for internal use only)
  56596. */
  56597. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56598. if (offsetX === 0)
  56599. offsetX = this._epsilon;
  56600. else if (offsetX === 1)
  56601. offsetX = 1 - this._epsilon;
  56602. if (offsetY === 0)
  56603. offsetY = this._epsilon;
  56604. else if (offsetY === 1)
  56605. offsetY = 1 - this._epsilon;
  56606. var offset = index * this._vertexBufferSize;
  56607. this._vertexData[offset] = particle.position.x;
  56608. this._vertexData[offset + 1] = particle.position.y;
  56609. this._vertexData[offset + 2] = particle.position.z;
  56610. this._vertexData[offset + 3] = particle.color.r;
  56611. this._vertexData[offset + 4] = particle.color.g;
  56612. this._vertexData[offset + 5] = particle.color.b;
  56613. this._vertexData[offset + 6] = particle.color.a;
  56614. this._vertexData[offset + 7] = particle.angle;
  56615. this._vertexData[offset + 8] = particle.size;
  56616. this._vertexData[offset + 9] = offsetX;
  56617. this._vertexData[offset + 10] = offsetY;
  56618. this._vertexData[offset + 11] = particle.cellIndex;
  56619. };
  56620. ParticleSystem.prototype._stopSubEmitters = function () {
  56621. if (!this.activeSubSystems) {
  56622. return;
  56623. }
  56624. this.activeSubSystems.forEach(function (subSystem) {
  56625. subSystem.stop(true);
  56626. });
  56627. this.activeSubSystems = new Array();
  56628. };
  56629. ParticleSystem.prototype._removeFromRoot = function () {
  56630. if (!this._rootParticleSystem) {
  56631. return;
  56632. }
  56633. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56634. if (index !== -1) {
  56635. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56636. }
  56637. };
  56638. // end of sub system methods
  56639. ParticleSystem.prototype._update = function (newParticles) {
  56640. // Update current
  56641. this._alive = this._particles.length > 0;
  56642. this.updateFunction(this._particles);
  56643. // Add new ones
  56644. var worldMatrix;
  56645. if (this.emitter.position) {
  56646. var emitterMesh = this.emitter;
  56647. worldMatrix = emitterMesh.getWorldMatrix();
  56648. }
  56649. else {
  56650. var emitterPosition = this.emitter;
  56651. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56652. }
  56653. var particle;
  56654. for (var index = 0; index < newParticles; index++) {
  56655. if (this._particles.length === this._capacity) {
  56656. break;
  56657. }
  56658. particle = this._createParticle();
  56659. this._particles.push(particle);
  56660. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56661. if (this.startPositionFunction) {
  56662. this.startPositionFunction(worldMatrix, particle.position, particle);
  56663. }
  56664. else {
  56665. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56666. }
  56667. if (this.startDirectionFunction) {
  56668. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56669. }
  56670. else {
  56671. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56672. }
  56673. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56674. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56675. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56676. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56677. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56678. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56679. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56680. }
  56681. };
  56682. ParticleSystem.prototype._getEffect = function () {
  56683. if (this._customEffect) {
  56684. return this._customEffect;
  56685. }
  56686. ;
  56687. var defines = [];
  56688. if (this._scene.clipPlane) {
  56689. defines.push("#define CLIPPLANE");
  56690. }
  56691. if (this._isAnimationSheetEnabled) {
  56692. defines.push("#define ANIMATESHEET");
  56693. }
  56694. // Effect
  56695. var join = defines.join("\n");
  56696. if (this._cachedDefines !== join) {
  56697. this._cachedDefines = join;
  56698. var attributesNamesOrOptions;
  56699. var effectCreationOption;
  56700. if (this._isAnimationSheetEnabled) {
  56701. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56702. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56703. }
  56704. else {
  56705. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56706. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56707. }
  56708. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56709. }
  56710. return this._effect;
  56711. };
  56712. /**
  56713. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56714. */
  56715. ParticleSystem.prototype.animate = function () {
  56716. if (!this._started)
  56717. return;
  56718. var effect = this._getEffect();
  56719. // Check
  56720. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56721. return;
  56722. if (this._currentRenderId === this._scene.getRenderId()) {
  56723. return;
  56724. }
  56725. this._currentRenderId = this._scene.getRenderId();
  56726. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56727. // determine the number of particles we need to create
  56728. var newParticles;
  56729. if (this.manualEmitCount > -1) {
  56730. newParticles = this.manualEmitCount;
  56731. this._newPartsExcess = 0;
  56732. this.manualEmitCount = 0;
  56733. }
  56734. else {
  56735. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56736. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56737. }
  56738. if (this._newPartsExcess > 1.0) {
  56739. newParticles += this._newPartsExcess >> 0;
  56740. this._newPartsExcess -= this._newPartsExcess >> 0;
  56741. }
  56742. this._alive = false;
  56743. if (!this._stopped) {
  56744. this._actualFrame += this._scaledUpdateSpeed;
  56745. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56746. this.stop();
  56747. }
  56748. else {
  56749. newParticles = 0;
  56750. }
  56751. this._update(newParticles);
  56752. // Stopped?
  56753. if (this._stopped) {
  56754. if (!this._alive) {
  56755. this._started = false;
  56756. if (this.onAnimationEnd) {
  56757. this.onAnimationEnd();
  56758. }
  56759. if (this.disposeOnStop) {
  56760. this._scene._toBeDisposed.push(this);
  56761. }
  56762. }
  56763. }
  56764. // Animation sheet
  56765. if (this._isAnimationSheetEnabled) {
  56766. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56767. }
  56768. else {
  56769. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56770. }
  56771. // Update VBO
  56772. var offset = 0;
  56773. for (var index = 0; index < this._particles.length; index++) {
  56774. var particle = this._particles[index];
  56775. this._appendParticleVertexes(offset, particle);
  56776. offset += 4;
  56777. }
  56778. if (this._vertexBuffer) {
  56779. this._vertexBuffer.update(this._vertexData);
  56780. }
  56781. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56782. this.stop();
  56783. }
  56784. };
  56785. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56786. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56787. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56788. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56789. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56790. };
  56791. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56792. this._appendParticleVertex(offset++, particle, 0, 0);
  56793. this._appendParticleVertex(offset++, particle, 1, 0);
  56794. this._appendParticleVertex(offset++, particle, 1, 1);
  56795. this._appendParticleVertex(offset++, particle, 0, 1);
  56796. };
  56797. /**
  56798. * Rebuilds the particle system.
  56799. */
  56800. ParticleSystem.prototype.rebuild = function () {
  56801. this._createIndexBuffer();
  56802. if (this._vertexBuffer) {
  56803. this._vertexBuffer._rebuild();
  56804. }
  56805. };
  56806. /**
  56807. * Is this system ready to be used/rendered
  56808. * @return true if the system is ready
  56809. */
  56810. ParticleSystem.prototype.isReady = function () {
  56811. var effect = this._getEffect();
  56812. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56813. return false;
  56814. }
  56815. return true;
  56816. };
  56817. /**
  56818. * Renders the particle system in its current state.
  56819. * @returns the current number of particles
  56820. */
  56821. ParticleSystem.prototype.render = function () {
  56822. var effect = this._getEffect();
  56823. // Check
  56824. if (!this.isReady() || !this._particles.length) {
  56825. return 0;
  56826. }
  56827. var engine = this._scene.getEngine();
  56828. // Render
  56829. engine.enableEffect(effect);
  56830. engine.setState(false);
  56831. var viewMatrix = this._scene.getViewMatrix();
  56832. effect.setTexture("diffuseSampler", this.particleTexture);
  56833. effect.setMatrix("view", viewMatrix);
  56834. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56835. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56836. var baseSize = this.particleTexture.getBaseSize();
  56837. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56838. }
  56839. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56840. if (this._scene.clipPlane) {
  56841. var clipPlane = this._scene.clipPlane;
  56842. var invView = viewMatrix.clone();
  56843. invView.invert();
  56844. effect.setMatrix("invView", invView);
  56845. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56846. }
  56847. // VBOs
  56848. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56849. // Draw order
  56850. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56851. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56852. }
  56853. else {
  56854. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56855. }
  56856. if (this.forceDepthWrite) {
  56857. engine.setDepthWrite(true);
  56858. }
  56859. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56860. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56861. return this._particles.length;
  56862. };
  56863. /**
  56864. * Disposes the particle system and free the associated resources
  56865. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56866. */
  56867. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56868. if (disposeTexture === void 0) { disposeTexture = true; }
  56869. if (this._vertexBuffer) {
  56870. this._vertexBuffer.dispose();
  56871. this._vertexBuffer = null;
  56872. }
  56873. if (this._indexBuffer) {
  56874. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56875. this._indexBuffer = null;
  56876. }
  56877. if (disposeTexture && this.particleTexture) {
  56878. this.particleTexture.dispose();
  56879. this.particleTexture = null;
  56880. }
  56881. this._removeFromRoot();
  56882. // Remove from scene
  56883. var index = this._scene.particleSystems.indexOf(this);
  56884. if (index > -1) {
  56885. this._scene.particleSystems.splice(index, 1);
  56886. }
  56887. // Callback
  56888. this.onDisposeObservable.notifyObservers(this);
  56889. this.onDisposeObservable.clear();
  56890. };
  56891. /**
  56892. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56893. * @param radius The radius of the sphere to emit from
  56894. * @returns the emitter
  56895. */
  56896. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56897. if (radius === void 0) { radius = 1; }
  56898. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56899. this.particleEmitterType = particleEmitter;
  56900. return particleEmitter;
  56901. };
  56902. /**
  56903. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56904. * @param radius The radius of the sphere to emit from
  56905. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56906. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56907. * @returns the emitter
  56908. */
  56909. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56910. if (radius === void 0) { radius = 1; }
  56911. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56912. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56913. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56914. this.particleEmitterType = particleEmitter;
  56915. return particleEmitter;
  56916. };
  56917. /**
  56918. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56919. * @param radius The radius of the cone to emit from
  56920. * @param angle The base angle of the cone
  56921. * @returns the emitter
  56922. */
  56923. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56924. if (radius === void 0) { radius = 1; }
  56925. if (angle === void 0) { angle = Math.PI / 4; }
  56926. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56927. this.particleEmitterType = particleEmitter;
  56928. return particleEmitter;
  56929. };
  56930. // 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.
  56931. /**
  56932. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56933. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56934. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56935. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56936. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56937. * @returns the emitter
  56938. */
  56939. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56940. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56941. this.particleEmitterType = particleEmitter;
  56942. this.direction1 = direction1;
  56943. this.direction2 = direction2;
  56944. this.minEmitBox = minEmitBox;
  56945. this.maxEmitBox = maxEmitBox;
  56946. return particleEmitter;
  56947. };
  56948. // Clone
  56949. /**
  56950. * Clones the particle system.
  56951. * @param name The name of the cloned object
  56952. * @param newEmitter The new emitter to use
  56953. * @returns the cloned particle system
  56954. */
  56955. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56956. var custom = null;
  56957. var program = null;
  56958. if (this.customShader != null) {
  56959. program = this.customShader;
  56960. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56961. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56962. }
  56963. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56964. result.customShader = program;
  56965. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56966. if (newEmitter === undefined) {
  56967. newEmitter = this.emitter;
  56968. }
  56969. result.emitter = newEmitter;
  56970. if (this.particleTexture) {
  56971. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56972. }
  56973. if (!this.preventAutoStart) {
  56974. result.start();
  56975. }
  56976. return result;
  56977. };
  56978. /**
  56979. * Serializes the particle system to a JSON object.
  56980. * @returns the JSON object
  56981. */
  56982. ParticleSystem.prototype.serialize = function () {
  56983. var serializationObject = {};
  56984. serializationObject.name = this.name;
  56985. serializationObject.id = this.id;
  56986. // Emitter
  56987. if (this.emitter.position) {
  56988. var emitterMesh = this.emitter;
  56989. serializationObject.emitterId = emitterMesh.id;
  56990. }
  56991. else {
  56992. var emitterPosition = this.emitter;
  56993. serializationObject.emitter = emitterPosition.asArray();
  56994. }
  56995. serializationObject.capacity = this.getCapacity();
  56996. if (this.particleTexture) {
  56997. serializationObject.textureName = this.particleTexture.name;
  56998. }
  56999. // Animations
  57000. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57001. // Particle system
  57002. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57003. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57004. serializationObject.minSize = this.minSize;
  57005. serializationObject.maxSize = this.maxSize;
  57006. serializationObject.minEmitPower = this.minEmitPower;
  57007. serializationObject.maxEmitPower = this.maxEmitPower;
  57008. serializationObject.minLifeTime = this.minLifeTime;
  57009. serializationObject.maxLifeTime = this.maxLifeTime;
  57010. serializationObject.emitRate = this.emitRate;
  57011. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57012. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57013. serializationObject.gravity = this.gravity.asArray();
  57014. serializationObject.direction1 = this.direction1.asArray();
  57015. serializationObject.direction2 = this.direction2.asArray();
  57016. serializationObject.color1 = this.color1.asArray();
  57017. serializationObject.color2 = this.color2.asArray();
  57018. serializationObject.colorDead = this.colorDead.asArray();
  57019. serializationObject.updateSpeed = this.updateSpeed;
  57020. serializationObject.targetStopDuration = this.targetStopDuration;
  57021. serializationObject.textureMask = this.textureMask.asArray();
  57022. serializationObject.blendMode = this.blendMode;
  57023. serializationObject.customShader = this.customShader;
  57024. serializationObject.preventAutoStart = this.preventAutoStart;
  57025. serializationObject.startSpriteCellID = this.startSpriteCellID;
  57026. serializationObject.endSpriteCellID = this.endSpriteCellID;
  57027. serializationObject.spriteCellLoop = this.spriteCellLoop;
  57028. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  57029. serializationObject.spriteCellWidth = this.spriteCellWidth;
  57030. serializationObject.spriteCellHeight = this.spriteCellHeight;
  57031. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57032. // Emitter
  57033. if (this.particleEmitterType) {
  57034. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57035. }
  57036. return serializationObject;
  57037. };
  57038. /**
  57039. * Parses a JSON object to create a particle system.
  57040. * @param parsedParticleSystem The JSON object to parse
  57041. * @param scene The scene to create the particle system in
  57042. * @param rootUrl The root url to use to load external dependencies like texture
  57043. * @returns the Parsed particle system
  57044. */
  57045. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57046. var name = parsedParticleSystem.name;
  57047. var custom = null;
  57048. var program = null;
  57049. if (parsedParticleSystem.customShader) {
  57050. program = parsedParticleSystem.customShader;
  57051. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57052. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57053. }
  57054. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57055. particleSystem.customShader = program;
  57056. if (parsedParticleSystem.id) {
  57057. particleSystem.id = parsedParticleSystem.id;
  57058. }
  57059. // Auto start
  57060. if (parsedParticleSystem.preventAutoStart) {
  57061. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57062. }
  57063. // Texture
  57064. if (parsedParticleSystem.textureName) {
  57065. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57066. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57067. }
  57068. // Emitter
  57069. if (parsedParticleSystem.emitterId) {
  57070. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57071. }
  57072. else {
  57073. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57074. }
  57075. // Animations
  57076. if (parsedParticleSystem.animations) {
  57077. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57078. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57079. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57080. }
  57081. }
  57082. if (parsedParticleSystem.autoAnimate) {
  57083. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57084. }
  57085. // Particle system
  57086. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57087. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57088. particleSystem.minSize = parsedParticleSystem.minSize;
  57089. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57090. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57091. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57092. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57093. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57094. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57095. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57096. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57097. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57098. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57099. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57100. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57101. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57102. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57103. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57104. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57105. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57106. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57107. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57108. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57109. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57110. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57111. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57112. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57113. if (!particleSystem.preventAutoStart) {
  57114. particleSystem.start();
  57115. }
  57116. return particleSystem;
  57117. };
  57118. /**
  57119. * Source color is added to the destination color without alpha affecting the result.
  57120. */
  57121. ParticleSystem.BLENDMODE_ONEONE = 0;
  57122. /**
  57123. * Blend current color and particle color using particle’s alpha.
  57124. */
  57125. ParticleSystem.BLENDMODE_STANDARD = 1;
  57126. return ParticleSystem;
  57127. }());
  57128. BABYLON.ParticleSystem = ParticleSystem;
  57129. })(BABYLON || (BABYLON = {}));
  57130. //# sourceMappingURL=babylon.particleSystem.js.map
  57131. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57132. var BABYLON;
  57133. (function (BABYLON) {
  57134. /**
  57135. * Particle emitter emitting particles from the inside of a box.
  57136. * It emits the particles randomly between 2 given directions.
  57137. */
  57138. var BoxParticleEmitter = /** @class */ (function () {
  57139. /**
  57140. * Creates a new instance BoxParticleEmitter
  57141. */
  57142. function BoxParticleEmitter() {
  57143. /**
  57144. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57145. */
  57146. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57147. /**
  57148. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57149. */
  57150. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57151. /**
  57152. * 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.
  57153. */
  57154. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57155. /**
  57156. * 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.
  57157. */
  57158. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57159. }
  57160. /**
  57161. * Called by the particle System when the direction is computed for the created particle.
  57162. * @param emitPower is the power of the particle (speed)
  57163. * @param worldMatrix is the world matrix of the particle system
  57164. * @param directionToUpdate is the direction vector to update with the result
  57165. * @param particle is the particle we are computed the direction for
  57166. */
  57167. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57168. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57169. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57170. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57171. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57172. };
  57173. /**
  57174. * Called by the particle System when the position is computed for the created particle.
  57175. * @param worldMatrix is the world matrix of the particle system
  57176. * @param positionToUpdate is the position vector to update with the result
  57177. * @param particle is the particle we are computed the position for
  57178. */
  57179. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57180. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57181. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57182. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57183. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57184. };
  57185. /**
  57186. * Clones the current emitter and returns a copy of it
  57187. * @returns the new emitter
  57188. */
  57189. BoxParticleEmitter.prototype.clone = function () {
  57190. var newOne = new BoxParticleEmitter();
  57191. BABYLON.Tools.DeepCopy(this, newOne);
  57192. return newOne;
  57193. };
  57194. /**
  57195. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57196. * @param effect defines the update shader
  57197. */
  57198. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57199. effect.setVector3("direction1", this.direction1);
  57200. effect.setVector3("direction2", this.direction2);
  57201. effect.setVector3("minEmitBox", this.minEmitBox);
  57202. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57203. };
  57204. /**
  57205. * Returns a string to use to update the GPU particles update shader
  57206. * @returns a string containng the defines string
  57207. */
  57208. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57209. return "#define BOXEMITTER";
  57210. };
  57211. /**
  57212. * Returns the string "BoxEmitter"
  57213. * @returns a string containing the class name
  57214. */
  57215. BoxParticleEmitter.prototype.getClassName = function () {
  57216. return "BoxEmitter";
  57217. };
  57218. /**
  57219. * Serializes the particle system to a JSON object.
  57220. * @returns the JSON object
  57221. */
  57222. BoxParticleEmitter.prototype.serialize = function () {
  57223. var serializationObject = {};
  57224. serializationObject.type = this.getClassName();
  57225. serializationObject.direction1 = this.direction1.asArray();
  57226. serializationObject.direction2 = this.direction2.asArray();
  57227. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57228. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57229. return serializationObject;
  57230. };
  57231. /**
  57232. * Parse properties from a JSON object
  57233. * @param serializationObject defines the JSON object
  57234. */
  57235. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57236. this.direction1.copyFrom(serializationObject.direction1);
  57237. this.direction2.copyFrom(serializationObject.direction2);
  57238. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57239. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57240. };
  57241. return BoxParticleEmitter;
  57242. }());
  57243. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57244. })(BABYLON || (BABYLON = {}));
  57245. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57246. var BABYLON;
  57247. (function (BABYLON) {
  57248. /**
  57249. * Particle emitter emitting particles from the inside of a cone.
  57250. * It emits the particles alongside the cone volume from the base to the particle.
  57251. * The emission direction might be randomized.
  57252. */
  57253. var ConeParticleEmitter = /** @class */ (function () {
  57254. /**
  57255. * Creates a new instance ConeParticleEmitter
  57256. * @param radius the radius of the emission cone (1 by default)
  57257. * @param angles the cone base angle (PI by default)
  57258. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57259. */
  57260. function ConeParticleEmitter(radius,
  57261. /**
  57262. * The radius of the emission cone.
  57263. */
  57264. angle,
  57265. /**
  57266. * The cone base angle.
  57267. */
  57268. directionRandomizer) {
  57269. if (radius === void 0) { radius = 1; }
  57270. if (angle === void 0) { angle = Math.PI; }
  57271. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57272. this.angle = angle;
  57273. this.directionRandomizer = directionRandomizer;
  57274. this.radius = radius;
  57275. }
  57276. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57277. /**
  57278. * Gets the radius of the emission cone.
  57279. */
  57280. get: function () {
  57281. return this._radius;
  57282. },
  57283. /**
  57284. * Sets the radius of the emission cone.
  57285. */
  57286. set: function (value) {
  57287. this._radius = value;
  57288. if (this.angle !== 0) {
  57289. this._height = value / Math.tan(this.angle / 2);
  57290. }
  57291. else {
  57292. this._height = 1;
  57293. }
  57294. },
  57295. enumerable: true,
  57296. configurable: true
  57297. });
  57298. /**
  57299. * Called by the particle System when the direction is computed for the created particle.
  57300. * @param emitPower is the power of the particle (speed)
  57301. * @param worldMatrix is the world matrix of the particle system
  57302. * @param directionToUpdate is the direction vector to update with the result
  57303. * @param particle is the particle we are computed the direction for
  57304. */
  57305. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57306. if (this.angle === 0) {
  57307. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57308. }
  57309. else {
  57310. // measure the direction Vector from the emitter to the particle.
  57311. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57312. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57313. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57314. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57315. direction.x += randX;
  57316. direction.y += randY;
  57317. direction.z += randZ;
  57318. direction.normalize();
  57319. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57320. }
  57321. };
  57322. /**
  57323. * Called by the particle System when the position is computed for the created particle.
  57324. * @param worldMatrix is the world matrix of the particle system
  57325. * @param positionToUpdate is the position vector to update with the result
  57326. * @param particle is the particle we are computed the position for
  57327. */
  57328. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57329. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57330. var h = BABYLON.Scalar.RandomRange(0, 1);
  57331. // Better distribution in a cone at normal angles.
  57332. h = 1 - h * h;
  57333. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57334. radius = radius * h;
  57335. var randX = radius * Math.sin(s);
  57336. var randZ = radius * Math.cos(s);
  57337. var randY = h * this._height;
  57338. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57339. };
  57340. /**
  57341. * Clones the current emitter and returns a copy of it
  57342. * @returns the new emitter
  57343. */
  57344. ConeParticleEmitter.prototype.clone = function () {
  57345. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57346. BABYLON.Tools.DeepCopy(this, newOne);
  57347. return newOne;
  57348. };
  57349. /**
  57350. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57351. * @param effect defines the update shader
  57352. */
  57353. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57354. effect.setFloat("radius", this.radius);
  57355. effect.setFloat("coneAngle", this.angle);
  57356. effect.setFloat("height", this._height);
  57357. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57358. };
  57359. /**
  57360. * Returns a string to use to update the GPU particles update shader
  57361. * @returns a string containng the defines string
  57362. */
  57363. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57364. return "#define CONEEMITTER";
  57365. };
  57366. /**
  57367. * Returns the string "BoxEmitter"
  57368. * @returns a string containing the class name
  57369. */
  57370. ConeParticleEmitter.prototype.getClassName = function () {
  57371. return "ConeEmitter";
  57372. };
  57373. /**
  57374. * Serializes the particle system to a JSON object.
  57375. * @returns the JSON object
  57376. */
  57377. ConeParticleEmitter.prototype.serialize = function () {
  57378. var serializationObject = {};
  57379. serializationObject.type = this.getClassName();
  57380. serializationObject.radius = this.radius;
  57381. serializationObject.angle = this.angle;
  57382. serializationObject.directionRandomizer = this.directionRandomizer;
  57383. return serializationObject;
  57384. };
  57385. /**
  57386. * Parse properties from a JSON object
  57387. * @param serializationObject defines the JSON object
  57388. */
  57389. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57390. this.radius = serializationObject.radius;
  57391. this.angle = serializationObject.angle;
  57392. this.directionRandomizer = serializationObject.directionRandomizer;
  57393. };
  57394. return ConeParticleEmitter;
  57395. }());
  57396. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57397. })(BABYLON || (BABYLON = {}));
  57398. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57399. var BABYLON;
  57400. (function (BABYLON) {
  57401. /**
  57402. * Particle emitter emitting particles from the inside of a sphere.
  57403. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57404. */
  57405. var SphereParticleEmitter = /** @class */ (function () {
  57406. /**
  57407. * Creates a new instance SphereParticleEmitter
  57408. * @param radius the radius of the emission sphere (1 by default)
  57409. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57410. */
  57411. function SphereParticleEmitter(
  57412. /**
  57413. * The radius of the emission sphere.
  57414. */
  57415. radius,
  57416. /**
  57417. * How much to randomize the particle direction [0-1].
  57418. */
  57419. directionRandomizer) {
  57420. if (radius === void 0) { radius = 1; }
  57421. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57422. this.radius = radius;
  57423. this.directionRandomizer = directionRandomizer;
  57424. }
  57425. /**
  57426. * Called by the particle System when the direction is computed for the created particle.
  57427. * @param emitPower is the power of the particle (speed)
  57428. * @param worldMatrix is the world matrix of the particle system
  57429. * @param directionToUpdate is the direction vector to update with the result
  57430. * @param particle is the particle we are computed the direction for
  57431. */
  57432. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57433. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57434. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57435. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57436. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57437. direction.x += randX;
  57438. direction.y += randY;
  57439. direction.z += randZ;
  57440. direction.normalize();
  57441. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57442. };
  57443. /**
  57444. * Called by the particle System when the position is computed for the created particle.
  57445. * @param worldMatrix is the world matrix of the particle system
  57446. * @param positionToUpdate is the position vector to update with the result
  57447. * @param particle is the particle we are computed the position for
  57448. */
  57449. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57450. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57451. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57452. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57453. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57454. var randY = randRadius * Math.cos(theta);
  57455. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57456. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57457. };
  57458. /**
  57459. * Clones the current emitter and returns a copy of it
  57460. * @returns the new emitter
  57461. */
  57462. SphereParticleEmitter.prototype.clone = function () {
  57463. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57464. BABYLON.Tools.DeepCopy(this, newOne);
  57465. return newOne;
  57466. };
  57467. /**
  57468. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57469. * @param effect defines the update shader
  57470. */
  57471. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57472. effect.setFloat("radius", this.radius);
  57473. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57474. };
  57475. /**
  57476. * Returns a string to use to update the GPU particles update shader
  57477. * @returns a string containng the defines string
  57478. */
  57479. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57480. return "#define SPHEREEMITTER";
  57481. };
  57482. /**
  57483. * Returns the string "SphereParticleEmitter"
  57484. * @returns a string containing the class name
  57485. */
  57486. SphereParticleEmitter.prototype.getClassName = function () {
  57487. return "SphereParticleEmitter";
  57488. };
  57489. /**
  57490. * Serializes the particle system to a JSON object.
  57491. * @returns the JSON object
  57492. */
  57493. SphereParticleEmitter.prototype.serialize = function () {
  57494. var serializationObject = {};
  57495. serializationObject.type = this.getClassName();
  57496. serializationObject.radius = this.radius;
  57497. serializationObject.directionRandomizer = this.directionRandomizer;
  57498. return serializationObject;
  57499. };
  57500. /**
  57501. * Parse properties from a JSON object
  57502. * @param serializationObject defines the JSON object
  57503. */
  57504. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57505. this.radius = serializationObject.radius;
  57506. this.directionRandomizer = serializationObject.directionRandomizer;
  57507. };
  57508. return SphereParticleEmitter;
  57509. }());
  57510. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57511. /**
  57512. * Particle emitter emitting particles from the inside of a sphere.
  57513. * It emits the particles randomly between two vectors.
  57514. */
  57515. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57516. __extends(SphereDirectedParticleEmitter, _super);
  57517. /**
  57518. * Creates a new instance SphereDirectedParticleEmitter
  57519. * @param radius the radius of the emission sphere (1 by default)
  57520. * @param direction1 the min limit of the emission direction (up vector by default)
  57521. * @param direction2 the max limit of the emission direction (up vector by default)
  57522. */
  57523. function SphereDirectedParticleEmitter(radius,
  57524. /**
  57525. * The min limit of the emission direction.
  57526. */
  57527. direction1,
  57528. /**
  57529. * The max limit of the emission direction.
  57530. */
  57531. direction2) {
  57532. if (radius === void 0) { radius = 1; }
  57533. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57534. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57535. var _this = _super.call(this, radius) || this;
  57536. _this.direction1 = direction1;
  57537. _this.direction2 = direction2;
  57538. return _this;
  57539. }
  57540. /**
  57541. * Called by the particle System when the direction is computed for the created particle.
  57542. * @param emitPower is the power of the particle (speed)
  57543. * @param worldMatrix is the world matrix of the particle system
  57544. * @param directionToUpdate is the direction vector to update with the result
  57545. * @param particle is the particle we are computed the direction for
  57546. */
  57547. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57548. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57549. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57550. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57551. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57552. };
  57553. /**
  57554. * Clones the current emitter and returns a copy of it
  57555. * @returns the new emitter
  57556. */
  57557. SphereDirectedParticleEmitter.prototype.clone = function () {
  57558. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57559. BABYLON.Tools.DeepCopy(this, newOne);
  57560. return newOne;
  57561. };
  57562. /**
  57563. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57564. * @param effect defines the update shader
  57565. */
  57566. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57567. effect.setFloat("radius", this.radius);
  57568. effect.setVector3("direction1", this.direction1);
  57569. effect.setVector3("direction2", this.direction2);
  57570. };
  57571. /**
  57572. * Returns a string to use to update the GPU particles update shader
  57573. * @returns a string containng the defines string
  57574. */
  57575. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57576. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57577. };
  57578. /**
  57579. * Returns the string "SphereDirectedParticleEmitter"
  57580. * @returns a string containing the class name
  57581. */
  57582. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57583. return "SphereDirectedParticleEmitter";
  57584. };
  57585. /**
  57586. * Serializes the particle system to a JSON object.
  57587. * @returns the JSON object
  57588. */
  57589. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57590. var serializationObject = _super.prototype.serialize.call(this);
  57591. serializationObject.direction1 = this.direction1.asArray();
  57592. serializationObject.direction2 = this.direction2.asArray();
  57593. return serializationObject;
  57594. };
  57595. /**
  57596. * Parse properties from a JSON object
  57597. * @param serializationObject defines the JSON object
  57598. */
  57599. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57600. _super.prototype.parse.call(this, serializationObject);
  57601. this.direction1.copyFrom(serializationObject.direction1);
  57602. this.direction2.copyFrom(serializationObject.direction2);
  57603. };
  57604. return SphereDirectedParticleEmitter;
  57605. }(SphereParticleEmitter));
  57606. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57607. })(BABYLON || (BABYLON = {}));
  57608. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57609. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57610. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57611. s = arguments[i];
  57612. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57613. t[p] = s[p];
  57614. }
  57615. return t;
  57616. };
  57617. var BABYLON;
  57618. (function (BABYLON) {
  57619. /**
  57620. * This represents a GPU particle system in Babylon
  57621. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57622. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57623. */
  57624. var GPUParticleSystem = /** @class */ (function () {
  57625. /**
  57626. * Instantiates a GPU particle system.
  57627. * 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.
  57628. * @param name The name of the particle system
  57629. * @param capacity The max number of particles alive at the same time
  57630. * @param scene The scene the particle system belongs to
  57631. */
  57632. function GPUParticleSystem(name, options, scene) {
  57633. /**
  57634. * The emitter represents the Mesh or position we are attaching the particle system to.
  57635. */
  57636. this.emitter = null;
  57637. /**
  57638. * The rendering group used by the Particle system to chose when to render.
  57639. */
  57640. this.renderingGroupId = 0;
  57641. /**
  57642. * The layer mask we are rendering the particles through.
  57643. */
  57644. this.layerMask = 0x0FFFFFFF;
  57645. this._targetIndex = 0;
  57646. this._currentRenderId = -1;
  57647. this._started = false;
  57648. this._stopped = false;
  57649. this._timeDelta = 0;
  57650. this._attributesStrideSize = 16;
  57651. this._actualFrame = 0;
  57652. /**
  57653. * List of animations used by the particle system.
  57654. */
  57655. this.animations = [];
  57656. /**
  57657. * An event triggered when the system is disposed.
  57658. */
  57659. this.onDisposeObservable = new BABYLON.Observable();
  57660. /**
  57661. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57662. */
  57663. this.updateSpeed = 0.01;
  57664. /**
  57665. * The amount of time the particle system is running (depends of the overall update speed).
  57666. */
  57667. this.targetStopDuration = 0;
  57668. /**
  57669. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57670. */
  57671. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57672. /**
  57673. * Minimum life time of emitting particles.
  57674. */
  57675. this.minLifeTime = 1;
  57676. /**
  57677. * Maximum life time of emitting particles.
  57678. */
  57679. this.maxLifeTime = 1;
  57680. /**
  57681. * Minimum Size of emitting particles.
  57682. */
  57683. this.minSize = 1;
  57684. /**
  57685. * Maximum Size of emitting particles.
  57686. */
  57687. this.maxSize = 1;
  57688. /**
  57689. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57690. */
  57691. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57692. /**
  57693. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57694. */
  57695. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57696. /**
  57697. * Color the particle will have at the end of its lifetime.
  57698. */
  57699. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57700. /**
  57701. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57702. */
  57703. this.emitRate = 100;
  57704. /**
  57705. * You can use gravity if you want to give an orientation to your particles.
  57706. */
  57707. this.gravity = BABYLON.Vector3.Zero();
  57708. /**
  57709. * Minimum power of emitting particles.
  57710. */
  57711. this.minEmitPower = 1;
  57712. /**
  57713. * Maximum power of emitting particles.
  57714. */
  57715. this.maxEmitPower = 1;
  57716. /**
  57717. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57718. */
  57719. this.minAngularSpeed = 0;
  57720. /**
  57721. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57722. */
  57723. this.maxAngularSpeed = 0;
  57724. /**
  57725. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57726. * to override the particles.
  57727. */
  57728. this.forceDepthWrite = false;
  57729. this.id = name;
  57730. this.name = name;
  57731. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57732. this._engine = this._scene.getEngine();
  57733. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57734. this._capacity = fullOptions.capacity;
  57735. this._activeCount = fullOptions.capacity;
  57736. this._currentActiveCount = 0;
  57737. this._scene.particleSystems.push(this);
  57738. this._updateEffectOptions = {
  57739. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57740. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57741. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57742. "angleRange"],
  57743. uniformBuffersNames: [],
  57744. samplers: ["randomSampler"],
  57745. defines: "",
  57746. fallbacks: null,
  57747. onCompiled: null,
  57748. onError: null,
  57749. indexParameters: null,
  57750. maxSimultaneousLights: 0,
  57751. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57752. };
  57753. // Random data
  57754. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57755. var d = [];
  57756. for (var i = 0; i < maxTextureSize; ++i) {
  57757. d.push(Math.random());
  57758. d.push(Math.random());
  57759. d.push(Math.random());
  57760. d.push(Math.random());
  57761. }
  57762. 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);
  57763. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57764. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57765. this._randomTextureSize = maxTextureSize;
  57766. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57767. }
  57768. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57769. /**
  57770. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57771. */
  57772. get: function () {
  57773. if (!BABYLON.Engine.LastCreatedEngine) {
  57774. return false;
  57775. }
  57776. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57777. },
  57778. enumerable: true,
  57779. configurable: true
  57780. });
  57781. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57782. /**
  57783. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57784. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57785. */
  57786. get: function () {
  57787. if (this.particleEmitterType.direction1) {
  57788. return this.particleEmitterType.direction1;
  57789. }
  57790. return BABYLON.Vector3.Zero();
  57791. },
  57792. set: function (value) {
  57793. if (this.particleEmitterType.direction1) {
  57794. this.particleEmitterType.direction1 = value;
  57795. }
  57796. },
  57797. enumerable: true,
  57798. configurable: true
  57799. });
  57800. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57801. /**
  57802. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57803. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57804. */
  57805. get: function () {
  57806. if (this.particleEmitterType.direction2) {
  57807. return this.particleEmitterType.direction2;
  57808. }
  57809. return BABYLON.Vector3.Zero();
  57810. },
  57811. set: function (value) {
  57812. if (this.particleEmitterType.direction2) {
  57813. this.particleEmitterType.direction2 = value;
  57814. }
  57815. },
  57816. enumerable: true,
  57817. configurable: true
  57818. });
  57819. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57820. /**
  57821. * 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.
  57822. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57823. */
  57824. get: function () {
  57825. if (this.particleEmitterType.minEmitBox) {
  57826. return this.particleEmitterType.minEmitBox;
  57827. }
  57828. return BABYLON.Vector3.Zero();
  57829. },
  57830. set: function (value) {
  57831. if (this.particleEmitterType.minEmitBox) {
  57832. this.particleEmitterType.minEmitBox = value;
  57833. }
  57834. },
  57835. enumerable: true,
  57836. configurable: true
  57837. });
  57838. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57839. /**
  57840. * 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.
  57841. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57842. */
  57843. get: function () {
  57844. if (this.particleEmitterType.maxEmitBox) {
  57845. return this.particleEmitterType.maxEmitBox;
  57846. }
  57847. return BABYLON.Vector3.Zero();
  57848. },
  57849. set: function (value) {
  57850. if (this.particleEmitterType.maxEmitBox) {
  57851. this.particleEmitterType.maxEmitBox = value;
  57852. }
  57853. },
  57854. enumerable: true,
  57855. configurable: true
  57856. });
  57857. /**
  57858. * Gets the maximum number of particles active at the same time.
  57859. * @returns The max number of active particles.
  57860. */
  57861. GPUParticleSystem.prototype.getCapacity = function () {
  57862. return this._capacity;
  57863. };
  57864. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57865. /**
  57866. * Gets or set the number of active particles
  57867. */
  57868. get: function () {
  57869. return this._activeCount;
  57870. },
  57871. set: function (value) {
  57872. this._activeCount = Math.min(value, this._capacity);
  57873. },
  57874. enumerable: true,
  57875. configurable: true
  57876. });
  57877. /**
  57878. * Is this system ready to be used/rendered
  57879. * @return true if the system is ready
  57880. */
  57881. GPUParticleSystem.prototype.isReady = function () {
  57882. if (!this._updateEffect) {
  57883. this._recreateUpdateEffect();
  57884. this._recreateRenderEffect();
  57885. return false;
  57886. }
  57887. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57888. return false;
  57889. }
  57890. return true;
  57891. };
  57892. /**
  57893. * Gets Wether the system has been started.
  57894. * @returns True if it has been started, otherwise false.
  57895. */
  57896. GPUParticleSystem.prototype.isStarted = function () {
  57897. return this._started;
  57898. };
  57899. /**
  57900. * Starts the particle system and begins to emit.
  57901. */
  57902. GPUParticleSystem.prototype.start = function () {
  57903. this._started = true;
  57904. this._stopped = false;
  57905. };
  57906. /**
  57907. * Stops the particle system.
  57908. */
  57909. GPUParticleSystem.prototype.stop = function () {
  57910. this._stopped = true;
  57911. };
  57912. /**
  57913. * Remove all active particles
  57914. */
  57915. GPUParticleSystem.prototype.reset = function () {
  57916. this._releaseBuffers();
  57917. this._releaseVAOs();
  57918. this._currentActiveCount = 0;
  57919. this._targetIndex = 0;
  57920. };
  57921. /**
  57922. * Returns the string "GPUParticleSystem"
  57923. * @returns a string containing the class name
  57924. */
  57925. GPUParticleSystem.prototype.getClassName = function () {
  57926. return "GPUParticleSystem";
  57927. };
  57928. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57929. var updateVertexBuffers = {};
  57930. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57931. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57932. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57933. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57934. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57935. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57936. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57937. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57938. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57939. this._engine.bindArrayBuffer(null);
  57940. return vao;
  57941. };
  57942. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57943. var renderVertexBuffers = {};
  57944. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57945. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57946. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57947. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57948. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57949. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57950. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57951. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57952. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57953. this._engine.bindArrayBuffer(null);
  57954. return vao;
  57955. };
  57956. GPUParticleSystem.prototype._initialize = function (force) {
  57957. if (force === void 0) { force = false; }
  57958. if (this._buffer0 && !force) {
  57959. return;
  57960. }
  57961. var engine = this._scene.getEngine();
  57962. var data = new Array();
  57963. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57964. // position
  57965. data.push(0.0);
  57966. data.push(0.0);
  57967. data.push(0.0);
  57968. // Age and life
  57969. data.push(0.0); // create the particle as a dead one to create a new one at start
  57970. data.push(0.0);
  57971. // Seed
  57972. data.push(Math.random());
  57973. // Size
  57974. data.push(0.0);
  57975. // color
  57976. data.push(0.0);
  57977. data.push(0.0);
  57978. data.push(0.0);
  57979. data.push(0.0);
  57980. // direction
  57981. data.push(0.0);
  57982. data.push(0.0);
  57983. data.push(0.0);
  57984. // angle
  57985. data.push(0.0);
  57986. data.push(0.0);
  57987. }
  57988. // Sprite data
  57989. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57990. -0.5, 0.5, 0, 1,
  57991. -0.5, -0.5, 0, 0,
  57992. 0.5, -0.5, 1, 0]);
  57993. // Buffers
  57994. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57995. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57996. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57997. // Update VAO
  57998. this._updateVAO = [];
  57999. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  58000. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  58001. // Render VAO
  58002. this._renderVAO = [];
  58003. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  58004. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  58005. // Links
  58006. this._sourceBuffer = this._buffer0;
  58007. this._targetBuffer = this._buffer1;
  58008. };
  58009. /** @hidden */
  58010. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  58011. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  58012. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  58013. return;
  58014. }
  58015. this._updateEffectOptions.defines = defines;
  58016. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  58017. };
  58018. /** @hidden */
  58019. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  58020. var defines = "";
  58021. if (this._scene.clipPlane) {
  58022. defines = "\n#define CLIPPLANE";
  58023. }
  58024. if (this._renderEffect && this._renderEffect.defines === defines) {
  58025. return;
  58026. }
  58027. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  58028. };
  58029. /**
  58030. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58031. */
  58032. GPUParticleSystem.prototype.animate = function () {
  58033. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  58034. this._actualFrame += this._timeDelta;
  58035. if (!this._stopped) {
  58036. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58037. this.stop();
  58038. }
  58039. }
  58040. };
  58041. /**
  58042. * Renders the particle system in its current state.
  58043. * @returns the current number of particles
  58044. */
  58045. GPUParticleSystem.prototype.render = function () {
  58046. if (!this._started) {
  58047. return 0;
  58048. }
  58049. this._recreateUpdateEffect();
  58050. this._recreateRenderEffect();
  58051. if (!this.isReady()) {
  58052. return 0;
  58053. }
  58054. if (this._currentRenderId === this._scene.getRenderId()) {
  58055. return 0;
  58056. }
  58057. this._currentRenderId = this._scene.getRenderId();
  58058. // Get everything ready to render
  58059. this._initialize();
  58060. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58061. // Enable update effect
  58062. this._engine.enableEffect(this._updateEffect);
  58063. this._engine.setState(false);
  58064. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58065. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58066. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58067. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58068. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58069. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58070. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58071. this._updateEffect.setDirectColor4("color1", this.color1);
  58072. this._updateEffect.setDirectColor4("color2", this.color2);
  58073. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58074. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58075. this._updateEffect.setVector3("gravity", this.gravity);
  58076. if (this.particleEmitterType) {
  58077. this.particleEmitterType.applyToShader(this._updateEffect);
  58078. }
  58079. var emitterWM;
  58080. if (this.emitter.position) {
  58081. var emitterMesh = this.emitter;
  58082. emitterWM = emitterMesh.getWorldMatrix();
  58083. }
  58084. else {
  58085. var emitterPosition = this.emitter;
  58086. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58087. }
  58088. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58089. // Bind source VAO
  58090. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58091. // Update
  58092. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58093. this._engine.setRasterizerState(false);
  58094. this._engine.beginTransformFeedback();
  58095. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58096. this._engine.endTransformFeedback();
  58097. this._engine.setRasterizerState(true);
  58098. this._engine.bindTransformFeedbackBuffer(null);
  58099. // Enable render effect
  58100. this._engine.enableEffect(this._renderEffect);
  58101. var viewMatrix = this._scene.getViewMatrix();
  58102. this._renderEffect.setMatrix("view", viewMatrix);
  58103. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58104. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58105. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58106. if (this._scene.clipPlane) {
  58107. var clipPlane = this._scene.clipPlane;
  58108. var invView = viewMatrix.clone();
  58109. invView.invert();
  58110. this._renderEffect.setMatrix("invView", invView);
  58111. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58112. }
  58113. // Draw order
  58114. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58115. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58116. }
  58117. else {
  58118. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58119. }
  58120. if (this.forceDepthWrite) {
  58121. this._engine.setDepthWrite(true);
  58122. }
  58123. // Bind source VAO
  58124. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58125. // Render
  58126. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58127. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58128. // Switch VAOs
  58129. this._targetIndex++;
  58130. if (this._targetIndex === 2) {
  58131. this._targetIndex = 0;
  58132. }
  58133. // Switch buffers
  58134. var tmpBuffer = this._sourceBuffer;
  58135. this._sourceBuffer = this._targetBuffer;
  58136. this._targetBuffer = tmpBuffer;
  58137. return this._currentActiveCount;
  58138. };
  58139. /**
  58140. * Rebuilds the particle system
  58141. */
  58142. GPUParticleSystem.prototype.rebuild = function () {
  58143. this._initialize(true);
  58144. };
  58145. GPUParticleSystem.prototype._releaseBuffers = function () {
  58146. if (this._buffer0) {
  58147. this._buffer0.dispose();
  58148. this._buffer0 = null;
  58149. }
  58150. if (this._buffer1) {
  58151. this._buffer1.dispose();
  58152. this._buffer1 = null;
  58153. }
  58154. if (this._spriteBuffer) {
  58155. this._spriteBuffer.dispose();
  58156. this._spriteBuffer = null;
  58157. }
  58158. };
  58159. GPUParticleSystem.prototype._releaseVAOs = function () {
  58160. if (!this._updateVAO) {
  58161. return;
  58162. }
  58163. for (var index = 0; index < this._updateVAO.length; index++) {
  58164. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58165. }
  58166. this._updateVAO = [];
  58167. for (var index = 0; index < this._renderVAO.length; index++) {
  58168. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58169. }
  58170. this._renderVAO = [];
  58171. };
  58172. /**
  58173. * Disposes the particle system and free the associated resources
  58174. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58175. */
  58176. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58177. if (disposeTexture === void 0) { disposeTexture = true; }
  58178. var index = this._scene.particleSystems.indexOf(this);
  58179. if (index > -1) {
  58180. this._scene.particleSystems.splice(index, 1);
  58181. }
  58182. this._releaseBuffers();
  58183. this._releaseVAOs();
  58184. if (this._randomTexture) {
  58185. this._randomTexture.dispose();
  58186. this._randomTexture = null;
  58187. }
  58188. if (disposeTexture && this.particleTexture) {
  58189. this.particleTexture.dispose();
  58190. this.particleTexture = null;
  58191. }
  58192. // Callback
  58193. this.onDisposeObservable.notifyObservers(this);
  58194. this.onDisposeObservable.clear();
  58195. };
  58196. /**
  58197. * Clones the particle system.
  58198. * @param name The name of the cloned object
  58199. * @param newEmitter The new emitter to use
  58200. * @returns the cloned particle system
  58201. */
  58202. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58203. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58204. BABYLON.Tools.DeepCopy(this, result);
  58205. if (newEmitter === undefined) {
  58206. newEmitter = this.emitter;
  58207. }
  58208. result.emitter = newEmitter;
  58209. if (this.particleTexture) {
  58210. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58211. }
  58212. return result;
  58213. };
  58214. /**
  58215. * Serializes the particle system to a JSON object.
  58216. * @returns the JSON object
  58217. */
  58218. GPUParticleSystem.prototype.serialize = function () {
  58219. var serializationObject = {};
  58220. serializationObject.name = this.name;
  58221. serializationObject.id = this.id;
  58222. // Emitter
  58223. if (this.emitter.position) {
  58224. var emitterMesh = this.emitter;
  58225. serializationObject.emitterId = emitterMesh.id;
  58226. }
  58227. else {
  58228. var emitterPosition = this.emitter;
  58229. serializationObject.emitter = emitterPosition.asArray();
  58230. }
  58231. serializationObject.capacity = this.getCapacity();
  58232. if (this.particleTexture) {
  58233. serializationObject.textureName = this.particleTexture.name;
  58234. }
  58235. // Animations
  58236. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58237. // Particle system
  58238. serializationObject.activeParticleCount = this.activeParticleCount;
  58239. serializationObject.randomTextureSize = this._randomTextureSize;
  58240. serializationObject.minSize = this.minSize;
  58241. serializationObject.maxSize = this.maxSize;
  58242. serializationObject.minEmitPower = this.minEmitPower;
  58243. serializationObject.maxEmitPower = this.maxEmitPower;
  58244. serializationObject.minLifeTime = this.minLifeTime;
  58245. serializationObject.maxLifeTime = this.maxLifeTime;
  58246. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58247. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58248. serializationObject.emitRate = this.emitRate;
  58249. serializationObject.gravity = this.gravity.asArray();
  58250. serializationObject.color1 = this.color1.asArray();
  58251. serializationObject.color2 = this.color2.asArray();
  58252. serializationObject.colorDead = this.colorDead.asArray();
  58253. serializationObject.updateSpeed = this.updateSpeed;
  58254. serializationObject.targetStopDuration = this.targetStopDuration;
  58255. serializationObject.blendMode = this.blendMode;
  58256. // Emitter
  58257. if (this.particleEmitterType) {
  58258. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58259. }
  58260. return serializationObject;
  58261. };
  58262. /**
  58263. * Parses a JSON object to create a GPU particle system.
  58264. * @param parsedParticleSystem The JSON object to parse
  58265. * @param scene The scene to create the particle system in
  58266. * @param rootUrl The root url to use to load external dependencies like texture
  58267. * @returns the parsed GPU particle system
  58268. */
  58269. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58270. var name = parsedParticleSystem.name;
  58271. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58272. if (parsedParticleSystem.id) {
  58273. particleSystem.id = parsedParticleSystem.id;
  58274. }
  58275. // Texture
  58276. if (parsedParticleSystem.textureName) {
  58277. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58278. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58279. }
  58280. // Emitter
  58281. if (parsedParticleSystem.emitterId) {
  58282. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58283. }
  58284. else {
  58285. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58286. }
  58287. // Animations
  58288. if (parsedParticleSystem.animations) {
  58289. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58290. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58291. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58292. }
  58293. }
  58294. // Particle system
  58295. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58296. particleSystem.minSize = parsedParticleSystem.minSize;
  58297. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58298. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58299. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58300. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58301. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58302. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58303. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58304. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58305. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58306. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58307. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58308. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58309. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58310. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58311. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58312. // Emitter
  58313. if (parsedParticleSystem.particleEmitterType) {
  58314. var emitterType = void 0;
  58315. switch (parsedParticleSystem.particleEmitterType.type) {
  58316. case "SphereEmitter":
  58317. emitterType = new BABYLON.SphereParticleEmitter();
  58318. break;
  58319. case "SphereDirectedParticleEmitter":
  58320. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58321. break;
  58322. case "ConeEmitter":
  58323. emitterType = new BABYLON.ConeParticleEmitter();
  58324. break;
  58325. case "BoxEmitter":
  58326. default:
  58327. emitterType = new BABYLON.BoxParticleEmitter();
  58328. break;
  58329. }
  58330. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58331. particleSystem.particleEmitterType = emitterType;
  58332. }
  58333. return particleSystem;
  58334. };
  58335. return GPUParticleSystem;
  58336. }());
  58337. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58338. })(BABYLON || (BABYLON = {}));
  58339. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58340. var BABYLON;
  58341. (function (BABYLON) {
  58342. /**
  58343. * Represents one particle of a solid particle system.
  58344. */
  58345. var SolidParticle = /** @class */ (function () {
  58346. /**
  58347. * Creates a Solid Particle object.
  58348. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58349. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58350. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58351. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58352. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58353. * @param shapeId (integer) is the model shape identifier in the SPS.
  58354. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58355. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58356. */
  58357. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58358. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58359. /**
  58360. * particle global index
  58361. */
  58362. this.idx = 0;
  58363. /**
  58364. * The color of the particle
  58365. */
  58366. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58367. /**
  58368. * The world space position of the particle.
  58369. */
  58370. this.position = BABYLON.Vector3.Zero();
  58371. /**
  58372. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58373. */
  58374. this.rotation = BABYLON.Vector3.Zero();
  58375. /**
  58376. * The scaling of the particle.
  58377. */
  58378. this.scaling = BABYLON.Vector3.One();
  58379. /**
  58380. * The uvs of the particle.
  58381. */
  58382. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58383. /**
  58384. * The current speed of the particle.
  58385. */
  58386. this.velocity = BABYLON.Vector3.Zero();
  58387. /**
  58388. * The pivot point in the particle local space.
  58389. */
  58390. this.pivot = BABYLON.Vector3.Zero();
  58391. /**
  58392. * Must the particle be translated from its pivot point in its local space ?
  58393. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58394. * Default : false
  58395. */
  58396. this.translateFromPivot = false;
  58397. /**
  58398. * Is the particle active or not ?
  58399. */
  58400. this.alive = true;
  58401. /**
  58402. * Is the particle visible or not ?
  58403. */
  58404. this.isVisible = true;
  58405. /**
  58406. * Index of this particle in the global "positions" array (Internal use)
  58407. */
  58408. this._pos = 0;
  58409. /**
  58410. * Index of this particle in the global "indices" array (Internal use)
  58411. */
  58412. this._ind = 0;
  58413. /**
  58414. * ModelShape id of this particle
  58415. */
  58416. this.shapeId = 0;
  58417. /**
  58418. * Index of the particle in its shape id (Internal use)
  58419. */
  58420. this.idxInShape = 0;
  58421. /**
  58422. * Still set as invisible in order to skip useless computations (Internal use)
  58423. */
  58424. this._stillInvisible = false;
  58425. /**
  58426. * Last computed particle rotation matrix
  58427. */
  58428. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58429. /**
  58430. * Parent particle Id, if any.
  58431. * Default null.
  58432. */
  58433. this.parentId = null;
  58434. /**
  58435. * Internal global position in the SPS.
  58436. */
  58437. this._globalPosition = BABYLON.Vector3.Zero();
  58438. this.idx = particleIndex;
  58439. this._pos = positionIndex;
  58440. this._ind = indiceIndex;
  58441. this._model = model;
  58442. this.shapeId = shapeId;
  58443. this.idxInShape = idxInShape;
  58444. this._sps = sps;
  58445. if (modelBoundingInfo) {
  58446. this._modelBoundingInfo = modelBoundingInfo;
  58447. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58448. }
  58449. }
  58450. Object.defineProperty(SolidParticle.prototype, "scale", {
  58451. /**
  58452. * Legacy support, changed scale to scaling
  58453. */
  58454. get: function () {
  58455. return this.scaling;
  58456. },
  58457. /**
  58458. * Legacy support, changed scale to scaling
  58459. */
  58460. set: function (scale) {
  58461. this.scaling = scale;
  58462. },
  58463. enumerable: true,
  58464. configurable: true
  58465. });
  58466. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58467. /**
  58468. * Legacy support, changed quaternion to rotationQuaternion
  58469. */
  58470. get: function () {
  58471. return this.rotationQuaternion;
  58472. },
  58473. /**
  58474. * Legacy support, changed quaternion to rotationQuaternion
  58475. */
  58476. set: function (q) {
  58477. this.rotationQuaternion = q;
  58478. },
  58479. enumerable: true,
  58480. configurable: true
  58481. });
  58482. /**
  58483. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58484. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58485. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58486. * @returns true if it intersects
  58487. */
  58488. SolidParticle.prototype.intersectsMesh = function (target) {
  58489. if (!this._boundingInfo || !target._boundingInfo) {
  58490. return false;
  58491. }
  58492. if (this._sps._bSphereOnly) {
  58493. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58494. }
  58495. return this._boundingInfo.intersects(target._boundingInfo, false);
  58496. };
  58497. return SolidParticle;
  58498. }());
  58499. BABYLON.SolidParticle = SolidParticle;
  58500. /**
  58501. * Represents the shape of the model used by one particle of a solid particle system.
  58502. * SPS internal tool, don't use it manually.
  58503. */
  58504. var ModelShape = /** @class */ (function () {
  58505. /**
  58506. * 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.
  58507. * SPS internal tool, don't use it manually.
  58508. * @hidden
  58509. */
  58510. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58511. /**
  58512. * length of the shape in the model indices array (internal use)
  58513. */
  58514. this._indicesLength = 0;
  58515. this.shapeID = id;
  58516. this._shape = shape;
  58517. this._indicesLength = indicesLength;
  58518. this._shapeUV = shapeUV;
  58519. this._positionFunction = posFunction;
  58520. this._vertexFunction = vtxFunction;
  58521. }
  58522. return ModelShape;
  58523. }());
  58524. BABYLON.ModelShape = ModelShape;
  58525. /**
  58526. * Represents a Depth Sorted Particle in the solid particle system.
  58527. */
  58528. var DepthSortedParticle = /** @class */ (function () {
  58529. function DepthSortedParticle() {
  58530. /**
  58531. * Index of the particle in the "indices" array
  58532. */
  58533. this.ind = 0;
  58534. /**
  58535. * Length of the particle shape in the "indices" array
  58536. */
  58537. this.indicesLength = 0;
  58538. /**
  58539. * Squared distance from the particle to the camera
  58540. */
  58541. this.sqDistance = 0.0;
  58542. }
  58543. return DepthSortedParticle;
  58544. }());
  58545. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58546. })(BABYLON || (BABYLON = {}));
  58547. //# sourceMappingURL=babylon.solidParticle.js.map
  58548. var BABYLON;
  58549. (function (BABYLON) {
  58550. /**
  58551. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58552. *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.
  58553. * The SPS is also a particle system. It provides some methods to manage the particles.
  58554. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58555. *
  58556. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58557. */
  58558. var SolidParticleSystem = /** @class */ (function () {
  58559. /**
  58560. * Creates a SPS (Solid Particle System) object.
  58561. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58562. * @param scene (Scene) is the scene in which the SPS is added.
  58563. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58564. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58565. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58566. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58567. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58568. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58569. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58570. */
  58571. function SolidParticleSystem(name, scene, options) {
  58572. /**
  58573. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58574. * Example : var p = SPS.particles[i];
  58575. */
  58576. this.particles = new Array();
  58577. /**
  58578. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58579. */
  58580. this.nbParticles = 0;
  58581. /**
  58582. * If the particles must ever face the camera (default false). Useful for planar particles.
  58583. */
  58584. this.billboard = false;
  58585. /**
  58586. * Recompute normals when adding a shape
  58587. */
  58588. this.recomputeNormals = true;
  58589. /**
  58590. * This a counter ofr your own usage. It's not set by any SPS functions.
  58591. */
  58592. this.counter = 0;
  58593. /**
  58594. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58595. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58596. */
  58597. this.vars = {};
  58598. /**
  58599. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58600. */
  58601. this._bSphereOnly = false;
  58602. /**
  58603. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58604. */
  58605. this._bSphereRadiusFactor = 1.0;
  58606. this._positions = new Array();
  58607. this._indices = new Array();
  58608. this._normals = new Array();
  58609. this._colors = new Array();
  58610. this._uvs = new Array();
  58611. this._index = 0; // indices index
  58612. this._updatable = true;
  58613. this._pickable = false;
  58614. this._isVisibilityBoxLocked = false;
  58615. this._alwaysVisible = false;
  58616. this._depthSort = false;
  58617. this._shapeCounter = 0;
  58618. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58619. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58620. this._computeParticleColor = true;
  58621. this._computeParticleTexture = true;
  58622. this._computeParticleRotation = true;
  58623. this._computeParticleVertex = false;
  58624. this._computeBoundingBox = false;
  58625. this._depthSortParticles = true;
  58626. this._cam_axisZ = BABYLON.Vector3.Zero();
  58627. this._cam_axisY = BABYLON.Vector3.Zero();
  58628. this._cam_axisX = BABYLON.Vector3.Zero();
  58629. this._axisZ = BABYLON.Axis.Z;
  58630. this._camDir = BABYLON.Vector3.Zero();
  58631. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58632. this._rotMatrix = new BABYLON.Matrix();
  58633. this._invertMatrix = new BABYLON.Matrix();
  58634. this._rotated = BABYLON.Vector3.Zero();
  58635. this._quaternion = new BABYLON.Quaternion();
  58636. this._vertex = BABYLON.Vector3.Zero();
  58637. this._normal = BABYLON.Vector3.Zero();
  58638. this._yaw = 0.0;
  58639. this._pitch = 0.0;
  58640. this._roll = 0.0;
  58641. this._halfroll = 0.0;
  58642. this._halfpitch = 0.0;
  58643. this._halfyaw = 0.0;
  58644. this._sinRoll = 0.0;
  58645. this._cosRoll = 0.0;
  58646. this._sinPitch = 0.0;
  58647. this._cosPitch = 0.0;
  58648. this._sinYaw = 0.0;
  58649. this._cosYaw = 0.0;
  58650. this._mustUnrotateFixedNormals = false;
  58651. this._minimum = BABYLON.Vector3.Zero();
  58652. this._maximum = BABYLON.Vector3.Zero();
  58653. this._minBbox = BABYLON.Vector3.Zero();
  58654. this._maxBbox = BABYLON.Vector3.Zero();
  58655. this._particlesIntersect = false;
  58656. this._depthSortFunction = function (p1, p2) {
  58657. return (p2.sqDistance - p1.sqDistance);
  58658. };
  58659. this._needs32Bits = false;
  58660. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58661. this._scaledPivot = BABYLON.Vector3.Zero();
  58662. this._particleHasParent = false;
  58663. this.name = name;
  58664. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58665. this._camera = scene.activeCamera;
  58666. this._pickable = options ? options.isPickable : false;
  58667. this._depthSort = options ? options.enableDepthSort : false;
  58668. this._particlesIntersect = options ? options.particleIntersection : false;
  58669. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58670. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58671. if (options && options.updatable) {
  58672. this._updatable = options.updatable;
  58673. }
  58674. else {
  58675. this._updatable = true;
  58676. }
  58677. if (this._pickable) {
  58678. this.pickedParticles = [];
  58679. }
  58680. if (this._depthSort) {
  58681. this.depthSortedParticles = [];
  58682. }
  58683. }
  58684. /**
  58685. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58686. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58687. * @returns the created mesh
  58688. */
  58689. SolidParticleSystem.prototype.buildMesh = function () {
  58690. if (this.nbParticles === 0) {
  58691. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58692. this.addShape(triangle, 1);
  58693. triangle.dispose();
  58694. }
  58695. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58696. this._positions32 = new Float32Array(this._positions);
  58697. this._uvs32 = new Float32Array(this._uvs);
  58698. this._colors32 = new Float32Array(this._colors);
  58699. if (this.recomputeNormals) {
  58700. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58701. }
  58702. this._normals32 = new Float32Array(this._normals);
  58703. this._fixedNormal32 = new Float32Array(this._normals);
  58704. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58705. this._unrotateFixedNormals();
  58706. }
  58707. var vertexData = new BABYLON.VertexData();
  58708. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58709. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58710. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58711. if (this._uvs32.length > 0) {
  58712. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58713. }
  58714. if (this._colors32.length > 0) {
  58715. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58716. }
  58717. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58718. vertexData.applyToMesh(mesh, this._updatable);
  58719. this.mesh = mesh;
  58720. this.mesh.isPickable = this._pickable;
  58721. // free memory
  58722. if (!this._depthSort) {
  58723. this._indices = null;
  58724. }
  58725. this._positions = null;
  58726. this._normals = null;
  58727. this._uvs = null;
  58728. this._colors = null;
  58729. if (!this._updatable) {
  58730. this.particles.length = 0;
  58731. }
  58732. return mesh;
  58733. };
  58734. /**
  58735. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58736. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58737. * Thus the particles generated from `digest()` have their property `position` set yet.
  58738. * @param mesh ( Mesh ) is the mesh to be digested
  58739. * @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
  58740. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58741. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58742. * @returns the current SPS
  58743. */
  58744. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58745. var size = (options && options.facetNb) || 1;
  58746. var number = (options && options.number) || 0;
  58747. var delta = (options && options.delta) || 0;
  58748. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58749. var meshInd = mesh.getIndices();
  58750. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58751. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58752. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58753. var f = 0; // facet counter
  58754. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58755. // compute size from number
  58756. if (number) {
  58757. number = (number > totalFacets) ? totalFacets : number;
  58758. size = Math.round(totalFacets / number);
  58759. delta = 0;
  58760. }
  58761. else {
  58762. size = (size > totalFacets) ? totalFacets : size;
  58763. }
  58764. var facetPos = []; // submesh positions
  58765. var facetInd = []; // submesh indices
  58766. var facetUV = []; // submesh UV
  58767. var facetCol = []; // submesh colors
  58768. var barycenter = BABYLON.Vector3.Zero();
  58769. var sizeO = size;
  58770. while (f < totalFacets) {
  58771. size = sizeO + Math.floor((1 + delta) * Math.random());
  58772. if (f > totalFacets - size) {
  58773. size = totalFacets - f;
  58774. }
  58775. // reset temp arrays
  58776. facetPos.length = 0;
  58777. facetInd.length = 0;
  58778. facetUV.length = 0;
  58779. facetCol.length = 0;
  58780. // iterate over "size" facets
  58781. var fi = 0;
  58782. for (var j = f * 3; j < (f + size) * 3; j++) {
  58783. facetInd.push(fi);
  58784. var i = meshInd[j];
  58785. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58786. if (meshUV) {
  58787. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58788. }
  58789. if (meshCol) {
  58790. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58791. }
  58792. fi++;
  58793. }
  58794. // create a model shape for each single particle
  58795. var idx = this.nbParticles;
  58796. var shape = this._posToShape(facetPos);
  58797. var shapeUV = this._uvsToShapeUV(facetUV);
  58798. // compute the barycenter of the shape
  58799. var v;
  58800. for (v = 0; v < shape.length; v++) {
  58801. barycenter.addInPlace(shape[v]);
  58802. }
  58803. barycenter.scaleInPlace(1 / shape.length);
  58804. // shift the shape from its barycenter to the origin
  58805. for (v = 0; v < shape.length; v++) {
  58806. shape[v].subtractInPlace(barycenter);
  58807. }
  58808. var bInfo;
  58809. if (this._particlesIntersect) {
  58810. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58811. }
  58812. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58813. // add the particle in the SPS
  58814. var currentPos = this._positions.length;
  58815. var currentInd = this._indices.length;
  58816. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58817. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58818. // initialize the particle position
  58819. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58820. this._index += shape.length;
  58821. idx++;
  58822. this.nbParticles++;
  58823. this._shapeCounter++;
  58824. f += size;
  58825. }
  58826. return this;
  58827. };
  58828. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58829. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58830. var index = 0;
  58831. var idx = 0;
  58832. for (var p = 0; p < this.particles.length; p++) {
  58833. this._particle = this.particles[p];
  58834. this._shape = this._particle._model._shape;
  58835. if (this._particle.rotationQuaternion) {
  58836. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58837. }
  58838. else {
  58839. this._yaw = this._particle.rotation.y;
  58840. this._pitch = this._particle.rotation.x;
  58841. this._roll = this._particle.rotation.z;
  58842. this._quaternionRotationYPR();
  58843. }
  58844. this._quaternionToRotationMatrix();
  58845. this._rotMatrix.invertToRef(this._invertMatrix);
  58846. for (var pt = 0; pt < this._shape.length; pt++) {
  58847. idx = index + pt * 3;
  58848. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58849. this._fixedNormal32[idx] = this._normal.x;
  58850. this._fixedNormal32[idx + 1] = this._normal.y;
  58851. this._fixedNormal32[idx + 2] = this._normal.z;
  58852. }
  58853. index = idx + 3;
  58854. }
  58855. };
  58856. //reset copy
  58857. SolidParticleSystem.prototype._resetCopy = function () {
  58858. this._copy.position.x = 0;
  58859. this._copy.position.y = 0;
  58860. this._copy.position.z = 0;
  58861. this._copy.rotation.x = 0;
  58862. this._copy.rotation.y = 0;
  58863. this._copy.rotation.z = 0;
  58864. this._copy.rotationQuaternion = null;
  58865. this._copy.scaling.x = 1.0;
  58866. this._copy.scaling.y = 1.0;
  58867. this._copy.scaling.z = 1.0;
  58868. this._copy.uvs.x = 0;
  58869. this._copy.uvs.y = 0;
  58870. this._copy.uvs.z = 1.0;
  58871. this._copy.uvs.w = 1.0;
  58872. this._copy.color = null;
  58873. this._copy.translateFromPivot = false;
  58874. };
  58875. // _meshBuilder : inserts the shape model in the global SPS mesh
  58876. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58877. var i;
  58878. var u = 0;
  58879. var c = 0;
  58880. var n = 0;
  58881. this._resetCopy();
  58882. if (options && options.positionFunction) { // call to custom positionFunction
  58883. options.positionFunction(this._copy, idx, idxInShape);
  58884. this._mustUnrotateFixedNormals = true;
  58885. }
  58886. if (this._copy.rotationQuaternion) {
  58887. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58888. }
  58889. else {
  58890. this._yaw = this._copy.rotation.y;
  58891. this._pitch = this._copy.rotation.x;
  58892. this._roll = this._copy.rotation.z;
  58893. this._quaternionRotationYPR();
  58894. }
  58895. this._quaternionToRotationMatrix();
  58896. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58897. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58898. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58899. if (this._copy.translateFromPivot) {
  58900. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58901. }
  58902. else {
  58903. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58904. }
  58905. for (i = 0; i < shape.length; i++) {
  58906. this._vertex.x = shape[i].x;
  58907. this._vertex.y = shape[i].y;
  58908. this._vertex.z = shape[i].z;
  58909. if (options && options.vertexFunction) {
  58910. options.vertexFunction(this._copy, this._vertex, i);
  58911. }
  58912. this._vertex.x *= this._copy.scaling.x;
  58913. this._vertex.y *= this._copy.scaling.y;
  58914. this._vertex.z *= this._copy.scaling.z;
  58915. this._vertex.x -= this._scaledPivot.x;
  58916. this._vertex.y -= this._scaledPivot.y;
  58917. this._vertex.z -= this._scaledPivot.z;
  58918. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58919. this._rotated.addInPlace(this._pivotBackTranslation);
  58920. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58921. if (meshUV) {
  58922. 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);
  58923. u += 2;
  58924. }
  58925. if (this._copy.color) {
  58926. this._color = this._copy.color;
  58927. }
  58928. else if (meshCol && meshCol[c] !== undefined) {
  58929. this._color.r = meshCol[c];
  58930. this._color.g = meshCol[c + 1];
  58931. this._color.b = meshCol[c + 2];
  58932. this._color.a = meshCol[c + 3];
  58933. }
  58934. else {
  58935. this._color.r = 1.0;
  58936. this._color.g = 1.0;
  58937. this._color.b = 1.0;
  58938. this._color.a = 1.0;
  58939. }
  58940. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58941. c += 4;
  58942. if (!this.recomputeNormals && meshNor) {
  58943. this._normal.x = meshNor[n];
  58944. this._normal.y = meshNor[n + 1];
  58945. this._normal.z = meshNor[n + 2];
  58946. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58947. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58948. n += 3;
  58949. }
  58950. }
  58951. for (i = 0; i < meshInd.length; i++) {
  58952. var current_ind = p + meshInd[i];
  58953. indices.push(current_ind);
  58954. if (current_ind > 65535) {
  58955. this._needs32Bits = true;
  58956. }
  58957. }
  58958. if (this._pickable) {
  58959. var nbfaces = meshInd.length / 3;
  58960. for (i = 0; i < nbfaces; i++) {
  58961. this.pickedParticles.push({ idx: idx, faceId: i });
  58962. }
  58963. }
  58964. if (this._depthSort) {
  58965. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58966. }
  58967. return this._copy;
  58968. };
  58969. // returns a shape array from positions array
  58970. SolidParticleSystem.prototype._posToShape = function (positions) {
  58971. var shape = [];
  58972. for (var i = 0; i < positions.length; i += 3) {
  58973. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58974. }
  58975. return shape;
  58976. };
  58977. // returns a shapeUV array from a Vector4 uvs
  58978. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58979. var shapeUV = [];
  58980. if (uvs) {
  58981. for (var i = 0; i < uvs.length; i++)
  58982. shapeUV.push(uvs[i]);
  58983. }
  58984. return shapeUV;
  58985. };
  58986. // adds a new particle object in the particles array
  58987. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58988. if (bInfo === void 0) { bInfo = null; }
  58989. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58990. this.particles.push(sp);
  58991. return sp;
  58992. };
  58993. /**
  58994. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58995. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58996. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58997. * @param nb (positive integer) the number of particles to be created from this model
  58998. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58999. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  59000. * @returns the number of shapes in the system
  59001. */
  59002. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  59003. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59004. var meshInd = mesh.getIndices();
  59005. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59006. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59007. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59008. var bbInfo;
  59009. if (this._particlesIntersect) {
  59010. bbInfo = mesh.getBoundingInfo();
  59011. }
  59012. var shape = this._posToShape(meshPos);
  59013. var shapeUV = this._uvsToShapeUV(meshUV);
  59014. var posfunc = options ? options.positionFunction : null;
  59015. var vtxfunc = options ? options.vertexFunction : null;
  59016. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59017. // particles
  59018. var sp;
  59019. var currentCopy;
  59020. var idx = this.nbParticles;
  59021. for (var i = 0; i < nb; i++) {
  59022. var currentPos = this._positions.length;
  59023. var currentInd = this._indices.length;
  59024. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59025. if (this._updatable) {
  59026. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59027. sp.position.copyFrom(currentCopy.position);
  59028. sp.rotation.copyFrom(currentCopy.rotation);
  59029. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59030. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59031. }
  59032. if (currentCopy.color && sp.color) {
  59033. sp.color.copyFrom(currentCopy.color);
  59034. }
  59035. sp.scaling.copyFrom(currentCopy.scaling);
  59036. sp.uvs.copyFrom(currentCopy.uvs);
  59037. }
  59038. this._index += shape.length;
  59039. idx++;
  59040. }
  59041. this.nbParticles += nb;
  59042. this._shapeCounter++;
  59043. return this._shapeCounter - 1;
  59044. };
  59045. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59046. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59047. this._resetCopy();
  59048. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59049. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59050. }
  59051. if (this._copy.rotationQuaternion) {
  59052. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59053. }
  59054. else {
  59055. this._yaw = this._copy.rotation.y;
  59056. this._pitch = this._copy.rotation.x;
  59057. this._roll = this._copy.rotation.z;
  59058. this._quaternionRotationYPR();
  59059. }
  59060. this._quaternionToRotationMatrix();
  59061. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59062. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59063. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59064. if (this._copy.translateFromPivot) {
  59065. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59066. }
  59067. else {
  59068. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59069. }
  59070. this._shape = particle._model._shape;
  59071. for (var pt = 0; pt < this._shape.length; pt++) {
  59072. this._vertex.x = this._shape[pt].x;
  59073. this._vertex.y = this._shape[pt].y;
  59074. this._vertex.z = this._shape[pt].z;
  59075. if (particle._model._vertexFunction) {
  59076. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59077. }
  59078. this._vertex.x *= this._copy.scaling.x;
  59079. this._vertex.y *= this._copy.scaling.y;
  59080. this._vertex.z *= this._copy.scaling.z;
  59081. this._vertex.x -= this._scaledPivot.x;
  59082. this._vertex.y -= this._scaledPivot.y;
  59083. this._vertex.z -= this._scaledPivot.z;
  59084. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59085. this._rotated.addInPlace(this._pivotBackTranslation);
  59086. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59087. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59088. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59089. }
  59090. particle.position.x = 0.0;
  59091. particle.position.y = 0.0;
  59092. particle.position.z = 0.0;
  59093. particle.rotation.x = 0.0;
  59094. particle.rotation.y = 0.0;
  59095. particle.rotation.z = 0.0;
  59096. particle.rotationQuaternion = null;
  59097. particle.scaling.x = 1.0;
  59098. particle.scaling.y = 1.0;
  59099. particle.scaling.z = 1.0;
  59100. particle.uvs.x = 0.0;
  59101. particle.uvs.y = 0.0;
  59102. particle.uvs.z = 1.0;
  59103. particle.uvs.w = 1.0;
  59104. particle.pivot.x = 0.0;
  59105. particle.pivot.y = 0.0;
  59106. particle.pivot.z = 0.0;
  59107. particle.translateFromPivot = false;
  59108. particle.parentId = null;
  59109. };
  59110. /**
  59111. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59112. * @returns the SPS.
  59113. */
  59114. SolidParticleSystem.prototype.rebuildMesh = function () {
  59115. for (var p = 0; p < this.particles.length; p++) {
  59116. this._rebuildParticle(this.particles[p]);
  59117. }
  59118. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59119. return this;
  59120. };
  59121. /**
  59122. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59123. * This method calls `updateParticle()` for each particle of the SPS.
  59124. * For an animated SPS, it is usually called within the render loop.
  59125. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59126. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59127. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59128. * @returns the SPS.
  59129. */
  59130. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59131. if (start === void 0) { start = 0; }
  59132. if (end === void 0) { end = this.nbParticles - 1; }
  59133. if (update === void 0) { update = true; }
  59134. if (!this._updatable) {
  59135. return this;
  59136. }
  59137. // custom beforeUpdate
  59138. this.beforeUpdateParticles(start, end, update);
  59139. this._cam_axisX.x = 1.0;
  59140. this._cam_axisX.y = 0.0;
  59141. this._cam_axisX.z = 0.0;
  59142. this._cam_axisY.x = 0.0;
  59143. this._cam_axisY.y = 1.0;
  59144. this._cam_axisY.z = 0.0;
  59145. this._cam_axisZ.x = 0.0;
  59146. this._cam_axisZ.y = 0.0;
  59147. this._cam_axisZ.z = 1.0;
  59148. // cases when the World Matrix is to be computed first
  59149. if (this.billboard || this._depthSort) {
  59150. this.mesh.computeWorldMatrix(true);
  59151. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59152. }
  59153. // if the particles will always face the camera
  59154. if (this.billboard) {
  59155. // compute the camera position and un-rotate it by the current mesh rotation
  59156. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59157. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59158. this._cam_axisZ.normalize();
  59159. // same for camera up vector extracted from the cam view matrix
  59160. var view = this._camera.getViewMatrix(true);
  59161. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59162. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59163. this._cam_axisY.normalize();
  59164. this._cam_axisX.normalize();
  59165. }
  59166. // if depthSort, compute the camera global position in the mesh local system
  59167. if (this._depthSort) {
  59168. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59169. }
  59170. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59171. var idx = 0; // current position index in the global array positions32
  59172. var index = 0; // position start index in the global array positions32 of the current particle
  59173. var colidx = 0; // current color index in the global array colors32
  59174. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59175. var uvidx = 0; // current uv index in the global array uvs32
  59176. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59177. var pt = 0; // current index in the particle model shape
  59178. if (this.mesh.isFacetDataEnabled) {
  59179. this._computeBoundingBox = true;
  59180. }
  59181. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59182. if (this._computeBoundingBox) {
  59183. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59184. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59185. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59186. }
  59187. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59188. if (this.mesh._boundingInfo) {
  59189. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59190. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59191. }
  59192. }
  59193. }
  59194. // particle loop
  59195. index = this.particles[start]._pos;
  59196. var vpos = (index / 3) | 0;
  59197. colorIndex = vpos * 4;
  59198. uvIndex = vpos * 2;
  59199. for (var p = start; p <= end; p++) {
  59200. this._particle = this.particles[p];
  59201. this._shape = this._particle._model._shape;
  59202. this._shapeUV = this._particle._model._shapeUV;
  59203. // call to custom user function to update the particle properties
  59204. this.updateParticle(this._particle);
  59205. // camera-particle distance for depth sorting
  59206. if (this._depthSort && this._depthSortParticles) {
  59207. var dsp = this.depthSortedParticles[p];
  59208. dsp.ind = this._particle._ind;
  59209. dsp.indicesLength = this._particle._model._indicesLength;
  59210. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59211. }
  59212. // skip the computations for inactive or already invisible particles
  59213. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59214. // increment indexes for the next particle
  59215. pt = this._shape.length;
  59216. index += pt * 3;
  59217. colorIndex += pt * 4;
  59218. uvIndex += pt * 2;
  59219. continue;
  59220. }
  59221. if (this._particle.isVisible) {
  59222. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59223. this._particleHasParent = (this._particle.parentId !== null);
  59224. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59225. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59226. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59227. // particle rotation matrix
  59228. if (this.billboard) {
  59229. this._particle.rotation.x = 0.0;
  59230. this._particle.rotation.y = 0.0;
  59231. }
  59232. if (this._computeParticleRotation || this.billboard) {
  59233. if (this._particle.rotationQuaternion) {
  59234. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59235. }
  59236. else {
  59237. this._yaw = this._particle.rotation.y;
  59238. this._pitch = this._particle.rotation.x;
  59239. this._roll = this._particle.rotation.z;
  59240. this._quaternionRotationYPR();
  59241. }
  59242. this._quaternionToRotationMatrix();
  59243. }
  59244. if (this._particleHasParent) {
  59245. this._parent = this.particles[this._particle.parentId];
  59246. 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];
  59247. 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];
  59248. 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];
  59249. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59250. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59251. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59252. if (this._computeParticleRotation || this.billboard) {
  59253. 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];
  59254. 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];
  59255. 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];
  59256. 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];
  59257. 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];
  59258. 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];
  59259. 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];
  59260. 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];
  59261. 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];
  59262. }
  59263. }
  59264. else {
  59265. this._particle._globalPosition.x = this._particle.position.x;
  59266. this._particle._globalPosition.y = this._particle.position.y;
  59267. this._particle._globalPosition.z = this._particle.position.z;
  59268. if (this._computeParticleRotation || this.billboard) {
  59269. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59270. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59271. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59272. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59273. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59274. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59275. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59276. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59277. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59278. }
  59279. }
  59280. if (this._particle.translateFromPivot) {
  59281. this._pivotBackTranslation.x = 0.0;
  59282. this._pivotBackTranslation.y = 0.0;
  59283. this._pivotBackTranslation.z = 0.0;
  59284. }
  59285. else {
  59286. this._pivotBackTranslation.x = this._scaledPivot.x;
  59287. this._pivotBackTranslation.y = this._scaledPivot.y;
  59288. this._pivotBackTranslation.z = this._scaledPivot.z;
  59289. }
  59290. // particle vertex loop
  59291. for (pt = 0; pt < this._shape.length; pt++) {
  59292. idx = index + pt * 3;
  59293. colidx = colorIndex + pt * 4;
  59294. uvidx = uvIndex + pt * 2;
  59295. this._vertex.x = this._shape[pt].x;
  59296. this._vertex.y = this._shape[pt].y;
  59297. this._vertex.z = this._shape[pt].z;
  59298. if (this._computeParticleVertex) {
  59299. this.updateParticleVertex(this._particle, this._vertex, pt);
  59300. }
  59301. // positions
  59302. this._vertex.x *= this._particle.scaling.x;
  59303. this._vertex.y *= this._particle.scaling.y;
  59304. this._vertex.z *= this._particle.scaling.z;
  59305. this._vertex.x -= this._scaledPivot.x;
  59306. this._vertex.y -= this._scaledPivot.y;
  59307. this._vertex.z -= this._scaledPivot.z;
  59308. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59309. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59310. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59311. this._rotated.x += this._pivotBackTranslation.x;
  59312. this._rotated.y += this._pivotBackTranslation.y;
  59313. this._rotated.z += this._pivotBackTranslation.z;
  59314. 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;
  59315. 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;
  59316. 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;
  59317. if (this._computeBoundingBox) {
  59318. if (this._positions32[idx] < this._minimum.x) {
  59319. this._minimum.x = this._positions32[idx];
  59320. }
  59321. if (this._positions32[idx] > this._maximum.x) {
  59322. this._maximum.x = this._positions32[idx];
  59323. }
  59324. if (this._positions32[idx + 1] < this._minimum.y) {
  59325. this._minimum.y = this._positions32[idx + 1];
  59326. }
  59327. if (this._positions32[idx + 1] > this._maximum.y) {
  59328. this._maximum.y = this._positions32[idx + 1];
  59329. }
  59330. if (this._positions32[idx + 2] < this._minimum.z) {
  59331. this._minimum.z = this._positions32[idx + 2];
  59332. }
  59333. if (this._positions32[idx + 2] > this._maximum.z) {
  59334. this._maximum.z = this._positions32[idx + 2];
  59335. }
  59336. }
  59337. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59338. if (!this._computeParticleVertex) {
  59339. this._normal.x = this._fixedNormal32[idx];
  59340. this._normal.y = this._fixedNormal32[idx + 1];
  59341. this._normal.z = this._fixedNormal32[idx + 2];
  59342. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59343. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59344. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59345. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59346. 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;
  59347. 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;
  59348. }
  59349. if (this._computeParticleColor && this._particle.color) {
  59350. this._colors32[colidx] = this._particle.color.r;
  59351. this._colors32[colidx + 1] = this._particle.color.g;
  59352. this._colors32[colidx + 2] = this._particle.color.b;
  59353. this._colors32[colidx + 3] = this._particle.color.a;
  59354. }
  59355. if (this._computeParticleTexture) {
  59356. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59357. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59358. }
  59359. }
  59360. }
  59361. // particle just set invisible : scaled to zero and positioned at the origin
  59362. else {
  59363. this._particle._stillInvisible = true; // mark the particle as invisible
  59364. for (pt = 0; pt < this._shape.length; pt++) {
  59365. idx = index + pt * 3;
  59366. colidx = colorIndex + pt * 4;
  59367. uvidx = uvIndex + pt * 2;
  59368. this._positions32[idx] = 0.0;
  59369. this._positions32[idx + 1] = 0.0;
  59370. this._positions32[idx + 2] = 0.0;
  59371. this._normals32[idx] = 0.0;
  59372. this._normals32[idx + 1] = 0.0;
  59373. this._normals32[idx + 2] = 0.0;
  59374. if (this._computeParticleColor && this._particle.color) {
  59375. this._colors32[colidx] = this._particle.color.r;
  59376. this._colors32[colidx + 1] = this._particle.color.g;
  59377. this._colors32[colidx + 2] = this._particle.color.b;
  59378. this._colors32[colidx + 3] = this._particle.color.a;
  59379. }
  59380. if (this._computeParticleTexture) {
  59381. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59382. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59383. }
  59384. }
  59385. }
  59386. // if the particle intersections must be computed : update the bbInfo
  59387. if (this._particlesIntersect) {
  59388. var bInfo = this._particle._boundingInfo;
  59389. var bBox = bInfo.boundingBox;
  59390. var bSphere = bInfo.boundingSphere;
  59391. if (!this._bSphereOnly) {
  59392. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59393. for (var b = 0; b < bBox.vectors.length; b++) {
  59394. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59395. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59396. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59397. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59398. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59399. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59400. 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;
  59401. 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;
  59402. 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;
  59403. }
  59404. bBox._update(this.mesh._worldMatrix);
  59405. }
  59406. // place and scale the particle bouding sphere in the SPS local system, then update it
  59407. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59408. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59409. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59410. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59411. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59412. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59413. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59414. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59415. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59416. 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));
  59417. bSphere._update(this.mesh._worldMatrix);
  59418. }
  59419. // increment indexes for the next particle
  59420. index = idx + 3;
  59421. colorIndex = colidx + 4;
  59422. uvIndex = uvidx + 2;
  59423. }
  59424. // if the VBO must be updated
  59425. if (update) {
  59426. if (this._computeParticleColor) {
  59427. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59428. }
  59429. if (this._computeParticleTexture) {
  59430. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59431. }
  59432. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59433. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59434. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59435. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59436. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59437. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59438. for (var i = 0; i < this._normals32.length; i++) {
  59439. this._fixedNormal32[i] = this._normals32[i];
  59440. }
  59441. }
  59442. if (!this.mesh.areNormalsFrozen) {
  59443. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59444. }
  59445. }
  59446. if (this._depthSort && this._depthSortParticles) {
  59447. this.depthSortedParticles.sort(this._depthSortFunction);
  59448. var dspl = this.depthSortedParticles.length;
  59449. var sorted = 0;
  59450. var lind = 0;
  59451. var sind = 0;
  59452. var sid = 0;
  59453. for (sorted = 0; sorted < dspl; sorted++) {
  59454. lind = this.depthSortedParticles[sorted].indicesLength;
  59455. sind = this.depthSortedParticles[sorted].ind;
  59456. for (var i = 0; i < lind; i++) {
  59457. this._indices32[sid] = this._indices[sind + i];
  59458. sid++;
  59459. }
  59460. }
  59461. this.mesh.updateIndices(this._indices32);
  59462. }
  59463. }
  59464. if (this._computeBoundingBox) {
  59465. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59466. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59467. }
  59468. this.afterUpdateParticles(start, end, update);
  59469. return this;
  59470. };
  59471. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59472. this._halfroll = this._roll * 0.5;
  59473. this._halfpitch = this._pitch * 0.5;
  59474. this._halfyaw = this._yaw * 0.5;
  59475. this._sinRoll = Math.sin(this._halfroll);
  59476. this._cosRoll = Math.cos(this._halfroll);
  59477. this._sinPitch = Math.sin(this._halfpitch);
  59478. this._cosPitch = Math.cos(this._halfpitch);
  59479. this._sinYaw = Math.sin(this._halfyaw);
  59480. this._cosYaw = Math.cos(this._halfyaw);
  59481. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59482. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59483. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59484. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59485. };
  59486. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59487. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59488. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59489. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59490. this._rotMatrix.m[3] = 0;
  59491. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59492. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59493. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59494. this._rotMatrix.m[7] = 0;
  59495. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59496. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59497. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59498. this._rotMatrix.m[11] = 0;
  59499. this._rotMatrix.m[12] = 0;
  59500. this._rotMatrix.m[13] = 0;
  59501. this._rotMatrix.m[14] = 0;
  59502. this._rotMatrix.m[15] = 1.0;
  59503. };
  59504. /**
  59505. * Disposes the SPS.
  59506. */
  59507. SolidParticleSystem.prototype.dispose = function () {
  59508. this.mesh.dispose();
  59509. this.vars = null;
  59510. // drop references to internal big arrays for the GC
  59511. this._positions = null;
  59512. this._indices = null;
  59513. this._normals = null;
  59514. this._uvs = null;
  59515. this._colors = null;
  59516. this._indices32 = null;
  59517. this._positions32 = null;
  59518. this._normals32 = null;
  59519. this._fixedNormal32 = null;
  59520. this._uvs32 = null;
  59521. this._colors32 = null;
  59522. this.pickedParticles = null;
  59523. };
  59524. /**
  59525. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59526. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59527. * @returns the SPS.
  59528. */
  59529. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59530. if (!this._isVisibilityBoxLocked) {
  59531. this.mesh.refreshBoundingInfo();
  59532. }
  59533. return this;
  59534. };
  59535. /**
  59536. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59537. * @param size the size (float) of the visibility box
  59538. * note : this doesn't lock the SPS mesh bounding box.
  59539. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59540. */
  59541. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59542. var vis = size / 2;
  59543. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59544. };
  59545. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59546. /**
  59547. * Gets whether the SPS as always visible or not
  59548. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59549. */
  59550. get: function () {
  59551. return this._alwaysVisible;
  59552. },
  59553. /**
  59554. * Sets the SPS as always visible or not
  59555. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59556. */
  59557. set: function (val) {
  59558. this._alwaysVisible = val;
  59559. this.mesh.alwaysSelectAsActiveMesh = val;
  59560. },
  59561. enumerable: true,
  59562. configurable: true
  59563. });
  59564. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59565. /**
  59566. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59567. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59568. */
  59569. get: function () {
  59570. return this._isVisibilityBoxLocked;
  59571. },
  59572. /**
  59573. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59574. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59575. */
  59576. set: function (val) {
  59577. this._isVisibilityBoxLocked = val;
  59578. var boundingInfo = this.mesh.getBoundingInfo();
  59579. boundingInfo.isLocked = val;
  59580. },
  59581. enumerable: true,
  59582. configurable: true
  59583. });
  59584. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59585. /**
  59586. * Gets if `setParticles()` computes the particle rotations or not.
  59587. * Default value : true. The SPS is faster when it's set to false.
  59588. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59589. */
  59590. get: function () {
  59591. return this._computeParticleRotation;
  59592. },
  59593. /**
  59594. * Tells to `setParticles()` to compute the particle rotations or not.
  59595. * Default value : true. The SPS is faster when it's set to false.
  59596. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59597. */
  59598. set: function (val) {
  59599. this._computeParticleRotation = val;
  59600. },
  59601. enumerable: true,
  59602. configurable: true
  59603. });
  59604. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59605. /**
  59606. * Gets if `setParticles()` computes the particle colors or not.
  59607. * Default value : true. The SPS is faster when it's set to false.
  59608. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59609. */
  59610. get: function () {
  59611. return this._computeParticleColor;
  59612. },
  59613. /**
  59614. * Tells to `setParticles()` to compute the particle colors or not.
  59615. * Default value : true. The SPS is faster when it's set to false.
  59616. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59617. */
  59618. set: function (val) {
  59619. this._computeParticleColor = val;
  59620. },
  59621. enumerable: true,
  59622. configurable: true
  59623. });
  59624. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59625. /**
  59626. * Gets if `setParticles()` computes the particle textures or not.
  59627. * Default value : true. The SPS is faster when it's set to false.
  59628. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59629. */
  59630. get: function () {
  59631. return this._computeParticleTexture;
  59632. },
  59633. set: function (val) {
  59634. this._computeParticleTexture = val;
  59635. },
  59636. enumerable: true,
  59637. configurable: true
  59638. });
  59639. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59640. /**
  59641. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59642. * Default value : false. The SPS is faster when it's set to false.
  59643. * Note : the particle custom vertex positions aren't stored values.
  59644. */
  59645. get: function () {
  59646. return this._computeParticleVertex;
  59647. },
  59648. /**
  59649. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59650. * Default value : false. The SPS is faster when it's set to false.
  59651. * Note : the particle custom vertex positions aren't stored values.
  59652. */
  59653. set: function (val) {
  59654. this._computeParticleVertex = val;
  59655. },
  59656. enumerable: true,
  59657. configurable: true
  59658. });
  59659. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59660. /**
  59661. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59662. */
  59663. get: function () {
  59664. return this._computeBoundingBox;
  59665. },
  59666. /**
  59667. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59668. */
  59669. set: function (val) {
  59670. this._computeBoundingBox = val;
  59671. },
  59672. enumerable: true,
  59673. configurable: true
  59674. });
  59675. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59676. /**
  59677. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59678. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59679. * Default : `true`
  59680. */
  59681. get: function () {
  59682. return this._depthSortParticles;
  59683. },
  59684. /**
  59685. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59686. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59687. * Default : `true`
  59688. */
  59689. set: function (val) {
  59690. this._depthSortParticles = val;
  59691. },
  59692. enumerable: true,
  59693. configurable: true
  59694. });
  59695. // =======================================================================
  59696. // Particle behavior logic
  59697. // these following methods may be overwritten by the user to fit his needs
  59698. /**
  59699. * This function does nothing. It may be overwritten to set all the particle first values.
  59700. * The SPS doesn't call this function, you may have to call it by your own.
  59701. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59702. */
  59703. SolidParticleSystem.prototype.initParticles = function () {
  59704. };
  59705. /**
  59706. * This function does nothing. It may be overwritten to recycle a particle.
  59707. * The SPS doesn't call this function, you may have to call it by your own.
  59708. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59709. * @param particle The particle to recycle
  59710. * @returns the recycled particle
  59711. */
  59712. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59713. return particle;
  59714. };
  59715. /**
  59716. * Updates a particle : this function should be overwritten by the user.
  59717. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59718. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59719. * @example : just set a particle position or velocity and recycle conditions
  59720. * @param particle The particle to update
  59721. * @returns the updated particle
  59722. */
  59723. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59724. return particle;
  59725. };
  59726. /**
  59727. * Updates a vertex of a particle : it can be overwritten by the user.
  59728. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59729. * @param particle the current particle
  59730. * @param vertex the current index of the current particle
  59731. * @param pt the index of the current vertex in the particle shape
  59732. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59733. * @example : just set a vertex particle position
  59734. * @returns the updated vertex
  59735. */
  59736. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59737. return vertex;
  59738. };
  59739. /**
  59740. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59741. * This does nothing and may be overwritten by the user.
  59742. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59743. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59744. * @param update the boolean update value actually passed to setParticles()
  59745. */
  59746. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59747. };
  59748. /**
  59749. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59750. * This will be passed three parameters.
  59751. * This does nothing and may be overwritten by the user.
  59752. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59753. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59754. * @param update the boolean update value actually passed to setParticles()
  59755. */
  59756. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59757. };
  59758. return SolidParticleSystem;
  59759. }());
  59760. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59761. })(BABYLON || (BABYLON = {}));
  59762. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59763. var BABYLON;
  59764. (function (BABYLON) {
  59765. var ShaderMaterial = /** @class */ (function (_super) {
  59766. __extends(ShaderMaterial, _super);
  59767. function ShaderMaterial(name, scene, shaderPath, options) {
  59768. var _this = _super.call(this, name, scene) || this;
  59769. _this._textures = {};
  59770. _this._textureArrays = {};
  59771. _this._floats = {};
  59772. _this._ints = {};
  59773. _this._floatsArrays = {};
  59774. _this._colors3 = {};
  59775. _this._colors3Arrays = {};
  59776. _this._colors4 = {};
  59777. _this._vectors2 = {};
  59778. _this._vectors3 = {};
  59779. _this._vectors4 = {};
  59780. _this._matrices = {};
  59781. _this._matrices3x3 = {};
  59782. _this._matrices2x2 = {};
  59783. _this._vectors2Arrays = {};
  59784. _this._vectors3Arrays = {};
  59785. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59786. _this._shaderPath = shaderPath;
  59787. options.needAlphaBlending = options.needAlphaBlending || false;
  59788. options.needAlphaTesting = options.needAlphaTesting || false;
  59789. options.attributes = options.attributes || ["position", "normal", "uv"];
  59790. options.uniforms = options.uniforms || ["worldViewProjection"];
  59791. options.uniformBuffers = options.uniformBuffers || [];
  59792. options.samplers = options.samplers || [];
  59793. options.defines = options.defines || [];
  59794. _this._options = options;
  59795. return _this;
  59796. }
  59797. ShaderMaterial.prototype.getClassName = function () {
  59798. return "ShaderMaterial";
  59799. };
  59800. ShaderMaterial.prototype.needAlphaBlending = function () {
  59801. return this._options.needAlphaBlending;
  59802. };
  59803. ShaderMaterial.prototype.needAlphaTesting = function () {
  59804. return this._options.needAlphaTesting;
  59805. };
  59806. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59807. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59808. this._options.uniforms.push(uniformName);
  59809. }
  59810. };
  59811. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59812. if (this._options.samplers.indexOf(name) === -1) {
  59813. this._options.samplers.push(name);
  59814. }
  59815. this._textures[name] = texture;
  59816. return this;
  59817. };
  59818. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59819. if (this._options.samplers.indexOf(name) === -1) {
  59820. this._options.samplers.push(name);
  59821. }
  59822. this._checkUniform(name);
  59823. this._textureArrays[name] = textures;
  59824. return this;
  59825. };
  59826. ShaderMaterial.prototype.setFloat = function (name, value) {
  59827. this._checkUniform(name);
  59828. this._floats[name] = value;
  59829. return this;
  59830. };
  59831. ShaderMaterial.prototype.setInt = function (name, value) {
  59832. this._checkUniform(name);
  59833. this._ints[name] = value;
  59834. return this;
  59835. };
  59836. ShaderMaterial.prototype.setFloats = function (name, value) {
  59837. this._checkUniform(name);
  59838. this._floatsArrays[name] = value;
  59839. return this;
  59840. };
  59841. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59842. this._checkUniform(name);
  59843. this._colors3[name] = value;
  59844. return this;
  59845. };
  59846. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59847. this._checkUniform(name);
  59848. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59849. color.toArray(arr, arr.length);
  59850. return arr;
  59851. }, []);
  59852. return this;
  59853. };
  59854. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59855. this._checkUniform(name);
  59856. this._colors4[name] = value;
  59857. return this;
  59858. };
  59859. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59860. this._checkUniform(name);
  59861. this._vectors2[name] = value;
  59862. return this;
  59863. };
  59864. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59865. this._checkUniform(name);
  59866. this._vectors3[name] = value;
  59867. return this;
  59868. };
  59869. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59870. this._checkUniform(name);
  59871. this._vectors4[name] = value;
  59872. return this;
  59873. };
  59874. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59875. this._checkUniform(name);
  59876. this._matrices[name] = value;
  59877. return this;
  59878. };
  59879. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59880. this._checkUniform(name);
  59881. this._matrices3x3[name] = value;
  59882. return this;
  59883. };
  59884. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59885. this._checkUniform(name);
  59886. this._matrices2x2[name] = value;
  59887. return this;
  59888. };
  59889. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59890. this._checkUniform(name);
  59891. this._vectors2Arrays[name] = value;
  59892. return this;
  59893. };
  59894. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59895. this._checkUniform(name);
  59896. this._vectors3Arrays[name] = value;
  59897. return this;
  59898. };
  59899. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59900. if (!mesh) {
  59901. return true;
  59902. }
  59903. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59904. return false;
  59905. }
  59906. return false;
  59907. };
  59908. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59909. var scene = this.getScene();
  59910. var engine = scene.getEngine();
  59911. if (!this.checkReadyOnEveryCall) {
  59912. if (this._renderId === scene.getRenderId()) {
  59913. if (this._checkCache(scene, mesh, useInstances)) {
  59914. return true;
  59915. }
  59916. }
  59917. }
  59918. // Instances
  59919. var defines = [];
  59920. var attribs = [];
  59921. var fallbacks = new BABYLON.EffectFallbacks();
  59922. if (useInstances) {
  59923. defines.push("#define INSTANCES");
  59924. }
  59925. for (var index = 0; index < this._options.defines.length; index++) {
  59926. defines.push(this._options.defines[index]);
  59927. }
  59928. for (var index = 0; index < this._options.attributes.length; index++) {
  59929. attribs.push(this._options.attributes[index]);
  59930. }
  59931. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59932. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59933. defines.push("#define VERTEXCOLOR");
  59934. }
  59935. // Bones
  59936. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59937. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59938. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59939. if (mesh.numBoneInfluencers > 4) {
  59940. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59941. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59942. }
  59943. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59944. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59945. fallbacks.addCPUSkinningFallback(0, mesh);
  59946. if (this._options.uniforms.indexOf("mBones") === -1) {
  59947. this._options.uniforms.push("mBones");
  59948. }
  59949. }
  59950. else {
  59951. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59952. }
  59953. // Textures
  59954. for (var name in this._textures) {
  59955. if (!this._textures[name].isReady()) {
  59956. return false;
  59957. }
  59958. }
  59959. // Alpha test
  59960. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59961. defines.push("#define ALPHATEST");
  59962. }
  59963. var previousEffect = this._effect;
  59964. var join = defines.join("\n");
  59965. this._effect = engine.createEffect(this._shaderPath, {
  59966. attributes: attribs,
  59967. uniformsNames: this._options.uniforms,
  59968. uniformBuffersNames: this._options.uniformBuffers,
  59969. samplers: this._options.samplers,
  59970. defines: join,
  59971. fallbacks: fallbacks,
  59972. onCompiled: this.onCompiled,
  59973. onError: this.onError
  59974. }, engine);
  59975. if (!this._effect.isReady()) {
  59976. return false;
  59977. }
  59978. if (previousEffect !== this._effect) {
  59979. scene.resetCachedMaterial();
  59980. }
  59981. this._renderId = scene.getRenderId();
  59982. return true;
  59983. };
  59984. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59985. var scene = this.getScene();
  59986. if (!this._effect) {
  59987. return;
  59988. }
  59989. if (this._options.uniforms.indexOf("world") !== -1) {
  59990. this._effect.setMatrix("world", world);
  59991. }
  59992. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59993. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59994. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59995. }
  59996. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59997. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59998. }
  59999. };
  60000. ShaderMaterial.prototype.bind = function (world, mesh) {
  60001. // Std values
  60002. this.bindOnlyWorldMatrix(world);
  60003. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60004. if (this._options.uniforms.indexOf("view") !== -1) {
  60005. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60006. }
  60007. if (this._options.uniforms.indexOf("projection") !== -1) {
  60008. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60009. }
  60010. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60011. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60012. }
  60013. // Bones
  60014. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60015. var name;
  60016. // Texture
  60017. for (name in this._textures) {
  60018. this._effect.setTexture(name, this._textures[name]);
  60019. }
  60020. // Texture arrays
  60021. for (name in this._textureArrays) {
  60022. this._effect.setTextureArray(name, this._textureArrays[name]);
  60023. }
  60024. // Int
  60025. for (name in this._ints) {
  60026. this._effect.setInt(name, this._ints[name]);
  60027. }
  60028. // Float
  60029. for (name in this._floats) {
  60030. this._effect.setFloat(name, this._floats[name]);
  60031. }
  60032. // Floats
  60033. for (name in this._floatsArrays) {
  60034. this._effect.setArray(name, this._floatsArrays[name]);
  60035. }
  60036. // Color3
  60037. for (name in this._colors3) {
  60038. this._effect.setColor3(name, this._colors3[name]);
  60039. }
  60040. for (name in this._colors3Arrays) {
  60041. this._effect.setArray3(name, this._colors3Arrays[name]);
  60042. }
  60043. // Color4
  60044. for (name in this._colors4) {
  60045. var color = this._colors4[name];
  60046. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60047. }
  60048. // Vector2
  60049. for (name in this._vectors2) {
  60050. this._effect.setVector2(name, this._vectors2[name]);
  60051. }
  60052. // Vector3
  60053. for (name in this._vectors3) {
  60054. this._effect.setVector3(name, this._vectors3[name]);
  60055. }
  60056. // Vector4
  60057. for (name in this._vectors4) {
  60058. this._effect.setVector4(name, this._vectors4[name]);
  60059. }
  60060. // Matrix
  60061. for (name in this._matrices) {
  60062. this._effect.setMatrix(name, this._matrices[name]);
  60063. }
  60064. // Matrix 3x3
  60065. for (name in this._matrices3x3) {
  60066. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60067. }
  60068. // Matrix 2x2
  60069. for (name in this._matrices2x2) {
  60070. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60071. }
  60072. // Vector2Array
  60073. for (name in this._vectors2Arrays) {
  60074. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60075. }
  60076. // Vector3Array
  60077. for (name in this._vectors3Arrays) {
  60078. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60079. }
  60080. }
  60081. this._afterBind(mesh);
  60082. };
  60083. ShaderMaterial.prototype.getActiveTextures = function () {
  60084. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60085. for (var name in this._textures) {
  60086. activeTextures.push(this._textures[name]);
  60087. }
  60088. for (var name in this._textureArrays) {
  60089. var array = this._textureArrays[name];
  60090. for (var index = 0; index < array.length; index++) {
  60091. activeTextures.push(array[index]);
  60092. }
  60093. }
  60094. return activeTextures;
  60095. };
  60096. ShaderMaterial.prototype.hasTexture = function (texture) {
  60097. if (_super.prototype.hasTexture.call(this, texture)) {
  60098. return true;
  60099. }
  60100. for (var name in this._textures) {
  60101. if (this._textures[name] === texture) {
  60102. return true;
  60103. }
  60104. }
  60105. for (var name in this._textureArrays) {
  60106. var array = this._textureArrays[name];
  60107. for (var index = 0; index < array.length; index++) {
  60108. if (array[index] === texture) {
  60109. return true;
  60110. }
  60111. }
  60112. }
  60113. return false;
  60114. };
  60115. ShaderMaterial.prototype.clone = function (name) {
  60116. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60117. return newShaderMaterial;
  60118. };
  60119. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60120. if (forceDisposeTextures) {
  60121. var name;
  60122. for (name in this._textures) {
  60123. this._textures[name].dispose();
  60124. }
  60125. for (name in this._textureArrays) {
  60126. var array = this._textureArrays[name];
  60127. for (var index = 0; index < array.length; index++) {
  60128. array[index].dispose();
  60129. }
  60130. }
  60131. }
  60132. this._textures = {};
  60133. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60134. };
  60135. ShaderMaterial.prototype.serialize = function () {
  60136. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60137. serializationObject.customType = "BABYLON.ShaderMaterial";
  60138. serializationObject.options = this._options;
  60139. serializationObject.shaderPath = this._shaderPath;
  60140. var name;
  60141. // Texture
  60142. serializationObject.textures = {};
  60143. for (name in this._textures) {
  60144. serializationObject.textures[name] = this._textures[name].serialize();
  60145. }
  60146. // Texture arrays
  60147. serializationObject.textureArrays = {};
  60148. for (name in this._textureArrays) {
  60149. serializationObject.textureArrays[name] = [];
  60150. var array = this._textureArrays[name];
  60151. for (var index = 0; index < array.length; index++) {
  60152. serializationObject.textureArrays[name].push(array[index].serialize());
  60153. }
  60154. }
  60155. // Float
  60156. serializationObject.floats = {};
  60157. for (name in this._floats) {
  60158. serializationObject.floats[name] = this._floats[name];
  60159. }
  60160. // Float s
  60161. serializationObject.FloatArrays = {};
  60162. for (name in this._floatsArrays) {
  60163. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60164. }
  60165. // Color3
  60166. serializationObject.colors3 = {};
  60167. for (name in this._colors3) {
  60168. serializationObject.colors3[name] = this._colors3[name].asArray();
  60169. }
  60170. // Color3 array
  60171. serializationObject.colors3Arrays = {};
  60172. for (name in this._colors3Arrays) {
  60173. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60174. }
  60175. // Color4
  60176. serializationObject.colors4 = {};
  60177. for (name in this._colors4) {
  60178. serializationObject.colors4[name] = this._colors4[name].asArray();
  60179. }
  60180. // Vector2
  60181. serializationObject.vectors2 = {};
  60182. for (name in this._vectors2) {
  60183. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60184. }
  60185. // Vector3
  60186. serializationObject.vectors3 = {};
  60187. for (name in this._vectors3) {
  60188. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60189. }
  60190. // Vector4
  60191. serializationObject.vectors4 = {};
  60192. for (name in this._vectors4) {
  60193. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60194. }
  60195. // Matrix
  60196. serializationObject.matrices = {};
  60197. for (name in this._matrices) {
  60198. serializationObject.matrices[name] = this._matrices[name].asArray();
  60199. }
  60200. // Matrix 3x3
  60201. serializationObject.matrices3x3 = {};
  60202. for (name in this._matrices3x3) {
  60203. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60204. }
  60205. // Matrix 2x2
  60206. serializationObject.matrices2x2 = {};
  60207. for (name in this._matrices2x2) {
  60208. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60209. }
  60210. // Vector2Array
  60211. serializationObject.vectors2Arrays = {};
  60212. for (name in this._vectors2Arrays) {
  60213. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60214. }
  60215. // Vector3Array
  60216. serializationObject.vectors3Arrays = {};
  60217. for (name in this._vectors3Arrays) {
  60218. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60219. }
  60220. return serializationObject;
  60221. };
  60222. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60223. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60224. var name;
  60225. // Texture
  60226. for (name in source.textures) {
  60227. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60228. }
  60229. // Texture arrays
  60230. for (name in source.textureArrays) {
  60231. var array = source.textureArrays[name];
  60232. var textureArray = new Array();
  60233. for (var index = 0; index < array.length; index++) {
  60234. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60235. }
  60236. material.setTextureArray(name, textureArray);
  60237. }
  60238. // Float
  60239. for (name in source.floats) {
  60240. material.setFloat(name, source.floats[name]);
  60241. }
  60242. // Float s
  60243. for (name in source.floatsArrays) {
  60244. material.setFloats(name, source.floatsArrays[name]);
  60245. }
  60246. // Color3
  60247. for (name in source.colors3) {
  60248. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60249. }
  60250. // Color3 arrays
  60251. for (name in source.colors3Arrays) {
  60252. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60253. if (i % 3 === 0) {
  60254. arr.push([num]);
  60255. }
  60256. else {
  60257. arr[arr.length - 1].push(num);
  60258. }
  60259. return arr;
  60260. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60261. material.setColor3Array(name, colors);
  60262. }
  60263. // Color4
  60264. for (name in source.colors4) {
  60265. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60266. }
  60267. // Vector2
  60268. for (name in source.vectors2) {
  60269. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60270. }
  60271. // Vector3
  60272. for (name in source.vectors3) {
  60273. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60274. }
  60275. // Vector4
  60276. for (name in source.vectors4) {
  60277. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60278. }
  60279. // Matrix
  60280. for (name in source.matrices) {
  60281. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60282. }
  60283. // Matrix 3x3
  60284. for (name in source.matrices3x3) {
  60285. material.setMatrix3x3(name, source.matrices3x3[name]);
  60286. }
  60287. // Matrix 2x2
  60288. for (name in source.matrices2x2) {
  60289. material.setMatrix2x2(name, source.matrices2x2[name]);
  60290. }
  60291. // Vector2Array
  60292. for (name in source.vectors2Arrays) {
  60293. material.setArray2(name, source.vectors2Arrays[name]);
  60294. }
  60295. // Vector3Array
  60296. for (name in source.vectors3Arrays) {
  60297. material.setArray3(name, source.vectors3Arrays[name]);
  60298. }
  60299. return material;
  60300. };
  60301. return ShaderMaterial;
  60302. }(BABYLON.Material));
  60303. BABYLON.ShaderMaterial = ShaderMaterial;
  60304. })(BABYLON || (BABYLON = {}));
  60305. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60306. var BABYLON;
  60307. (function (BABYLON) {
  60308. var GroundMesh = /** @class */ (function (_super) {
  60309. __extends(GroundMesh, _super);
  60310. function GroundMesh(name, scene) {
  60311. var _this = _super.call(this, name, scene) || this;
  60312. _this.generateOctree = false;
  60313. return _this;
  60314. }
  60315. GroundMesh.prototype.getClassName = function () {
  60316. return "GroundMesh";
  60317. };
  60318. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60319. get: function () {
  60320. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60321. },
  60322. enumerable: true,
  60323. configurable: true
  60324. });
  60325. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60326. get: function () {
  60327. return this._subdivisionsX;
  60328. },
  60329. enumerable: true,
  60330. configurable: true
  60331. });
  60332. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60333. get: function () {
  60334. return this._subdivisionsY;
  60335. },
  60336. enumerable: true,
  60337. configurable: true
  60338. });
  60339. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60340. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60341. this._subdivisionsX = chunksCount;
  60342. this._subdivisionsY = chunksCount;
  60343. this.subdivide(chunksCount);
  60344. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60345. };
  60346. /**
  60347. * Returns a height (y) value in the Worl system :
  60348. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60349. * Returns the ground y position if (x, z) are outside the ground surface.
  60350. */
  60351. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60352. var world = this.getWorldMatrix();
  60353. var invMat = BABYLON.Tmp.Matrix[5];
  60354. world.invertToRef(invMat);
  60355. var tmpVect = BABYLON.Tmp.Vector3[8];
  60356. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60357. x = tmpVect.x;
  60358. z = tmpVect.z;
  60359. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60360. return this.position.y;
  60361. }
  60362. if (!this._heightQuads || this._heightQuads.length == 0) {
  60363. this._initHeightQuads();
  60364. this._computeHeightQuads();
  60365. }
  60366. var facet = this._getFacetAt(x, z);
  60367. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60368. // return y in the World system
  60369. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60370. return tmpVect.y;
  60371. };
  60372. /**
  60373. * Returns a normalized vector (Vector3) orthogonal to the ground
  60374. * at the ground coordinates (x, z) expressed in the World system.
  60375. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60376. */
  60377. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60378. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60379. this.getNormalAtCoordinatesToRef(x, z, normal);
  60380. return normal;
  60381. };
  60382. /**
  60383. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60384. * at the ground coordinates (x, z) expressed in the World system.
  60385. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60386. * Returns the GroundMesh.
  60387. */
  60388. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60389. var world = this.getWorldMatrix();
  60390. var tmpMat = BABYLON.Tmp.Matrix[5];
  60391. world.invertToRef(tmpMat);
  60392. var tmpVect = BABYLON.Tmp.Vector3[8];
  60393. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60394. x = tmpVect.x;
  60395. z = tmpVect.z;
  60396. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60397. return this;
  60398. }
  60399. if (!this._heightQuads || this._heightQuads.length == 0) {
  60400. this._initHeightQuads();
  60401. this._computeHeightQuads();
  60402. }
  60403. var facet = this._getFacetAt(x, z);
  60404. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60405. return this;
  60406. };
  60407. /**
  60408. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60409. * if the ground has been updated.
  60410. * This can be used in the render loop.
  60411. * Returns the GroundMesh.
  60412. */
  60413. GroundMesh.prototype.updateCoordinateHeights = function () {
  60414. if (!this._heightQuads || this._heightQuads.length == 0) {
  60415. this._initHeightQuads();
  60416. }
  60417. this._computeHeightQuads();
  60418. return this;
  60419. };
  60420. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60421. GroundMesh.prototype._getFacetAt = function (x, z) {
  60422. // retrieve col and row from x, z coordinates in the ground local system
  60423. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60424. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60425. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60426. var facet;
  60427. if (z < quad.slope.x * x + quad.slope.y) {
  60428. facet = quad.facet1;
  60429. }
  60430. else {
  60431. facet = quad.facet2;
  60432. }
  60433. return facet;
  60434. };
  60435. // Creates and populates the heightMap array with "facet" elements :
  60436. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60437. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60438. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60439. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60440. // Returns the GroundMesh.
  60441. GroundMesh.prototype._initHeightQuads = function () {
  60442. var subdivisionsX = this._subdivisionsX;
  60443. var subdivisionsY = this._subdivisionsY;
  60444. this._heightQuads = new Array();
  60445. for (var row = 0; row < subdivisionsY; row++) {
  60446. for (var col = 0; col < subdivisionsX; col++) {
  60447. 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) };
  60448. this._heightQuads[row * subdivisionsX + col] = quad;
  60449. }
  60450. }
  60451. return this;
  60452. };
  60453. // Compute each quad element values and update the the heightMap array :
  60454. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60455. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60456. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60457. // Returns the GroundMesh.
  60458. GroundMesh.prototype._computeHeightQuads = function () {
  60459. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60460. if (!positions) {
  60461. return this;
  60462. }
  60463. var v1 = BABYLON.Tmp.Vector3[3];
  60464. var v2 = BABYLON.Tmp.Vector3[2];
  60465. var v3 = BABYLON.Tmp.Vector3[1];
  60466. var v4 = BABYLON.Tmp.Vector3[0];
  60467. var v1v2 = BABYLON.Tmp.Vector3[4];
  60468. var v1v3 = BABYLON.Tmp.Vector3[5];
  60469. var v1v4 = BABYLON.Tmp.Vector3[6];
  60470. var norm1 = BABYLON.Tmp.Vector3[7];
  60471. var norm2 = BABYLON.Tmp.Vector3[8];
  60472. var i = 0;
  60473. var j = 0;
  60474. var k = 0;
  60475. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60476. var h = 0;
  60477. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60478. var d2 = 0;
  60479. var subdivisionsX = this._subdivisionsX;
  60480. var subdivisionsY = this._subdivisionsY;
  60481. for (var row = 0; row < subdivisionsY; row++) {
  60482. for (var col = 0; col < subdivisionsX; col++) {
  60483. i = col * 3;
  60484. j = row * (subdivisionsX + 1) * 3;
  60485. k = (row + 1) * (subdivisionsX + 1) * 3;
  60486. v1.x = positions[j + i];
  60487. v1.y = positions[j + i + 1];
  60488. v1.z = positions[j + i + 2];
  60489. v2.x = positions[j + i + 3];
  60490. v2.y = positions[j + i + 4];
  60491. v2.z = positions[j + i + 5];
  60492. v3.x = positions[k + i];
  60493. v3.y = positions[k + i + 1];
  60494. v3.z = positions[k + i + 2];
  60495. v4.x = positions[k + i + 3];
  60496. v4.y = positions[k + i + 4];
  60497. v4.z = positions[k + i + 5];
  60498. // 2D slope V1V4
  60499. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60500. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60501. // facet equations :
  60502. // we compute each facet normal vector
  60503. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60504. // we compute the value d by applying the equation to v1 which belongs to the plane
  60505. // then we store the facet equation in a Vector4
  60506. v2.subtractToRef(v1, v1v2);
  60507. v3.subtractToRef(v1, v1v3);
  60508. v4.subtractToRef(v1, v1v4);
  60509. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60510. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60511. norm1.normalize();
  60512. norm2.normalize();
  60513. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60514. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60515. var quad = this._heightQuads[row * subdivisionsX + col];
  60516. quad.slope.copyFromFloats(cd, h);
  60517. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60518. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60519. }
  60520. }
  60521. return this;
  60522. };
  60523. GroundMesh.prototype.serialize = function (serializationObject) {
  60524. _super.prototype.serialize.call(this, serializationObject);
  60525. serializationObject.subdivisionsX = this._subdivisionsX;
  60526. serializationObject.subdivisionsY = this._subdivisionsY;
  60527. serializationObject.minX = this._minX;
  60528. serializationObject.maxX = this._maxX;
  60529. serializationObject.minZ = this._minZ;
  60530. serializationObject.maxZ = this._maxZ;
  60531. serializationObject.width = this._width;
  60532. serializationObject.height = this._height;
  60533. };
  60534. GroundMesh.Parse = function (parsedMesh, scene) {
  60535. var result = new GroundMesh(parsedMesh.name, scene);
  60536. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60537. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60538. result._minX = parsedMesh.minX;
  60539. result._maxX = parsedMesh.maxX;
  60540. result._minZ = parsedMesh.minZ;
  60541. result._maxZ = parsedMesh.maxZ;
  60542. result._width = parsedMesh.width;
  60543. result._height = parsedMesh.height;
  60544. return result;
  60545. };
  60546. return GroundMesh;
  60547. }(BABYLON.Mesh));
  60548. BABYLON.GroundMesh = GroundMesh;
  60549. })(BABYLON || (BABYLON = {}));
  60550. //# sourceMappingURL=babylon.groundMesh.js.map
  60551. var BABYLON;
  60552. (function (BABYLON) {
  60553. /**
  60554. * Creates an instance based on a source mesh.
  60555. */
  60556. var InstancedMesh = /** @class */ (function (_super) {
  60557. __extends(InstancedMesh, _super);
  60558. function InstancedMesh(name, source) {
  60559. var _this = _super.call(this, name, source.getScene()) || this;
  60560. source.instances.push(_this);
  60561. _this._sourceMesh = source;
  60562. _this.position.copyFrom(source.position);
  60563. _this.rotation.copyFrom(source.rotation);
  60564. _this.scaling.copyFrom(source.scaling);
  60565. if (source.rotationQuaternion) {
  60566. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60567. }
  60568. _this.infiniteDistance = source.infiniteDistance;
  60569. _this.setPivotMatrix(source.getPivotMatrix());
  60570. _this.refreshBoundingInfo();
  60571. _this._syncSubMeshes();
  60572. return _this;
  60573. }
  60574. /**
  60575. * Returns the string "InstancedMesh".
  60576. */
  60577. InstancedMesh.prototype.getClassName = function () {
  60578. return "InstancedMesh";
  60579. };
  60580. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60581. // Methods
  60582. get: function () {
  60583. return this._sourceMesh.receiveShadows;
  60584. },
  60585. enumerable: true,
  60586. configurable: true
  60587. });
  60588. Object.defineProperty(InstancedMesh.prototype, "material", {
  60589. get: function () {
  60590. return this._sourceMesh.material;
  60591. },
  60592. enumerable: true,
  60593. configurable: true
  60594. });
  60595. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60596. get: function () {
  60597. return this._sourceMesh.visibility;
  60598. },
  60599. enumerable: true,
  60600. configurable: true
  60601. });
  60602. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60603. get: function () {
  60604. return this._sourceMesh.skeleton;
  60605. },
  60606. enumerable: true,
  60607. configurable: true
  60608. });
  60609. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60610. get: function () {
  60611. return this._sourceMesh.renderingGroupId;
  60612. },
  60613. set: function (value) {
  60614. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60615. return;
  60616. }
  60617. //no-op with warning
  60618. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60619. },
  60620. enumerable: true,
  60621. configurable: true
  60622. });
  60623. /**
  60624. * Returns the total number of vertices (integer).
  60625. */
  60626. InstancedMesh.prototype.getTotalVertices = function () {
  60627. return this._sourceMesh.getTotalVertices();
  60628. };
  60629. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60630. get: function () {
  60631. return this._sourceMesh;
  60632. },
  60633. enumerable: true,
  60634. configurable: true
  60635. });
  60636. /**
  60637. * Is this node ready to be used/rendered
  60638. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60639. * @return {boolean} is it ready
  60640. */
  60641. InstancedMesh.prototype.isReady = function (completeCheck) {
  60642. if (completeCheck === void 0) { completeCheck = false; }
  60643. return this._sourceMesh.isReady(completeCheck, true);
  60644. };
  60645. /**
  60646. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60647. */
  60648. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60649. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60650. };
  60651. /**
  60652. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60653. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60654. * The `data` are either a numeric array either a Float32Array.
  60655. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60656. * 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).
  60657. * Note that a new underlying VertexBuffer object is created each call.
  60658. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60659. *
  60660. * Possible `kind` values :
  60661. * - BABYLON.VertexBuffer.PositionKind
  60662. * - BABYLON.VertexBuffer.UVKind
  60663. * - BABYLON.VertexBuffer.UV2Kind
  60664. * - BABYLON.VertexBuffer.UV3Kind
  60665. * - BABYLON.VertexBuffer.UV4Kind
  60666. * - BABYLON.VertexBuffer.UV5Kind
  60667. * - BABYLON.VertexBuffer.UV6Kind
  60668. * - BABYLON.VertexBuffer.ColorKind
  60669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60673. *
  60674. * Returns the Mesh.
  60675. */
  60676. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60677. if (this.sourceMesh) {
  60678. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60679. }
  60680. return this.sourceMesh;
  60681. };
  60682. /**
  60683. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60684. * If the mesh has no geometry, it is simply returned as it is.
  60685. * The `data` are either a numeric array either a Float32Array.
  60686. * No new underlying VertexBuffer object is created.
  60687. * 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.
  60688. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60689. *
  60690. * Possible `kind` values :
  60691. * - BABYLON.VertexBuffer.PositionKind
  60692. * - BABYLON.VertexBuffer.UVKind
  60693. * - BABYLON.VertexBuffer.UV2Kind
  60694. * - BABYLON.VertexBuffer.UV3Kind
  60695. * - BABYLON.VertexBuffer.UV4Kind
  60696. * - BABYLON.VertexBuffer.UV5Kind
  60697. * - BABYLON.VertexBuffer.UV6Kind
  60698. * - BABYLON.VertexBuffer.ColorKind
  60699. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60700. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60701. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60702. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60703. *
  60704. * Returns the Mesh.
  60705. */
  60706. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60707. if (this.sourceMesh) {
  60708. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60709. }
  60710. return this.sourceMesh;
  60711. };
  60712. /**
  60713. * Sets the mesh indices.
  60714. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60715. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60716. * This method creates a new index buffer each call.
  60717. * Returns the Mesh.
  60718. */
  60719. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60720. if (totalVertices === void 0) { totalVertices = null; }
  60721. if (this.sourceMesh) {
  60722. this.sourceMesh.setIndices(indices, totalVertices);
  60723. }
  60724. return this.sourceMesh;
  60725. };
  60726. /**
  60727. * Boolean : True if the mesh owns the requested kind of data.
  60728. */
  60729. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60730. return this._sourceMesh.isVerticesDataPresent(kind);
  60731. };
  60732. /**
  60733. * Returns an array of indices (IndicesArray).
  60734. */
  60735. InstancedMesh.prototype.getIndices = function () {
  60736. return this._sourceMesh.getIndices();
  60737. };
  60738. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60739. get: function () {
  60740. return this._sourceMesh._positions;
  60741. },
  60742. enumerable: true,
  60743. configurable: true
  60744. });
  60745. /**
  60746. * Sets a new updated BoundingInfo to the mesh.
  60747. * Returns the mesh.
  60748. */
  60749. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60750. var meshBB = this._sourceMesh.getBoundingInfo();
  60751. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60752. this._updateBoundingInfo();
  60753. return this;
  60754. };
  60755. InstancedMesh.prototype._preActivate = function () {
  60756. if (this._currentLOD) {
  60757. this._currentLOD._preActivate();
  60758. }
  60759. return this;
  60760. };
  60761. InstancedMesh.prototype._activate = function (renderId) {
  60762. if (this._currentLOD) {
  60763. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60764. }
  60765. return this;
  60766. };
  60767. /**
  60768. * Returns the current associated LOD AbstractMesh.
  60769. */
  60770. InstancedMesh.prototype.getLOD = function (camera) {
  60771. if (!camera) {
  60772. return this;
  60773. }
  60774. var boundingInfo = this.getBoundingInfo();
  60775. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60776. if (this._currentLOD === this.sourceMesh) {
  60777. return this;
  60778. }
  60779. return this._currentLOD;
  60780. };
  60781. InstancedMesh.prototype._syncSubMeshes = function () {
  60782. this.releaseSubMeshes();
  60783. if (this._sourceMesh.subMeshes) {
  60784. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60785. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60786. }
  60787. }
  60788. return this;
  60789. };
  60790. InstancedMesh.prototype._generatePointsArray = function () {
  60791. return this._sourceMesh._generatePointsArray();
  60792. };
  60793. /**
  60794. * Creates a new InstancedMesh from the current mesh.
  60795. * - name (string) : the cloned mesh name
  60796. * - newParent (optional Node) : the optional Node to parent the clone to.
  60797. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60798. *
  60799. * Returns the clone.
  60800. */
  60801. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60802. var result = this._sourceMesh.createInstance(name);
  60803. // Deep copy
  60804. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60805. // Bounding info
  60806. this.refreshBoundingInfo();
  60807. // Parent
  60808. if (newParent) {
  60809. result.parent = newParent;
  60810. }
  60811. if (!doNotCloneChildren) {
  60812. // Children
  60813. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60814. var mesh = this.getScene().meshes[index];
  60815. if (mesh.parent === this) {
  60816. mesh.clone(mesh.name, result);
  60817. }
  60818. }
  60819. }
  60820. result.computeWorldMatrix(true);
  60821. return result;
  60822. };
  60823. /**
  60824. * Disposes the InstancedMesh.
  60825. * Returns nothing.
  60826. */
  60827. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60828. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60829. // Remove from mesh
  60830. var index = this._sourceMesh.instances.indexOf(this);
  60831. this._sourceMesh.instances.splice(index, 1);
  60832. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60833. };
  60834. return InstancedMesh;
  60835. }(BABYLON.AbstractMesh));
  60836. BABYLON.InstancedMesh = InstancedMesh;
  60837. })(BABYLON || (BABYLON = {}));
  60838. //# sourceMappingURL=babylon.instancedMesh.js.map
  60839. var BABYLON;
  60840. (function (BABYLON) {
  60841. var LinesMesh = /** @class */ (function (_super) {
  60842. __extends(LinesMesh, _super);
  60843. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60844. if (scene === void 0) { scene = null; }
  60845. if (parent === void 0) { parent = null; }
  60846. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60847. _this.useVertexColor = useVertexColor;
  60848. _this.useVertexAlpha = useVertexAlpha;
  60849. _this.color = new BABYLON.Color3(1, 1, 1);
  60850. _this.alpha = 1;
  60851. if (source) {
  60852. _this.color = source.color.clone();
  60853. _this.alpha = source.alpha;
  60854. _this.useVertexColor = source.useVertexColor;
  60855. _this.useVertexAlpha = source.useVertexAlpha;
  60856. }
  60857. _this._intersectionThreshold = 0.1;
  60858. var defines = [];
  60859. var options = {
  60860. attributes: [BABYLON.VertexBuffer.PositionKind],
  60861. uniforms: ["world", "viewProjection"],
  60862. needAlphaBlending: true,
  60863. defines: defines
  60864. };
  60865. if (useVertexAlpha === false) {
  60866. options.needAlphaBlending = false;
  60867. }
  60868. if (!useVertexColor) {
  60869. options.uniforms.push("color");
  60870. }
  60871. else {
  60872. options.defines.push("#define VERTEXCOLOR");
  60873. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60874. }
  60875. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60876. return _this;
  60877. }
  60878. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60879. /**
  60880. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60881. * This margin is expressed in world space coordinates, so its value may vary.
  60882. * Default value is 0.1
  60883. * @returns the intersection Threshold value.
  60884. */
  60885. get: function () {
  60886. return this._intersectionThreshold;
  60887. },
  60888. /**
  60889. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60890. * This margin is expressed in world space coordinates, so its value may vary.
  60891. * @param value the new threshold to apply
  60892. */
  60893. set: function (value) {
  60894. if (this._intersectionThreshold === value) {
  60895. return;
  60896. }
  60897. this._intersectionThreshold = value;
  60898. if (this.geometry) {
  60899. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60900. }
  60901. },
  60902. enumerable: true,
  60903. configurable: true
  60904. });
  60905. /**
  60906. * Returns the string "LineMesh"
  60907. */
  60908. LinesMesh.prototype.getClassName = function () {
  60909. return "LinesMesh";
  60910. };
  60911. Object.defineProperty(LinesMesh.prototype, "material", {
  60912. get: function () {
  60913. return this._colorShader;
  60914. },
  60915. set: function (value) {
  60916. // Do nothing
  60917. },
  60918. enumerable: true,
  60919. configurable: true
  60920. });
  60921. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60922. get: function () {
  60923. return false;
  60924. },
  60925. enumerable: true,
  60926. configurable: true
  60927. });
  60928. LinesMesh.prototype.createInstance = function (name) {
  60929. throw new Error("LinesMeshes do not support createInstance.");
  60930. };
  60931. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60932. if (!this._geometry) {
  60933. return this;
  60934. }
  60935. // VBOs
  60936. this._geometry._bind(this._colorShader.getEffect());
  60937. // Color
  60938. if (!this.useVertexColor) {
  60939. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60940. }
  60941. return this;
  60942. };
  60943. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60944. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60945. return this;
  60946. }
  60947. var engine = this.getScene().getEngine();
  60948. // Draw order
  60949. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60950. return this;
  60951. };
  60952. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60953. this._colorShader.dispose();
  60954. _super.prototype.dispose.call(this, doNotRecurse);
  60955. };
  60956. /**
  60957. * Returns a new LineMesh object cloned from the current one.
  60958. */
  60959. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60960. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60961. };
  60962. return LinesMesh;
  60963. }(BABYLON.Mesh));
  60964. BABYLON.LinesMesh = LinesMesh;
  60965. })(BABYLON || (BABYLON = {}));
  60966. //# sourceMappingURL=babylon.linesMesh.js.map
  60967. var BABYLON;
  60968. (function (BABYLON) {
  60969. /**
  60970. * Class containing static functions to help procedurally build meshes
  60971. */
  60972. var MeshBuilder = /** @class */ (function () {
  60973. function MeshBuilder() {
  60974. }
  60975. MeshBuilder.updateSideOrientation = function (orientation) {
  60976. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60977. return BABYLON.Mesh.DOUBLESIDE;
  60978. }
  60979. if (orientation === undefined || orientation === null) {
  60980. return BABYLON.Mesh.FRONTSIDE;
  60981. }
  60982. return orientation;
  60983. };
  60984. /**
  60985. * Creates a box mesh
  60986. * * The parameter `size` sets the size (float) of each box side (default 1)
  60987. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60988. * * 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)
  60989. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60990. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60991. * * 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
  60992. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60993. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60994. * @param name defines the name of the mesh
  60995. * @param options defines the options used to create the mesh
  60996. * @param scene defines the hosting scene
  60997. * @returns the box mesh
  60998. */
  60999. MeshBuilder.CreateBox = function (name, options, scene) {
  61000. if (scene === void 0) { scene = null; }
  61001. var box = new BABYLON.Mesh(name, scene);
  61002. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61003. box._originalBuilderSideOrientation = options.sideOrientation;
  61004. var vertexData = BABYLON.VertexData.CreateBox(options);
  61005. vertexData.applyToMesh(box, options.updatable);
  61006. return box;
  61007. };
  61008. /**
  61009. * Creates a sphere mesh
  61010. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61011. * * 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`)
  61012. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61013. * * 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
  61014. * * 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)
  61015. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61016. * * 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
  61017. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61018. * @param name defines the name of the mesh
  61019. * @param options defines the options used to create the mesh
  61020. * @param scene defines the hosting scene
  61021. * @returns the sphere mesh
  61022. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61023. */
  61024. MeshBuilder.CreateSphere = function (name, options, scene) {
  61025. var sphere = new BABYLON.Mesh(name, scene);
  61026. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61027. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61028. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61029. vertexData.applyToMesh(sphere, options.updatable);
  61030. return sphere;
  61031. };
  61032. /**
  61033. * Creates a plane polygonal mesh. By default, this is a disc
  61034. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61035. * * 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
  61036. * * 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
  61037. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61038. * * 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
  61039. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61040. * @param name defines the name of the mesh
  61041. * @param options defines the options used to create the mesh
  61042. * @param scene defines the hosting scene
  61043. * @returns the plane polygonal mesh
  61044. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61045. */
  61046. MeshBuilder.CreateDisc = function (name, options, scene) {
  61047. if (scene === void 0) { scene = null; }
  61048. var disc = new BABYLON.Mesh(name, scene);
  61049. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61050. disc._originalBuilderSideOrientation = options.sideOrientation;
  61051. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61052. vertexData.applyToMesh(disc, options.updatable);
  61053. return disc;
  61054. };
  61055. /**
  61056. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61057. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61058. * * 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`)
  61059. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61060. * * 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
  61061. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61062. * * 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
  61063. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61064. * @param name defines the name of the mesh
  61065. * @param options defines the options used to create the mesh
  61066. * @param scene defines the hosting scene
  61067. * @returns the icosahedron mesh
  61068. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61069. */
  61070. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61071. var sphere = new BABYLON.Mesh(name, scene);
  61072. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61073. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61074. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61075. vertexData.applyToMesh(sphere, options.updatable);
  61076. return sphere;
  61077. };
  61078. ;
  61079. /**
  61080. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61081. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61082. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61083. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61084. * * 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
  61085. * * 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
  61086. * * 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
  61087. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61088. * * 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
  61089. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61090. * * 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
  61091. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61092. * * 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
  61093. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61094. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61095. * @param name defines the name of the mesh
  61096. * @param options defines the options used to create the mesh
  61097. * @param scene defines the hosting scene
  61098. * @returns the ribbon mesh
  61099. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61100. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61101. */
  61102. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61103. if (scene === void 0) { scene = null; }
  61104. var pathArray = options.pathArray;
  61105. var closeArray = options.closeArray;
  61106. var closePath = options.closePath;
  61107. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61108. var instance = options.instance;
  61109. var updatable = options.updatable;
  61110. if (instance) { // existing ribbon instance update
  61111. // positionFunction : ribbon case
  61112. // only pathArray and sideOrientation parameters are taken into account for positions update
  61113. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61114. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61115. var positionFunction = function (positions) {
  61116. var minlg = pathArray[0].length;
  61117. var i = 0;
  61118. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61119. for (var si = 1; si <= ns; si++) {
  61120. for (var p = 0; p < pathArray.length; p++) {
  61121. var path = pathArray[p];
  61122. var l = path.length;
  61123. minlg = (minlg < l) ? minlg : l;
  61124. var j = 0;
  61125. while (j < minlg) {
  61126. positions[i] = path[j].x;
  61127. positions[i + 1] = path[j].y;
  61128. positions[i + 2] = path[j].z;
  61129. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61130. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61131. }
  61132. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61133. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61134. }
  61135. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61136. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61137. }
  61138. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61139. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61140. }
  61141. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61142. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61143. }
  61144. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61145. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61146. }
  61147. j++;
  61148. i += 3;
  61149. }
  61150. if (instance._closePath) {
  61151. positions[i] = path[0].x;
  61152. positions[i + 1] = path[0].y;
  61153. positions[i + 2] = path[0].z;
  61154. i += 3;
  61155. }
  61156. }
  61157. }
  61158. };
  61159. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61160. positionFunction(positions);
  61161. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61162. instance._boundingInfo.update(instance._worldMatrix);
  61163. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61164. if (options.colors) {
  61165. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61166. for (var c = 0; c < options.colors.length; c++) {
  61167. colors[c * 4] = options.colors[c].r;
  61168. colors[c * 4 + 1] = options.colors[c].g;
  61169. colors[c * 4 + 2] = options.colors[c].b;
  61170. colors[c * 4 + 3] = options.colors[c].a;
  61171. }
  61172. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61173. }
  61174. if (options.uvs) {
  61175. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61176. for (var i = 0; i < options.uvs.length; i++) {
  61177. uvs[i * 2] = options.uvs[i].x;
  61178. uvs[i * 2 + 1] = options.uvs[i].y;
  61179. }
  61180. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61181. }
  61182. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61183. var indices = instance.getIndices();
  61184. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61185. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61186. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61187. if (instance._closePath) {
  61188. var indexFirst = 0;
  61189. var indexLast = 0;
  61190. for (var p = 0; p < pathArray.length; p++) {
  61191. indexFirst = instance._idx[p] * 3;
  61192. if (p + 1 < pathArray.length) {
  61193. indexLast = (instance._idx[p + 1] - 1) * 3;
  61194. }
  61195. else {
  61196. indexLast = normals.length - 3;
  61197. }
  61198. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61199. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61200. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61201. normals[indexLast] = normals[indexFirst];
  61202. normals[indexLast + 1] = normals[indexFirst + 1];
  61203. normals[indexLast + 2] = normals[indexFirst + 2];
  61204. }
  61205. }
  61206. if (!(instance.areNormalsFrozen)) {
  61207. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61208. }
  61209. }
  61210. return instance;
  61211. }
  61212. else { // new ribbon creation
  61213. var ribbon = new BABYLON.Mesh(name, scene);
  61214. ribbon._originalBuilderSideOrientation = sideOrientation;
  61215. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61216. if (closePath) {
  61217. ribbon._idx = vertexData._idx;
  61218. }
  61219. ribbon._closePath = closePath;
  61220. ribbon._closeArray = closeArray;
  61221. vertexData.applyToMesh(ribbon, updatable);
  61222. return ribbon;
  61223. }
  61224. };
  61225. /**
  61226. * Creates a cylinder or a cone mesh
  61227. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61228. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61229. * * 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.
  61230. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61231. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61232. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61233. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61234. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61235. * * 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).
  61236. * * 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
  61237. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61238. * * 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
  61239. * * 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.
  61240. * * If `enclose` is false, a ring surface is one element.
  61241. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61242. * * 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
  61243. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61244. * * 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
  61245. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61246. * @param name defines the name of the mesh
  61247. * @param options defines the options used to create the mesh
  61248. * @param scene defines the hosting scene
  61249. * @returns the cylinder mesh
  61250. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61251. */
  61252. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61253. var cylinder = new BABYLON.Mesh(name, scene);
  61254. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61255. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61256. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61257. vertexData.applyToMesh(cylinder, options.updatable);
  61258. return cylinder;
  61259. };
  61260. /**
  61261. * Creates a torus mesh
  61262. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61263. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61264. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61265. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61266. * * 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
  61267. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61268. * @param name defines the name of the mesh
  61269. * @param options defines the options used to create the mesh
  61270. * @param scene defines the hosting scene
  61271. * @returns the torus mesh
  61272. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61273. */
  61274. MeshBuilder.CreateTorus = function (name, options, scene) {
  61275. var torus = new BABYLON.Mesh(name, scene);
  61276. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61277. torus._originalBuilderSideOrientation = options.sideOrientation;
  61278. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61279. vertexData.applyToMesh(torus, options.updatable);
  61280. return torus;
  61281. };
  61282. /**
  61283. * Creates a torus knot mesh
  61284. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61285. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61286. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61287. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61288. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61289. * * 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
  61290. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61291. * @param name defines the name of the mesh
  61292. * @param options defines the options used to create the mesh
  61293. * @param scene defines the hosting scene
  61294. * @returns the torus knot mesh
  61295. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61296. */
  61297. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61298. var torusKnot = new BABYLON.Mesh(name, scene);
  61299. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61300. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61301. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61302. vertexData.applyToMesh(torusKnot, options.updatable);
  61303. return torusKnot;
  61304. };
  61305. /**
  61306. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61307. * * 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
  61308. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61309. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61310. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61311. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61312. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61313. * * 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
  61314. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61315. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61316. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61317. * @param name defines the name of the new line system
  61318. * @param options defines the options used to create the line system
  61319. * @param scene defines the hosting scene
  61320. * @returns a new line system mesh
  61321. */
  61322. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61323. var instance = options.instance;
  61324. var lines = options.lines;
  61325. var colors = options.colors;
  61326. if (instance) { // lines update
  61327. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61328. var vertexColor;
  61329. var lineColors;
  61330. if (colors) {
  61331. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61332. }
  61333. var i = 0;
  61334. var c = 0;
  61335. for (var l = 0; l < lines.length; l++) {
  61336. var points = lines[l];
  61337. for (var p = 0; p < points.length; p++) {
  61338. positions[i] = points[p].x;
  61339. positions[i + 1] = points[p].y;
  61340. positions[i + 2] = points[p].z;
  61341. if (colors && vertexColor) {
  61342. lineColors = colors[l];
  61343. vertexColor[c] = lineColors[p].r;
  61344. vertexColor[c + 1] = lineColors[p].g;
  61345. vertexColor[c + 2] = lineColors[p].b;
  61346. vertexColor[c + 3] = lineColors[p].a;
  61347. c += 4;
  61348. }
  61349. i += 3;
  61350. }
  61351. }
  61352. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61353. if (colors && vertexColor) {
  61354. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61355. }
  61356. return instance;
  61357. }
  61358. // line system creation
  61359. var useVertexColor = (colors) ? true : false;
  61360. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61361. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61362. vertexData.applyToMesh(lineSystem, options.updatable);
  61363. return lineSystem;
  61364. };
  61365. /**
  61366. * Creates a line mesh
  61367. * 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
  61368. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61369. * * The parameter `points` is an array successive Vector3
  61370. * * 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
  61371. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61372. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61373. * * When updating an instance, remember that only point positions can change, not the number of points
  61374. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61375. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61376. * @param name defines the name of the new line system
  61377. * @param options defines the options used to create the line system
  61378. * @param scene defines the hosting scene
  61379. * @returns a new line mesh
  61380. */
  61381. MeshBuilder.CreateLines = function (name, options, scene) {
  61382. if (scene === void 0) { scene = null; }
  61383. var colors = (options.colors) ? [options.colors] : null;
  61384. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61385. return lines;
  61386. };
  61387. /**
  61388. * Creates a dashed line mesh
  61389. * * 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
  61390. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61391. * * The parameter `points` is an array successive Vector3
  61392. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61393. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61394. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61395. * * 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
  61396. * * When updating an instance, remember that only point positions can change, not the number of points
  61397. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61398. * @param name defines the name of the mesh
  61399. * @param options defines the options used to create the mesh
  61400. * @param scene defines the hosting scene
  61401. * @returns the dashed line mesh
  61402. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61403. */
  61404. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61405. if (scene === void 0) { scene = null; }
  61406. var points = options.points;
  61407. var instance = options.instance;
  61408. var gapSize = options.gapSize || 1;
  61409. var dashSize = options.dashSize || 3;
  61410. if (instance) { // dashed lines update
  61411. var positionFunction = function (positions) {
  61412. var curvect = BABYLON.Vector3.Zero();
  61413. var nbSeg = positions.length / 6;
  61414. var lg = 0;
  61415. var nb = 0;
  61416. var shft = 0;
  61417. var dashshft = 0;
  61418. var curshft = 0;
  61419. var p = 0;
  61420. var i = 0;
  61421. var j = 0;
  61422. for (i = 0; i < points.length - 1; i++) {
  61423. points[i + 1].subtractToRef(points[i], curvect);
  61424. lg += curvect.length();
  61425. }
  61426. shft = lg / nbSeg;
  61427. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61428. for (i = 0; i < points.length - 1; i++) {
  61429. points[i + 1].subtractToRef(points[i], curvect);
  61430. nb = Math.floor(curvect.length() / shft);
  61431. curvect.normalize();
  61432. j = 0;
  61433. while (j < nb && p < positions.length) {
  61434. curshft = shft * j;
  61435. positions[p] = points[i].x + curshft * curvect.x;
  61436. positions[p + 1] = points[i].y + curshft * curvect.y;
  61437. positions[p + 2] = points[i].z + curshft * curvect.z;
  61438. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61439. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61440. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61441. p += 6;
  61442. j++;
  61443. }
  61444. }
  61445. while (p < positions.length) {
  61446. positions[p] = points[i].x;
  61447. positions[p + 1] = points[i].y;
  61448. positions[p + 2] = points[i].z;
  61449. p += 3;
  61450. }
  61451. };
  61452. instance.updateMeshPositions(positionFunction, false);
  61453. return instance;
  61454. }
  61455. // dashed lines creation
  61456. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61457. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61458. vertexData.applyToMesh(dashedLines, options.updatable);
  61459. dashedLines.dashSize = dashSize;
  61460. dashedLines.gapSize = gapSize;
  61461. return dashedLines;
  61462. };
  61463. /**
  61464. * 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.
  61465. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  61466. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61467. * * The parameter `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.
  61468. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61469. * * 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
  61470. * * 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
  61471. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61472. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61473. * * 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
  61474. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61475. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61476. * @param name defines the name of the mesh
  61477. * @param options defines the options used to create the mesh
  61478. * @param scene defines the hosting scene
  61479. * @returns the extruded shape mesh
  61480. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61481. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61482. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61483. */
  61484. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61485. if (scene === void 0) { scene = null; }
  61486. var path = options.path;
  61487. var shape = options.shape;
  61488. var scale = options.scale || 1;
  61489. var rotation = options.rotation || 0;
  61490. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61491. var updatable = options.updatable;
  61492. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61493. var instance = options.instance || null;
  61494. var invertUV = options.invertUV || false;
  61495. 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);
  61496. };
  61497. /**
  61498. * Creates an custom extruded shape mesh.
  61499. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61500. * * 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.
  61501. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61502. * * 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
  61503. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61504. * * 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
  61505. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61506. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61507. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61508. * * 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
  61509. * * 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
  61510. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61511. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61512. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61513. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61514. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61515. * @param name defines the name of the mesh
  61516. * @param options defines the options used to create the mesh
  61517. * @param scene defines the hosting scene
  61518. * @returns the custom extruded shape mesh
  61519. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61520. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61521. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61522. */
  61523. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61524. var path = options.path;
  61525. var shape = options.shape;
  61526. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61527. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61528. var ribbonCloseArray = options.ribbonCloseArray || false;
  61529. var ribbonClosePath = options.ribbonClosePath || false;
  61530. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61531. var updatable = options.updatable;
  61532. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61533. var instance = options.instance;
  61534. var invertUV = options.invertUV || false;
  61535. 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);
  61536. };
  61537. /**
  61538. * Creates lathe mesh.
  61539. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61540. * * 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
  61541. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61542. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61543. * * 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
  61544. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61545. * * 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
  61546. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61547. * * 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
  61548. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61549. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61550. * @param name defines the name of the mesh
  61551. * @param options defines the options used to create the mesh
  61552. * @param scene defines the hosting scene
  61553. * @returns the lathe mesh
  61554. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61555. */
  61556. MeshBuilder.CreateLathe = function (name, options, scene) {
  61557. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61558. var closed = (options.closed === undefined) ? true : options.closed;
  61559. var shape = options.shape;
  61560. var radius = options.radius || 1;
  61561. var tessellation = options.tessellation || 64;
  61562. var updatable = options.updatable;
  61563. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61564. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61565. var pi2 = Math.PI * 2;
  61566. var paths = new Array();
  61567. var invertUV = options.invertUV || false;
  61568. var i = 0;
  61569. var p = 0;
  61570. var step = pi2 / tessellation * arc;
  61571. var rotated;
  61572. var path = new Array();
  61573. for (i = 0; i <= tessellation; i++) {
  61574. var path = [];
  61575. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61576. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61577. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61578. }
  61579. for (p = 0; p < shape.length; p++) {
  61580. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61581. path.push(rotated);
  61582. }
  61583. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61584. 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));
  61585. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61586. }
  61587. paths.push(path);
  61588. }
  61589. // lathe ribbon
  61590. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61591. return lathe;
  61592. };
  61593. /**
  61594. * Creates a plane mesh
  61595. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61596. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61597. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61598. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61599. * * 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
  61600. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61601. * @param name defines the name of the mesh
  61602. * @param options defines the options used to create the mesh
  61603. * @param scene defines the hosting scene
  61604. * @returns the plane mesh
  61605. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61606. */
  61607. MeshBuilder.CreatePlane = function (name, options, scene) {
  61608. var plane = new BABYLON.Mesh(name, scene);
  61609. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61610. plane._originalBuilderSideOrientation = options.sideOrientation;
  61611. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61612. vertexData.applyToMesh(plane, options.updatable);
  61613. if (options.sourcePlane) {
  61614. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61615. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61616. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61617. plane.rotate(vectorProduct, product);
  61618. }
  61619. return plane;
  61620. };
  61621. /**
  61622. * Creates a ground mesh
  61623. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61624. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61625. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61626. * @param name defines the name of the mesh
  61627. * @param options defines the options used to create the mesh
  61628. * @param scene defines the hosting scene
  61629. * @returns the ground mesh
  61630. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61631. */
  61632. MeshBuilder.CreateGround = function (name, options, scene) {
  61633. var ground = new BABYLON.GroundMesh(name, scene);
  61634. ground._setReady(false);
  61635. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61636. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61637. ground._width = options.width || 1;
  61638. ground._height = options.height || 1;
  61639. ground._maxX = ground._width / 2;
  61640. ground._maxZ = ground._height / 2;
  61641. ground._minX = -ground._maxX;
  61642. ground._minZ = -ground._maxZ;
  61643. var vertexData = BABYLON.VertexData.CreateGround(options);
  61644. vertexData.applyToMesh(ground, options.updatable);
  61645. ground._setReady(true);
  61646. return ground;
  61647. };
  61648. /**
  61649. * Creates a tiled ground mesh
  61650. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61651. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61652. * * 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
  61653. * * 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
  61654. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61655. * @param name defines the name of the mesh
  61656. * @param options defines the options used to create the mesh
  61657. * @param scene defines the hosting scene
  61658. * @returns the tiled ground mesh
  61659. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61660. */
  61661. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61662. var tiledGround = new BABYLON.Mesh(name, scene);
  61663. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61664. vertexData.applyToMesh(tiledGround, options.updatable);
  61665. return tiledGround;
  61666. };
  61667. /**
  61668. * Creates a ground mesh from a height map
  61669. * * The parameter `url` sets the URL of the height map image resource.
  61670. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61671. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61672. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61673. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61674. * * 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.
  61675. * * 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).
  61676. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61677. * @param name defines the name of the mesh
  61678. * @param url defines the url to the height map
  61679. * @param options defines the options used to create the mesh
  61680. * @param scene defines the hosting scene
  61681. * @returns the ground mesh
  61682. * @see http://doc.babylonjs.com/babylon101/height_map
  61683. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61684. */
  61685. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61686. var width = options.width || 10.0;
  61687. var height = options.height || 10.0;
  61688. var subdivisions = options.subdivisions || 1 | 0;
  61689. var minHeight = options.minHeight || 0.0;
  61690. var maxHeight = options.maxHeight || 1.0;
  61691. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61692. var updatable = options.updatable;
  61693. var onReady = options.onReady;
  61694. var ground = new BABYLON.GroundMesh(name, scene);
  61695. ground._subdivisionsX = subdivisions;
  61696. ground._subdivisionsY = subdivisions;
  61697. ground._width = width;
  61698. ground._height = height;
  61699. ground._maxX = ground._width / 2.0;
  61700. ground._maxZ = ground._height / 2.0;
  61701. ground._minX = -ground._maxX;
  61702. ground._minZ = -ground._maxZ;
  61703. ground._setReady(false);
  61704. var onload = function (img) {
  61705. // Getting height map data
  61706. var canvas = document.createElement("canvas");
  61707. var context = canvas.getContext("2d");
  61708. if (!context) {
  61709. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61710. }
  61711. if (scene.isDisposed) {
  61712. return;
  61713. }
  61714. var bufferWidth = img.width;
  61715. var bufferHeight = img.height;
  61716. canvas.width = bufferWidth;
  61717. canvas.height = bufferHeight;
  61718. context.drawImage(img, 0, 0);
  61719. // Create VertexData from map data
  61720. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61721. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61722. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61723. width: width, height: height,
  61724. subdivisions: subdivisions,
  61725. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61726. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61727. });
  61728. vertexData.applyToMesh(ground, updatable);
  61729. //execute ready callback, if set
  61730. if (onReady) {
  61731. onReady(ground);
  61732. }
  61733. ground._setReady(true);
  61734. };
  61735. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61736. return ground;
  61737. };
  61738. /**
  61739. * Creates a polygon mesh
  61740. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61741. * * 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
  61742. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61743. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61744. * * 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)
  61745. * * Remember you can only change the shape positions, not their number when updating a polygon
  61746. * @param name defines the name of the mesh
  61747. * @param options defines the options used to create the mesh
  61748. * @param scene defines the hosting scene
  61749. * @returns the polygon mesh
  61750. */
  61751. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61752. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61753. var shape = options.shape;
  61754. var holes = options.holes || [];
  61755. var depth = options.depth || 0;
  61756. var contours = [];
  61757. var hole = [];
  61758. for (var i = 0; i < shape.length; i++) {
  61759. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61760. }
  61761. var epsilon = 0.00000001;
  61762. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61763. contours.pop();
  61764. }
  61765. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61766. for (var hNb = 0; hNb < holes.length; hNb++) {
  61767. hole = [];
  61768. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61769. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61770. }
  61771. polygonTriangulation.addHole(hole);
  61772. }
  61773. var polygon = polygonTriangulation.build(options.updatable, depth);
  61774. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61775. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61776. vertexData.applyToMesh(polygon, options.updatable);
  61777. return polygon;
  61778. };
  61779. ;
  61780. /**
  61781. * Creates an extruded polygon mesh, with depth in the Y direction.
  61782. * * 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)
  61783. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61784. * @param name defines the name of the mesh
  61785. * @param options defines the options used to create the mesh
  61786. * @param scene defines the hosting scene
  61787. * @returns the polygon mesh
  61788. */
  61789. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61790. return MeshBuilder.CreatePolygon(name, options, scene);
  61791. };
  61792. ;
  61793. /**
  61794. * Creates a tube mesh.
  61795. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61796. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61797. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61798. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61799. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61800. * * 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)
  61801. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61802. * * 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
  61803. * * 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
  61804. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61805. * * 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
  61806. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61807. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61808. * @param name defines the name of the mesh
  61809. * @param options defines the options used to create the mesh
  61810. * @param scene defines the hosting scene
  61811. * @returns the tube mesh
  61812. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61813. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61814. */
  61815. MeshBuilder.CreateTube = function (name, options, scene) {
  61816. var path = options.path;
  61817. var instance = options.instance;
  61818. var radius = 1.0;
  61819. if (instance) {
  61820. radius = instance.radius;
  61821. }
  61822. if (options.radius !== undefined) {
  61823. radius = options.radius;
  61824. }
  61825. ;
  61826. var tessellation = options.tessellation || 64 | 0;
  61827. var radiusFunction = options.radiusFunction || null;
  61828. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61829. var invertUV = options.invertUV || false;
  61830. var updatable = options.updatable;
  61831. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61832. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61833. // tube geometry
  61834. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61835. var tangents = path3D.getTangents();
  61836. var normals = path3D.getNormals();
  61837. var distances = path3D.getDistances();
  61838. var pi2 = Math.PI * 2;
  61839. var step = pi2 / tessellation * arc;
  61840. var returnRadius = function () { return radius; };
  61841. var radiusFunctionFinal = radiusFunction || returnRadius;
  61842. var circlePath;
  61843. var rad;
  61844. var normal;
  61845. var rotated;
  61846. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61847. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61848. for (var i = 0; i < path.length; i++) {
  61849. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61850. circlePath = Array(); // current circle array
  61851. normal = normals[i]; // current normal
  61852. for (var t = 0; t < tessellation; t++) {
  61853. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61854. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61855. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61856. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61857. circlePath[t] = rotated;
  61858. }
  61859. circlePaths[index] = circlePath;
  61860. index++;
  61861. }
  61862. // cap
  61863. var capPath = function (nbPoints, pathIndex) {
  61864. var pointCap = Array();
  61865. for (var i = 0; i < nbPoints; i++) {
  61866. pointCap.push(path[pathIndex]);
  61867. }
  61868. return pointCap;
  61869. };
  61870. switch (cap) {
  61871. case BABYLON.Mesh.NO_CAP:
  61872. break;
  61873. case BABYLON.Mesh.CAP_START:
  61874. circlePaths[0] = capPath(tessellation, 0);
  61875. circlePaths[1] = circlePaths[2].slice(0);
  61876. break;
  61877. case BABYLON.Mesh.CAP_END:
  61878. circlePaths[index] = circlePaths[index - 1].slice(0);
  61879. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61880. break;
  61881. case BABYLON.Mesh.CAP_ALL:
  61882. circlePaths[0] = capPath(tessellation, 0);
  61883. circlePaths[1] = circlePaths[2].slice(0);
  61884. circlePaths[index] = circlePaths[index - 1].slice(0);
  61885. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61886. break;
  61887. default:
  61888. break;
  61889. }
  61890. return circlePaths;
  61891. };
  61892. var path3D;
  61893. var pathArray;
  61894. if (instance) { // tube update
  61895. var arc = options.arc || instance.arc;
  61896. path3D = (instance.path3D).update(path);
  61897. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61898. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61899. instance.path3D = path3D;
  61900. instance.pathArray = pathArray;
  61901. instance.arc = arc;
  61902. instance.radius = radius;
  61903. return instance;
  61904. }
  61905. // tube creation
  61906. path3D = new BABYLON.Path3D(path);
  61907. var newPathArray = new Array();
  61908. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61909. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61910. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61911. tube.pathArray = pathArray;
  61912. tube.path3D = path3D;
  61913. tube.tessellation = tessellation;
  61914. tube.cap = cap;
  61915. tube.arc = options.arc;
  61916. tube.radius = radius;
  61917. return tube;
  61918. };
  61919. /**
  61920. * Creates a polyhedron mesh
  61921. * * 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
  61922. * * The parameter `size` (positive float, default 1) sets the polygon size
  61923. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61924. * * 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`
  61925. * * 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
  61926. * * 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)`)
  61927. * * 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
  61928. * * 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
  61929. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61930. * * 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
  61931. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61932. * @param name defines the name of the mesh
  61933. * @param options defines the options used to create the mesh
  61934. * @param scene defines the hosting scene
  61935. * @returns the polyhedron mesh
  61936. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61937. */
  61938. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61939. var polyhedron = new BABYLON.Mesh(name, scene);
  61940. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61941. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61942. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61943. vertexData.applyToMesh(polyhedron, options.updatable);
  61944. return polyhedron;
  61945. };
  61946. /**
  61947. * Creates a decal mesh.
  61948. * 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
  61949. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61950. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61951. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61952. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61953. * @param name defines the name of the mesh
  61954. * @param sourceMesh defines the mesh where the decal must be applied
  61955. * @param options defines the options used to create the mesh
  61956. * @param scene defines the hosting scene
  61957. * @returns the decal mesh
  61958. * @see http://doc.babylonjs.com/how_to/decals
  61959. */
  61960. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61961. var indices = sourceMesh.getIndices();
  61962. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61963. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61964. var position = options.position || BABYLON.Vector3.Zero();
  61965. var normal = options.normal || BABYLON.Vector3.Up();
  61966. var size = options.size || BABYLON.Vector3.One();
  61967. var angle = options.angle || 0;
  61968. // Getting correct rotation
  61969. if (!normal) {
  61970. var target = new BABYLON.Vector3(0, 0, 1);
  61971. var camera = sourceMesh.getScene().activeCamera;
  61972. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61973. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61974. }
  61975. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61976. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61977. var pitch = Math.atan2(normal.y, len);
  61978. // Matrix
  61979. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61980. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61981. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61982. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61983. var vertexData = new BABYLON.VertexData();
  61984. vertexData.indices = [];
  61985. vertexData.positions = [];
  61986. vertexData.normals = [];
  61987. vertexData.uvs = [];
  61988. var currentVertexDataIndex = 0;
  61989. var extractDecalVector3 = function (indexId) {
  61990. var result = new BABYLON.PositionNormalVertex();
  61991. if (!indices || !positions || !normals) {
  61992. return result;
  61993. }
  61994. var vertexId = indices[indexId];
  61995. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61996. // Send vector to decal local world
  61997. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61998. // Get normal
  61999. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62000. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62001. return result;
  62002. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62003. var clip = function (vertices, axis) {
  62004. if (vertices.length === 0) {
  62005. return vertices;
  62006. }
  62007. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62008. var clipVertices = function (v0, v1) {
  62009. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62010. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62011. };
  62012. var result = new Array();
  62013. for (var index = 0; index < vertices.length; index += 3) {
  62014. var v1Out;
  62015. var v2Out;
  62016. var v3Out;
  62017. var total = 0;
  62018. var nV1 = null;
  62019. var nV2 = null;
  62020. var nV3 = null;
  62021. var nV4 = null;
  62022. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62023. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62024. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62025. v1Out = d1 > 0;
  62026. v2Out = d2 > 0;
  62027. v3Out = d3 > 0;
  62028. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62029. switch (total) {
  62030. case 0:
  62031. result.push(vertices[index]);
  62032. result.push(vertices[index + 1]);
  62033. result.push(vertices[index + 2]);
  62034. break;
  62035. case 1:
  62036. if (v1Out) {
  62037. nV1 = vertices[index + 1];
  62038. nV2 = vertices[index + 2];
  62039. nV3 = clipVertices(vertices[index], nV1);
  62040. nV4 = clipVertices(vertices[index], nV2);
  62041. }
  62042. if (v2Out) {
  62043. nV1 = vertices[index];
  62044. nV2 = vertices[index + 2];
  62045. nV3 = clipVertices(vertices[index + 1], nV1);
  62046. nV4 = clipVertices(vertices[index + 1], nV2);
  62047. result.push(nV3);
  62048. result.push(nV2.clone());
  62049. result.push(nV1.clone());
  62050. result.push(nV2.clone());
  62051. result.push(nV3.clone());
  62052. result.push(nV4);
  62053. break;
  62054. }
  62055. if (v3Out) {
  62056. nV1 = vertices[index];
  62057. nV2 = vertices[index + 1];
  62058. nV3 = clipVertices(vertices[index + 2], nV1);
  62059. nV4 = clipVertices(vertices[index + 2], nV2);
  62060. }
  62061. if (nV1 && nV2 && nV3 && nV4) {
  62062. result.push(nV1.clone());
  62063. result.push(nV2.clone());
  62064. result.push(nV3);
  62065. result.push(nV4);
  62066. result.push(nV3.clone());
  62067. result.push(nV2.clone());
  62068. }
  62069. break;
  62070. case 2:
  62071. if (!v1Out) {
  62072. nV1 = vertices[index].clone();
  62073. nV2 = clipVertices(nV1, vertices[index + 1]);
  62074. nV3 = clipVertices(nV1, vertices[index + 2]);
  62075. result.push(nV1);
  62076. result.push(nV2);
  62077. result.push(nV3);
  62078. }
  62079. if (!v2Out) {
  62080. nV1 = vertices[index + 1].clone();
  62081. nV2 = clipVertices(nV1, vertices[index + 2]);
  62082. nV3 = clipVertices(nV1, vertices[index]);
  62083. result.push(nV1);
  62084. result.push(nV2);
  62085. result.push(nV3);
  62086. }
  62087. if (!v3Out) {
  62088. nV1 = vertices[index + 2].clone();
  62089. nV2 = clipVertices(nV1, vertices[index]);
  62090. nV3 = clipVertices(nV1, vertices[index + 1]);
  62091. result.push(nV1);
  62092. result.push(nV2);
  62093. result.push(nV3);
  62094. }
  62095. break;
  62096. case 3:
  62097. break;
  62098. }
  62099. }
  62100. return result;
  62101. };
  62102. for (var index = 0; index < indices.length; index += 3) {
  62103. var faceVertices = new Array();
  62104. faceVertices.push(extractDecalVector3(index));
  62105. faceVertices.push(extractDecalVector3(index + 1));
  62106. faceVertices.push(extractDecalVector3(index + 2));
  62107. // Clip
  62108. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62109. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62110. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62111. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62112. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62113. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62114. if (faceVertices.length === 0) {
  62115. continue;
  62116. }
  62117. // Add UVs and get back to world
  62118. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62119. var vertex = faceVertices[vIndex];
  62120. //TODO check for Int32Array | Uint32Array | Uint16Array
  62121. vertexData.indices.push(currentVertexDataIndex);
  62122. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62123. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62124. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62125. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62126. currentVertexDataIndex++;
  62127. }
  62128. }
  62129. // Return mesh
  62130. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62131. vertexData.applyToMesh(decal);
  62132. decal.position = position.clone();
  62133. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62134. return decal;
  62135. };
  62136. // Privates
  62137. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62138. // extrusion geometry
  62139. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62140. var tangents = path3D.getTangents();
  62141. var normals = path3D.getNormals();
  62142. var binormals = path3D.getBinormals();
  62143. var distances = path3D.getDistances();
  62144. var angle = 0;
  62145. var returnScale = function () { return scale !== null ? scale : 1; };
  62146. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62147. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62148. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62149. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62150. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62151. for (var i = 0; i < curve.length; i++) {
  62152. var shapePath = new Array();
  62153. var angleStep = rotate(i, distances[i]);
  62154. var scaleRatio = scl(i, distances[i]);
  62155. for (var p = 0; p < shape.length; p++) {
  62156. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62157. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62158. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62159. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62160. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62161. shapePath[p] = rotated;
  62162. }
  62163. shapePaths[index] = shapePath;
  62164. angle += angleStep;
  62165. index++;
  62166. }
  62167. // cap
  62168. var capPath = function (shapePath) {
  62169. var pointCap = Array();
  62170. var barycenter = BABYLON.Vector3.Zero();
  62171. var i;
  62172. for (i = 0; i < shapePath.length; i++) {
  62173. barycenter.addInPlace(shapePath[i]);
  62174. }
  62175. barycenter.scaleInPlace(1.0 / shapePath.length);
  62176. for (i = 0; i < shapePath.length; i++) {
  62177. pointCap.push(barycenter);
  62178. }
  62179. return pointCap;
  62180. };
  62181. switch (cap) {
  62182. case BABYLON.Mesh.NO_CAP:
  62183. break;
  62184. case BABYLON.Mesh.CAP_START:
  62185. shapePaths[0] = capPath(shapePaths[2]);
  62186. shapePaths[1] = shapePaths[2];
  62187. break;
  62188. case BABYLON.Mesh.CAP_END:
  62189. shapePaths[index] = shapePaths[index - 1];
  62190. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62191. break;
  62192. case BABYLON.Mesh.CAP_ALL:
  62193. shapePaths[0] = capPath(shapePaths[2]);
  62194. shapePaths[1] = shapePaths[2];
  62195. shapePaths[index] = shapePaths[index - 1];
  62196. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62197. break;
  62198. default:
  62199. break;
  62200. }
  62201. return shapePaths;
  62202. };
  62203. var path3D;
  62204. var pathArray;
  62205. if (instance) { // instance update
  62206. path3D = (instance.path3D).update(curve);
  62207. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62208. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62209. return instance;
  62210. }
  62211. // extruded shape creation
  62212. path3D = new BABYLON.Path3D(curve);
  62213. var newShapePaths = new Array();
  62214. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62215. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62216. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62217. extrudedGeneric.pathArray = pathArray;
  62218. extrudedGeneric.path3D = path3D;
  62219. extrudedGeneric.cap = cap;
  62220. return extrudedGeneric;
  62221. };
  62222. return MeshBuilder;
  62223. }());
  62224. BABYLON.MeshBuilder = MeshBuilder;
  62225. })(BABYLON || (BABYLON = {}));
  62226. //# sourceMappingURL=babylon.meshBuilder.js.map
  62227. var BABYLON;
  62228. (function (BABYLON) {
  62229. /**
  62230. * Draco compression (https://google.github.io/draco/)
  62231. *
  62232. * This class wraps the Draco module.
  62233. *
  62234. * **Encoder**
  62235. *
  62236. * The encoder is not currently implemented.
  62237. *
  62238. * **Decoder**
  62239. *
  62240. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62241. *
  62242. * To update the configuration, use the following code:
  62243. * ```javascript
  62244. * BABYLON.DracoCompression.Configuration = {
  62245. * decoder: {
  62246. * wasmUrl: "<url to the WebAssembly library>",
  62247. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62248. * fallbackUrl: "<url to the fallback JavaScript library>",
  62249. * }
  62250. * };
  62251. * ```
  62252. *
  62253. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62254. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62255. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62256. *
  62257. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62258. * ```javascript
  62259. * var dracoCompression = new BABYLON.DracoCompression();
  62260. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62261. * [BABYLON.VertexBuffer.PositionKind]: 0
  62262. * });
  62263. * ```
  62264. *
  62265. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62266. */
  62267. var DracoCompression = /** @class */ (function () {
  62268. /**
  62269. * Constructor
  62270. */
  62271. function DracoCompression() {
  62272. }
  62273. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62274. /**
  62275. * Returns true if the decoder is available.
  62276. */
  62277. get: function () {
  62278. if (typeof DracoDecoderModule !== "undefined") {
  62279. return true;
  62280. }
  62281. var decoder = DracoCompression.Configuration.decoder;
  62282. if (decoder) {
  62283. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62284. return true;
  62285. }
  62286. if (decoder.fallbackUrl) {
  62287. return true;
  62288. }
  62289. }
  62290. return false;
  62291. },
  62292. enumerable: true,
  62293. configurable: true
  62294. });
  62295. /**
  62296. * Stop all async operations and release resources.
  62297. */
  62298. DracoCompression.prototype.dispose = function () {
  62299. };
  62300. /**
  62301. * Decode Draco compressed mesh data to vertex data.
  62302. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62303. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62304. * @returns A promise that resolves with the decoded vertex data
  62305. */
  62306. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62307. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62308. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62309. var module = wrappedModule.module;
  62310. var vertexData = new BABYLON.VertexData();
  62311. var buffer = new module.DecoderBuffer();
  62312. buffer.Init(dataView, dataView.byteLength);
  62313. var decoder = new module.Decoder();
  62314. var geometry;
  62315. var status;
  62316. try {
  62317. var type = decoder.GetEncodedGeometryType(buffer);
  62318. switch (type) {
  62319. case module.TRIANGULAR_MESH:
  62320. geometry = new module.Mesh();
  62321. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62322. break;
  62323. case module.POINT_CLOUD:
  62324. geometry = new module.PointCloud();
  62325. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62326. break;
  62327. default:
  62328. throw new Error("Invalid geometry type " + type);
  62329. }
  62330. if (!status.ok() || !geometry.ptr) {
  62331. throw new Error(status.error_msg());
  62332. }
  62333. var numPoints = geometry.num_points();
  62334. if (type === module.TRIANGULAR_MESH) {
  62335. var numFaces = geometry.num_faces();
  62336. var faceIndices = new module.DracoInt32Array();
  62337. try {
  62338. var indices = new Uint32Array(numFaces * 3);
  62339. for (var i = 0; i < numFaces; i++) {
  62340. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62341. var offset = i * 3;
  62342. indices[offset + 0] = faceIndices.GetValue(0);
  62343. indices[offset + 1] = faceIndices.GetValue(1);
  62344. indices[offset + 2] = faceIndices.GetValue(2);
  62345. }
  62346. vertexData.indices = indices;
  62347. }
  62348. finally {
  62349. module.destroy(faceIndices);
  62350. }
  62351. }
  62352. for (var kind in attributes) {
  62353. var uniqueId = attributes[kind];
  62354. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62355. var dracoData = new module.DracoFloat32Array();
  62356. try {
  62357. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62358. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62359. for (var i = 0; i < babylonData.length; i++) {
  62360. babylonData[i] = dracoData.GetValue(i);
  62361. }
  62362. vertexData.set(babylonData, kind);
  62363. }
  62364. finally {
  62365. module.destroy(dracoData);
  62366. }
  62367. }
  62368. }
  62369. finally {
  62370. if (geometry) {
  62371. module.destroy(geometry);
  62372. }
  62373. module.destroy(decoder);
  62374. module.destroy(buffer);
  62375. }
  62376. return vertexData;
  62377. });
  62378. };
  62379. DracoCompression._GetDecoderModule = function () {
  62380. if (!DracoCompression._DecoderModulePromise) {
  62381. var promise = null;
  62382. var config_1 = {};
  62383. if (typeof DracoDecoderModule !== "undefined") {
  62384. promise = Promise.resolve();
  62385. }
  62386. else {
  62387. var decoder = DracoCompression.Configuration.decoder;
  62388. if (decoder) {
  62389. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62390. promise = Promise.all([
  62391. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62392. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62393. config_1.wasmBinary = data;
  62394. })
  62395. ]);
  62396. }
  62397. else if (decoder.fallbackUrl) {
  62398. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62399. }
  62400. }
  62401. }
  62402. if (!promise) {
  62403. throw new Error("Draco decoder module is not available");
  62404. }
  62405. DracoCompression._DecoderModulePromise = promise.then(function () {
  62406. return new Promise(function (resolve) {
  62407. config_1.onModuleLoaded = function (decoderModule) {
  62408. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62409. resolve({ module: decoderModule });
  62410. };
  62411. DracoDecoderModule(config_1);
  62412. });
  62413. });
  62414. }
  62415. return DracoCompression._DecoderModulePromise;
  62416. };
  62417. DracoCompression._LoadScriptAsync = function (url) {
  62418. return new Promise(function (resolve, reject) {
  62419. BABYLON.Tools.LoadScript(url, function () {
  62420. resolve();
  62421. }, function (message) {
  62422. reject(new Error(message));
  62423. });
  62424. });
  62425. };
  62426. DracoCompression._LoadFileAsync = function (url) {
  62427. return new Promise(function (resolve, reject) {
  62428. BABYLON.Tools.LoadFile(url, function (data) {
  62429. resolve(data);
  62430. }, undefined, undefined, true, function (request, exception) {
  62431. reject(exception);
  62432. });
  62433. });
  62434. };
  62435. /**
  62436. * The configuration. Defaults to the following urls:
  62437. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62438. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62439. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62440. */
  62441. DracoCompression.Configuration = {
  62442. decoder: {
  62443. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62444. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62445. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62446. }
  62447. };
  62448. return DracoCompression;
  62449. }());
  62450. BABYLON.DracoCompression = DracoCompression;
  62451. })(BABYLON || (BABYLON = {}));
  62452. //# sourceMappingURL=babylon.dracoCompression.js.map
  62453. var BABYLON;
  62454. (function (BABYLON) {
  62455. var AudioEngine = /** @class */ (function () {
  62456. function AudioEngine() {
  62457. this._audioContext = null;
  62458. this._audioContextInitialized = false;
  62459. this.canUseWebAudio = false;
  62460. this.WarnedWebAudioUnsupported = false;
  62461. this.unlocked = false;
  62462. this.isMP3supported = false;
  62463. this.isOGGsupported = false;
  62464. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62465. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62466. this.canUseWebAudio = true;
  62467. }
  62468. var audioElem = document.createElement('audio');
  62469. try {
  62470. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62471. this.isMP3supported = true;
  62472. }
  62473. }
  62474. catch (e) {
  62475. // protect error during capability check.
  62476. }
  62477. try {
  62478. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62479. this.isOGGsupported = true;
  62480. }
  62481. }
  62482. catch (e) {
  62483. // protect error during capability check.
  62484. }
  62485. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62486. this._unlockiOSaudio();
  62487. }
  62488. else {
  62489. this.unlocked = true;
  62490. }
  62491. }
  62492. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62493. get: function () {
  62494. if (!this._audioContextInitialized) {
  62495. this._initializeAudioContext();
  62496. }
  62497. return this._audioContext;
  62498. },
  62499. enumerable: true,
  62500. configurable: true
  62501. });
  62502. AudioEngine.prototype._unlockiOSaudio = function () {
  62503. var _this = this;
  62504. var unlockaudio = function () {
  62505. if (!_this.audioContext) {
  62506. return;
  62507. }
  62508. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62509. var source = _this.audioContext.createBufferSource();
  62510. source.buffer = buffer;
  62511. source.connect(_this.audioContext.destination);
  62512. source.start(0);
  62513. setTimeout(function () {
  62514. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62515. _this.unlocked = true;
  62516. window.removeEventListener('touchend', unlockaudio, false);
  62517. if (_this.onAudioUnlocked) {
  62518. _this.onAudioUnlocked();
  62519. }
  62520. }
  62521. }, 0);
  62522. };
  62523. window.addEventListener('touchend', unlockaudio, false);
  62524. };
  62525. AudioEngine.prototype._initializeAudioContext = function () {
  62526. try {
  62527. if (this.canUseWebAudio) {
  62528. this._audioContext = new AudioContext();
  62529. // create a global volume gain node
  62530. this.masterGain = this._audioContext.createGain();
  62531. this.masterGain.gain.value = 1;
  62532. this.masterGain.connect(this._audioContext.destination);
  62533. this._audioContextInitialized = true;
  62534. }
  62535. }
  62536. catch (e) {
  62537. this.canUseWebAudio = false;
  62538. BABYLON.Tools.Error("Web Audio: " + e.message);
  62539. }
  62540. };
  62541. AudioEngine.prototype.dispose = function () {
  62542. if (this.canUseWebAudio && this._audioContextInitialized) {
  62543. if (this._connectedAnalyser && this._audioContext) {
  62544. this._connectedAnalyser.stopDebugCanvas();
  62545. this._connectedAnalyser.dispose();
  62546. this.masterGain.disconnect();
  62547. this.masterGain.connect(this._audioContext.destination);
  62548. this._connectedAnalyser = null;
  62549. }
  62550. this.masterGain.gain.value = 1;
  62551. }
  62552. this.WarnedWebAudioUnsupported = false;
  62553. };
  62554. AudioEngine.prototype.getGlobalVolume = function () {
  62555. if (this.canUseWebAudio && this._audioContextInitialized) {
  62556. return this.masterGain.gain.value;
  62557. }
  62558. else {
  62559. return -1;
  62560. }
  62561. };
  62562. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62563. if (this.canUseWebAudio && this._audioContextInitialized) {
  62564. this.masterGain.gain.value = newVolume;
  62565. }
  62566. };
  62567. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62568. if (this._connectedAnalyser) {
  62569. this._connectedAnalyser.stopDebugCanvas();
  62570. }
  62571. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62572. this._connectedAnalyser = analyser;
  62573. this.masterGain.disconnect();
  62574. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62575. }
  62576. };
  62577. return AudioEngine;
  62578. }());
  62579. BABYLON.AudioEngine = AudioEngine;
  62580. })(BABYLON || (BABYLON = {}));
  62581. //# sourceMappingURL=babylon.audioEngine.js.map
  62582. var BABYLON;
  62583. (function (BABYLON) {
  62584. var Sound = /** @class */ (function () {
  62585. /**
  62586. * Create a sound and attach it to a scene
  62587. * @param name Name of your sound
  62588. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62589. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62590. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62591. */
  62592. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62593. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62594. var _this = this;
  62595. this.autoplay = false;
  62596. this.loop = false;
  62597. this.useCustomAttenuation = false;
  62598. this.spatialSound = false;
  62599. this.refDistance = 1;
  62600. this.rolloffFactor = 1;
  62601. this.maxDistance = 100;
  62602. this.distanceModel = "linear";
  62603. this._panningModel = "equalpower";
  62604. this._playbackRate = 1;
  62605. this._streaming = false;
  62606. this._startTime = 0;
  62607. this._startOffset = 0;
  62608. this._position = BABYLON.Vector3.Zero();
  62609. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62610. this._volume = 1;
  62611. this._isReadyToPlay = false;
  62612. this.isPlaying = false;
  62613. this.isPaused = false;
  62614. this._isDirectional = false;
  62615. // Used if you'd like to create a directional sound.
  62616. // If not set, the sound will be omnidirectional
  62617. this._coneInnerAngle = 360;
  62618. this._coneOuterAngle = 360;
  62619. this._coneOuterGain = 0;
  62620. this._isOutputConnected = false;
  62621. this._urlType = "Unknown";
  62622. this.name = name;
  62623. this._scene = scene;
  62624. this._readyToPlayCallback = readyToPlayCallback;
  62625. // Default custom attenuation function is a linear attenuation
  62626. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62627. if (currentDistance < maxDistance) {
  62628. return currentVolume * (1 - currentDistance / maxDistance);
  62629. }
  62630. else {
  62631. return 0;
  62632. }
  62633. };
  62634. if (options) {
  62635. this.autoplay = options.autoplay || false;
  62636. this.loop = options.loop || false;
  62637. // if volume === 0, we need another way to check this option
  62638. if (options.volume !== undefined) {
  62639. this._volume = options.volume;
  62640. }
  62641. this.spatialSound = options.spatialSound || false;
  62642. this.maxDistance = options.maxDistance || 100;
  62643. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62644. this.rolloffFactor = options.rolloffFactor || 1;
  62645. this.refDistance = options.refDistance || 1;
  62646. this.distanceModel = options.distanceModel || "linear";
  62647. this._playbackRate = options.playbackRate || 1;
  62648. this._streaming = options.streaming || false;
  62649. }
  62650. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62651. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62652. this._soundGain.gain.value = this._volume;
  62653. this._inputAudioNode = this._soundGain;
  62654. this._ouputAudioNode = this._soundGain;
  62655. if (this.spatialSound) {
  62656. this._createSpatialParameters();
  62657. }
  62658. this._scene.mainSoundTrack.AddSound(this);
  62659. var validParameter = true;
  62660. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62661. if (urlOrArrayBuffer) {
  62662. try {
  62663. if (typeof (urlOrArrayBuffer) === "string")
  62664. this._urlType = "String";
  62665. if (Array.isArray(urlOrArrayBuffer))
  62666. this._urlType = "Array";
  62667. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62668. this._urlType = "ArrayBuffer";
  62669. var urls = [];
  62670. var codecSupportedFound = false;
  62671. switch (this._urlType) {
  62672. case "ArrayBuffer":
  62673. if (urlOrArrayBuffer.byteLength > 0) {
  62674. codecSupportedFound = true;
  62675. this._soundLoaded(urlOrArrayBuffer);
  62676. }
  62677. break;
  62678. case "String":
  62679. urls.push(urlOrArrayBuffer);
  62680. case "Array":
  62681. if (urls.length === 0)
  62682. urls = urlOrArrayBuffer;
  62683. // If we found a supported format, we load it immediately and stop the loop
  62684. for (var i = 0; i < urls.length; i++) {
  62685. var url = urls[i];
  62686. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62687. codecSupportedFound = true;
  62688. }
  62689. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62690. codecSupportedFound = true;
  62691. }
  62692. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62693. codecSupportedFound = true;
  62694. }
  62695. if (url.indexOf("blob:") !== -1) {
  62696. codecSupportedFound = true;
  62697. }
  62698. if (codecSupportedFound) {
  62699. // Loading sound using XHR2
  62700. if (!this._streaming) {
  62701. this._scene._loadFile(url, function (data) {
  62702. _this._soundLoaded(data);
  62703. }, undefined, true, true, function (exception) {
  62704. if (exception) {
  62705. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62706. }
  62707. BABYLON.Tools.Error("Sound creation aborted.");
  62708. _this._scene.mainSoundTrack.RemoveSound(_this);
  62709. });
  62710. }
  62711. // Streaming sound using HTML5 Audio tag
  62712. else {
  62713. this._htmlAudioElement = new Audio(url);
  62714. this._htmlAudioElement.controls = false;
  62715. this._htmlAudioElement.loop = this.loop;
  62716. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62717. this._htmlAudioElement.preload = "auto";
  62718. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62719. _this._isReadyToPlay = true;
  62720. if (_this.autoplay) {
  62721. _this.play();
  62722. }
  62723. if (_this._readyToPlayCallback) {
  62724. _this._readyToPlayCallback();
  62725. }
  62726. });
  62727. document.body.appendChild(this._htmlAudioElement);
  62728. }
  62729. break;
  62730. }
  62731. }
  62732. break;
  62733. default:
  62734. validParameter = false;
  62735. break;
  62736. }
  62737. if (!validParameter) {
  62738. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62739. }
  62740. else {
  62741. if (!codecSupportedFound) {
  62742. this._isReadyToPlay = true;
  62743. // Simulating a ready to play event to avoid breaking code path
  62744. if (this._readyToPlayCallback) {
  62745. window.setTimeout(function () {
  62746. if (_this._readyToPlayCallback) {
  62747. _this._readyToPlayCallback();
  62748. }
  62749. }, 1000);
  62750. }
  62751. }
  62752. }
  62753. }
  62754. catch (ex) {
  62755. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62756. this._scene.mainSoundTrack.RemoveSound(this);
  62757. }
  62758. }
  62759. }
  62760. else {
  62761. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62762. this._scene.mainSoundTrack.AddSound(this);
  62763. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62764. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62765. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62766. }
  62767. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62768. if (this._readyToPlayCallback) {
  62769. window.setTimeout(function () {
  62770. if (_this._readyToPlayCallback) {
  62771. _this._readyToPlayCallback();
  62772. }
  62773. }, 1000);
  62774. }
  62775. }
  62776. }
  62777. Sound.prototype.dispose = function () {
  62778. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62779. if (this.isPlaying) {
  62780. this.stop();
  62781. }
  62782. this._isReadyToPlay = false;
  62783. if (this.soundTrackId === -1) {
  62784. this._scene.mainSoundTrack.RemoveSound(this);
  62785. }
  62786. else {
  62787. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62788. }
  62789. if (this._soundGain) {
  62790. this._soundGain.disconnect();
  62791. this._soundGain = null;
  62792. }
  62793. if (this._soundPanner) {
  62794. this._soundPanner.disconnect();
  62795. this._soundPanner = null;
  62796. }
  62797. if (this._soundSource) {
  62798. this._soundSource.disconnect();
  62799. this._soundSource = null;
  62800. }
  62801. this._audioBuffer = null;
  62802. if (this._htmlAudioElement) {
  62803. this._htmlAudioElement.pause();
  62804. this._htmlAudioElement.src = "";
  62805. document.body.removeChild(this._htmlAudioElement);
  62806. }
  62807. if (this._connectedMesh && this._registerFunc) {
  62808. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62809. this._connectedMesh = null;
  62810. }
  62811. }
  62812. };
  62813. Sound.prototype.isReady = function () {
  62814. return this._isReadyToPlay;
  62815. };
  62816. Sound.prototype._soundLoaded = function (audioData) {
  62817. var _this = this;
  62818. if (!BABYLON.Engine.audioEngine.audioContext) {
  62819. return;
  62820. }
  62821. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62822. _this._audioBuffer = buffer;
  62823. _this._isReadyToPlay = true;
  62824. if (_this.autoplay) {
  62825. _this.play();
  62826. }
  62827. if (_this._readyToPlayCallback) {
  62828. _this._readyToPlayCallback();
  62829. }
  62830. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62831. };
  62832. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62833. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62834. this._audioBuffer = audioBuffer;
  62835. this._isReadyToPlay = true;
  62836. }
  62837. };
  62838. Sound.prototype.updateOptions = function (options) {
  62839. if (options) {
  62840. this.loop = options.loop || this.loop;
  62841. this.maxDistance = options.maxDistance || this.maxDistance;
  62842. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62843. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62844. this.refDistance = options.refDistance || this.refDistance;
  62845. this.distanceModel = options.distanceModel || this.distanceModel;
  62846. this._playbackRate = options.playbackRate || this._playbackRate;
  62847. this._updateSpatialParameters();
  62848. if (this.isPlaying) {
  62849. if (this._streaming) {
  62850. this._htmlAudioElement.playbackRate = this._playbackRate;
  62851. }
  62852. else {
  62853. if (this._soundSource) {
  62854. this._soundSource.playbackRate.value = this._playbackRate;
  62855. }
  62856. }
  62857. }
  62858. }
  62859. };
  62860. Sound.prototype._createSpatialParameters = function () {
  62861. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62862. if (this._scene.headphone) {
  62863. this._panningModel = "HRTF";
  62864. }
  62865. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62866. this._updateSpatialParameters();
  62867. this._soundPanner.connect(this._ouputAudioNode);
  62868. this._inputAudioNode = this._soundPanner;
  62869. }
  62870. };
  62871. Sound.prototype._updateSpatialParameters = function () {
  62872. if (this.spatialSound && this._soundPanner) {
  62873. if (this.useCustomAttenuation) {
  62874. // Tricks to disable in a way embedded Web Audio attenuation
  62875. this._soundPanner.distanceModel = "linear";
  62876. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62877. this._soundPanner.refDistance = 1;
  62878. this._soundPanner.rolloffFactor = 1;
  62879. this._soundPanner.panningModel = this._panningModel;
  62880. }
  62881. else {
  62882. this._soundPanner.distanceModel = this.distanceModel;
  62883. this._soundPanner.maxDistance = this.maxDistance;
  62884. this._soundPanner.refDistance = this.refDistance;
  62885. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62886. this._soundPanner.panningModel = this._panningModel;
  62887. }
  62888. }
  62889. };
  62890. Sound.prototype.switchPanningModelToHRTF = function () {
  62891. this._panningModel = "HRTF";
  62892. this._switchPanningModel();
  62893. };
  62894. Sound.prototype.switchPanningModelToEqualPower = function () {
  62895. this._panningModel = "equalpower";
  62896. this._switchPanningModel();
  62897. };
  62898. Sound.prototype._switchPanningModel = function () {
  62899. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62900. this._soundPanner.panningModel = this._panningModel;
  62901. }
  62902. };
  62903. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62905. if (this._isOutputConnected) {
  62906. this._ouputAudioNode.disconnect();
  62907. }
  62908. this._ouputAudioNode.connect(soundTrackAudioNode);
  62909. this._isOutputConnected = true;
  62910. }
  62911. };
  62912. /**
  62913. * Transform this sound into a directional source
  62914. * @param coneInnerAngle Size of the inner cone in degree
  62915. * @param coneOuterAngle Size of the outer cone in degree
  62916. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62917. */
  62918. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62919. if (coneOuterAngle < coneInnerAngle) {
  62920. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62921. return;
  62922. }
  62923. this._coneInnerAngle = coneInnerAngle;
  62924. this._coneOuterAngle = coneOuterAngle;
  62925. this._coneOuterGain = coneOuterGain;
  62926. this._isDirectional = true;
  62927. if (this.isPlaying && this.loop) {
  62928. this.stop();
  62929. this.play();
  62930. }
  62931. };
  62932. Sound.prototype.setPosition = function (newPosition) {
  62933. this._position = newPosition;
  62934. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62935. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62936. }
  62937. };
  62938. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62939. this._localDirection = newLocalDirection;
  62940. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62941. this._updateDirection();
  62942. }
  62943. };
  62944. Sound.prototype._updateDirection = function () {
  62945. if (!this._connectedMesh || !this._soundPanner) {
  62946. return;
  62947. }
  62948. var mat = this._connectedMesh.getWorldMatrix();
  62949. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62950. direction.normalize();
  62951. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62952. };
  62953. Sound.prototype.updateDistanceFromListener = function () {
  62954. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62955. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62956. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62957. }
  62958. };
  62959. Sound.prototype.setAttenuationFunction = function (callback) {
  62960. this._customAttenuationFunction = callback;
  62961. };
  62962. /**
  62963. * Play the sound
  62964. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62965. * @param offset (optional) Start the sound setting it at a specific time
  62966. */
  62967. Sound.prototype.play = function (time, offset) {
  62968. var _this = this;
  62969. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62970. try {
  62971. if (this._startOffset < 0) {
  62972. time = -this._startOffset;
  62973. this._startOffset = 0;
  62974. }
  62975. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62976. if (!this._soundSource || !this._streamingSource) {
  62977. if (this.spatialSound && this._soundPanner) {
  62978. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62979. if (this._isDirectional) {
  62980. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62981. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62982. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62983. if (this._connectedMesh) {
  62984. this._updateDirection();
  62985. }
  62986. else {
  62987. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62988. }
  62989. }
  62990. }
  62991. }
  62992. if (this._streaming) {
  62993. if (!this._streamingSource) {
  62994. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62995. this._htmlAudioElement.onended = function () { _this._onended(); };
  62996. this._htmlAudioElement.playbackRate = this._playbackRate;
  62997. }
  62998. this._streamingSource.disconnect();
  62999. this._streamingSource.connect(this._inputAudioNode);
  63000. this._htmlAudioElement.play();
  63001. }
  63002. else {
  63003. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63004. this._soundSource.buffer = this._audioBuffer;
  63005. this._soundSource.connect(this._inputAudioNode);
  63006. this._soundSource.loop = this.loop;
  63007. this._soundSource.playbackRate.value = this._playbackRate;
  63008. this._soundSource.onended = function () { _this._onended(); };
  63009. if (this._soundSource.buffer) {
  63010. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63011. }
  63012. }
  63013. this._startTime = startTime;
  63014. this.isPlaying = true;
  63015. this.isPaused = false;
  63016. }
  63017. catch (ex) {
  63018. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63019. }
  63020. }
  63021. };
  63022. Sound.prototype._onended = function () {
  63023. this.isPlaying = false;
  63024. if (this.onended) {
  63025. this.onended();
  63026. }
  63027. };
  63028. /**
  63029. * Stop the sound
  63030. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63031. */
  63032. Sound.prototype.stop = function (time) {
  63033. if (this.isPlaying) {
  63034. if (this._streaming) {
  63035. this._htmlAudioElement.pause();
  63036. // Test needed for Firefox or it will generate an Invalid State Error
  63037. if (this._htmlAudioElement.currentTime > 0) {
  63038. this._htmlAudioElement.currentTime = 0;
  63039. }
  63040. }
  63041. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63042. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63043. this._soundSource.stop(stopTime);
  63044. this._soundSource.onended = function () { };
  63045. if (!this.isPaused) {
  63046. this._startOffset = 0;
  63047. }
  63048. }
  63049. this.isPlaying = false;
  63050. }
  63051. };
  63052. Sound.prototype.pause = function () {
  63053. if (this.isPlaying) {
  63054. this.isPaused = true;
  63055. if (this._streaming) {
  63056. this._htmlAudioElement.pause();
  63057. }
  63058. else if (BABYLON.Engine.audioEngine.audioContext) {
  63059. this.stop(0);
  63060. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63061. }
  63062. }
  63063. };
  63064. Sound.prototype.setVolume = function (newVolume, time) {
  63065. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63066. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63067. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63068. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63069. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63070. }
  63071. else {
  63072. this._soundGain.gain.value = newVolume;
  63073. }
  63074. }
  63075. this._volume = newVolume;
  63076. };
  63077. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63078. this._playbackRate = newPlaybackRate;
  63079. if (this.isPlaying) {
  63080. if (this._streaming) {
  63081. this._htmlAudioElement.playbackRate = this._playbackRate;
  63082. }
  63083. else if (this._soundSource) {
  63084. this._soundSource.playbackRate.value = this._playbackRate;
  63085. }
  63086. }
  63087. };
  63088. Sound.prototype.getVolume = function () {
  63089. return this._volume;
  63090. };
  63091. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63092. var _this = this;
  63093. if (this._connectedMesh && this._registerFunc) {
  63094. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63095. this._registerFunc = null;
  63096. }
  63097. this._connectedMesh = meshToConnectTo;
  63098. if (!this.spatialSound) {
  63099. this.spatialSound = true;
  63100. this._createSpatialParameters();
  63101. if (this.isPlaying && this.loop) {
  63102. this.stop();
  63103. this.play();
  63104. }
  63105. }
  63106. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63107. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63108. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63109. };
  63110. Sound.prototype.detachFromMesh = function () {
  63111. if (this._connectedMesh && this._registerFunc) {
  63112. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63113. this._registerFunc = null;
  63114. this._connectedMesh = null;
  63115. }
  63116. };
  63117. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63118. if (!node.getBoundingInfo) {
  63119. return;
  63120. }
  63121. var mesh = node;
  63122. var boundingInfo = mesh.getBoundingInfo();
  63123. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63124. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63125. this._updateDirection();
  63126. }
  63127. };
  63128. Sound.prototype.clone = function () {
  63129. var _this = this;
  63130. if (!this._streaming) {
  63131. var setBufferAndRun = function () {
  63132. if (_this._isReadyToPlay) {
  63133. clonedSound._audioBuffer = _this.getAudioBuffer();
  63134. clonedSound._isReadyToPlay = true;
  63135. if (clonedSound.autoplay) {
  63136. clonedSound.play();
  63137. }
  63138. }
  63139. else {
  63140. window.setTimeout(setBufferAndRun, 300);
  63141. }
  63142. };
  63143. var currentOptions = {
  63144. autoplay: this.autoplay, loop: this.loop,
  63145. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63146. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63147. refDistance: this.refDistance, distanceModel: this.distanceModel
  63148. };
  63149. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63150. if (this.useCustomAttenuation) {
  63151. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63152. }
  63153. clonedSound.setPosition(this._position);
  63154. clonedSound.setPlaybackRate(this._playbackRate);
  63155. setBufferAndRun();
  63156. return clonedSound;
  63157. }
  63158. // Can't clone a streaming sound
  63159. else {
  63160. return null;
  63161. }
  63162. };
  63163. Sound.prototype.getAudioBuffer = function () {
  63164. return this._audioBuffer;
  63165. };
  63166. Sound.prototype.serialize = function () {
  63167. var serializationObject = {
  63168. name: this.name,
  63169. url: this.name,
  63170. autoplay: this.autoplay,
  63171. loop: this.loop,
  63172. volume: this._volume,
  63173. spatialSound: this.spatialSound,
  63174. maxDistance: this.maxDistance,
  63175. rolloffFactor: this.rolloffFactor,
  63176. refDistance: this.refDistance,
  63177. distanceModel: this.distanceModel,
  63178. playbackRate: this._playbackRate,
  63179. panningModel: this._panningModel,
  63180. soundTrackId: this.soundTrackId
  63181. };
  63182. if (this.spatialSound) {
  63183. if (this._connectedMesh)
  63184. serializationObject.connectedMeshId = this._connectedMesh.id;
  63185. serializationObject.position = this._position.asArray();
  63186. serializationObject.refDistance = this.refDistance;
  63187. serializationObject.distanceModel = this.distanceModel;
  63188. serializationObject.isDirectional = this._isDirectional;
  63189. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63190. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63191. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63192. serializationObject.coneOuterGain = this._coneOuterGain;
  63193. }
  63194. return serializationObject;
  63195. };
  63196. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63197. var soundName = parsedSound.name;
  63198. var soundUrl;
  63199. if (parsedSound.url) {
  63200. soundUrl = rootUrl + parsedSound.url;
  63201. }
  63202. else {
  63203. soundUrl = rootUrl + soundName;
  63204. }
  63205. var options = {
  63206. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63207. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63208. rolloffFactor: parsedSound.rolloffFactor,
  63209. refDistance: parsedSound.refDistance,
  63210. distanceModel: parsedSound.distanceModel,
  63211. playbackRate: parsedSound.playbackRate
  63212. };
  63213. var newSound;
  63214. if (!sourceSound) {
  63215. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63216. scene._addPendingData(newSound);
  63217. }
  63218. else {
  63219. var setBufferAndRun = function () {
  63220. if (sourceSound._isReadyToPlay) {
  63221. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63222. newSound._isReadyToPlay = true;
  63223. if (newSound.autoplay) {
  63224. newSound.play();
  63225. }
  63226. }
  63227. else {
  63228. window.setTimeout(setBufferAndRun, 300);
  63229. }
  63230. };
  63231. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63232. setBufferAndRun();
  63233. }
  63234. if (parsedSound.position) {
  63235. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63236. newSound.setPosition(soundPosition);
  63237. }
  63238. if (parsedSound.isDirectional) {
  63239. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63240. if (parsedSound.localDirectionToMesh) {
  63241. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63242. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63243. }
  63244. }
  63245. if (parsedSound.connectedMeshId) {
  63246. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63247. if (connectedMesh) {
  63248. newSound.attachToMesh(connectedMesh);
  63249. }
  63250. }
  63251. return newSound;
  63252. };
  63253. return Sound;
  63254. }());
  63255. BABYLON.Sound = Sound;
  63256. })(BABYLON || (BABYLON = {}));
  63257. //# sourceMappingURL=babylon.sound.js.map
  63258. var BABYLON;
  63259. (function (BABYLON) {
  63260. var SoundTrack = /** @class */ (function () {
  63261. function SoundTrack(scene, options) {
  63262. this.id = -1;
  63263. this._isMainTrack = false;
  63264. this._isInitialized = false;
  63265. this._scene = scene;
  63266. this.soundCollection = new Array();
  63267. this._options = options;
  63268. if (!this._isMainTrack) {
  63269. this._scene.soundTracks.push(this);
  63270. this.id = this._scene.soundTracks.length - 1;
  63271. }
  63272. }
  63273. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63274. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63275. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63276. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63277. if (this._options) {
  63278. if (this._options.volume) {
  63279. this._outputAudioNode.gain.value = this._options.volume;
  63280. }
  63281. if (this._options.mainTrack) {
  63282. this._isMainTrack = this._options.mainTrack;
  63283. }
  63284. }
  63285. this._isInitialized = true;
  63286. }
  63287. };
  63288. SoundTrack.prototype.dispose = function () {
  63289. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63290. if (this._connectedAnalyser) {
  63291. this._connectedAnalyser.stopDebugCanvas();
  63292. }
  63293. while (this.soundCollection.length) {
  63294. this.soundCollection[0].dispose();
  63295. }
  63296. if (this._outputAudioNode) {
  63297. this._outputAudioNode.disconnect();
  63298. }
  63299. this._outputAudioNode = null;
  63300. }
  63301. };
  63302. SoundTrack.prototype.AddSound = function (sound) {
  63303. if (!this._isInitialized) {
  63304. this._initializeSoundTrackAudioGraph();
  63305. }
  63306. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63307. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63308. }
  63309. if (sound.soundTrackId) {
  63310. if (sound.soundTrackId === -1) {
  63311. this._scene.mainSoundTrack.RemoveSound(sound);
  63312. }
  63313. else {
  63314. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63315. }
  63316. }
  63317. this.soundCollection.push(sound);
  63318. sound.soundTrackId = this.id;
  63319. };
  63320. SoundTrack.prototype.RemoveSound = function (sound) {
  63321. var index = this.soundCollection.indexOf(sound);
  63322. if (index !== -1) {
  63323. this.soundCollection.splice(index, 1);
  63324. }
  63325. };
  63326. SoundTrack.prototype.setVolume = function (newVolume) {
  63327. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63328. this._outputAudioNode.gain.value = newVolume;
  63329. }
  63330. };
  63331. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63332. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63333. for (var i = 0; i < this.soundCollection.length; i++) {
  63334. this.soundCollection[i].switchPanningModelToHRTF();
  63335. }
  63336. }
  63337. };
  63338. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63339. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63340. for (var i = 0; i < this.soundCollection.length; i++) {
  63341. this.soundCollection[i].switchPanningModelToEqualPower();
  63342. }
  63343. }
  63344. };
  63345. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63346. if (this._connectedAnalyser) {
  63347. this._connectedAnalyser.stopDebugCanvas();
  63348. }
  63349. this._connectedAnalyser = analyser;
  63350. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63351. this._outputAudioNode.disconnect();
  63352. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63353. }
  63354. };
  63355. return SoundTrack;
  63356. }());
  63357. BABYLON.SoundTrack = SoundTrack;
  63358. })(BABYLON || (BABYLON = {}));
  63359. //# sourceMappingURL=babylon.soundtrack.js.map
  63360. var BABYLON;
  63361. (function (BABYLON) {
  63362. /**
  63363. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63364. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63365. */
  63366. var Analyser = /** @class */ (function () {
  63367. /**
  63368. * Creates a new analyser
  63369. * @param scene defines hosting scene
  63370. */
  63371. function Analyser(scene) {
  63372. /**
  63373. * Gets or sets the smoothing
  63374. * @ignorenaming
  63375. */
  63376. this.SMOOTHING = 0.75;
  63377. /**
  63378. * Gets or sets the FFT table size
  63379. * @ignorenaming
  63380. */
  63381. this.FFT_SIZE = 512;
  63382. /**
  63383. * Gets or sets the bar graph amplitude
  63384. * @ignorenaming
  63385. */
  63386. this.BARGRAPHAMPLITUDE = 256;
  63387. /**
  63388. * Gets or sets the position of the debug canvas
  63389. * @ignorenaming
  63390. */
  63391. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63392. /**
  63393. * Gets or sets the debug canvas size
  63394. * @ignorenaming
  63395. */
  63396. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63397. this._scene = scene;
  63398. this._audioEngine = BABYLON.Engine.audioEngine;
  63399. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63400. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63401. this._webAudioAnalyser.minDecibels = -140;
  63402. this._webAudioAnalyser.maxDecibels = 0;
  63403. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63404. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63405. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63406. }
  63407. }
  63408. /**
  63409. * Get the number of data values you will have to play with for the visualization
  63410. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63411. * @returns a number
  63412. */
  63413. Analyser.prototype.getFrequencyBinCount = function () {
  63414. if (this._audioEngine.canUseWebAudio) {
  63415. return this._webAudioAnalyser.frequencyBinCount;
  63416. }
  63417. else {
  63418. return 0;
  63419. }
  63420. };
  63421. /**
  63422. * Gets the current frequency data as a byte array
  63423. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63424. * @returns a Uint8Array
  63425. */
  63426. Analyser.prototype.getByteFrequencyData = function () {
  63427. if (this._audioEngine.canUseWebAudio) {
  63428. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63429. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63430. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63431. }
  63432. return this._byteFreqs;
  63433. };
  63434. /**
  63435. * Gets the current waveform as a byte array
  63436. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63437. * @returns a Uint8Array
  63438. */
  63439. Analyser.prototype.getByteTimeDomainData = function () {
  63440. if (this._audioEngine.canUseWebAudio) {
  63441. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63442. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63443. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63444. }
  63445. return this._byteTime;
  63446. };
  63447. /**
  63448. * Gets the current frequency data as a float array
  63449. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63450. * @returns a Float32Array
  63451. */
  63452. Analyser.prototype.getFloatFrequencyData = function () {
  63453. if (this._audioEngine.canUseWebAudio) {
  63454. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63455. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63456. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63457. }
  63458. return this._floatFreqs;
  63459. };
  63460. /**
  63461. * Renders the debug canvas
  63462. */
  63463. Analyser.prototype.drawDebugCanvas = function () {
  63464. var _this = this;
  63465. if (this._audioEngine.canUseWebAudio) {
  63466. if (!this._debugCanvas) {
  63467. this._debugCanvas = document.createElement("canvas");
  63468. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63469. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63470. this._debugCanvas.style.position = "absolute";
  63471. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63472. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63473. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63474. document.body.appendChild(this._debugCanvas);
  63475. this._registerFunc = function () {
  63476. _this.drawDebugCanvas();
  63477. };
  63478. this._scene.registerBeforeRender(this._registerFunc);
  63479. }
  63480. if (this._registerFunc && this._debugCanvasContext) {
  63481. var workingArray = this.getByteFrequencyData();
  63482. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63483. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63484. // Draw the frequency domain chart.
  63485. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63486. var value = workingArray[i];
  63487. var percent = value / this.BARGRAPHAMPLITUDE;
  63488. var height = this.DEBUGCANVASSIZE.height * percent;
  63489. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63490. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63491. var hue = i / this.getFrequencyBinCount() * 360;
  63492. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63493. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63494. }
  63495. }
  63496. }
  63497. };
  63498. /**
  63499. * Stops rendering the debug canvas and removes it
  63500. */
  63501. Analyser.prototype.stopDebugCanvas = function () {
  63502. if (this._debugCanvas) {
  63503. if (this._registerFunc) {
  63504. this._scene.unregisterBeforeRender(this._registerFunc);
  63505. this._registerFunc = null;
  63506. }
  63507. document.body.removeChild(this._debugCanvas);
  63508. this._debugCanvas = null;
  63509. this._debugCanvasContext = null;
  63510. }
  63511. };
  63512. /**
  63513. * Connects two audio nodes
  63514. * @param inputAudioNode defines first node to connect
  63515. * @param outputAudioNode defines second node to connect
  63516. */
  63517. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63518. if (this._audioEngine.canUseWebAudio) {
  63519. inputAudioNode.connect(this._webAudioAnalyser);
  63520. this._webAudioAnalyser.connect(outputAudioNode);
  63521. }
  63522. };
  63523. /**
  63524. * Releases all associated resources
  63525. */
  63526. Analyser.prototype.dispose = function () {
  63527. if (this._audioEngine.canUseWebAudio) {
  63528. this._webAudioAnalyser.disconnect();
  63529. }
  63530. };
  63531. return Analyser;
  63532. }());
  63533. BABYLON.Analyser = Analyser;
  63534. })(BABYLON || (BABYLON = {}));
  63535. //# sourceMappingURL=babylon.analyser.js.map
  63536. var BABYLON;
  63537. (function (BABYLON) {
  63538. var CubeTexture = /** @class */ (function (_super) {
  63539. __extends(CubeTexture, _super);
  63540. /**
  63541. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63542. * as prefiltered data.
  63543. * @param rootUrl defines the url of the texture or the root name of the six images
  63544. * @param scene defines the scene the texture is attached to
  63545. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63546. * @param noMipmap defines if mipmaps should be created or not
  63547. * @param files defines the six files to load for the different faces
  63548. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63549. * @param onError defines a callback triggered in case of error during load
  63550. * @param format defines the internal format to use for the texture once loaded
  63551. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63552. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63553. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63554. * @return the cube texture
  63555. */
  63556. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63557. if (extensions === void 0) { extensions = null; }
  63558. if (noMipmap === void 0) { noMipmap = false; }
  63559. if (files === void 0) { files = null; }
  63560. if (onLoad === void 0) { onLoad = null; }
  63561. if (onError === void 0) { onError = null; }
  63562. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63563. if (prefiltered === void 0) { prefiltered = false; }
  63564. if (forcedExtension === void 0) { forcedExtension = null; }
  63565. if (createPolynomials === void 0) { createPolynomials = false; }
  63566. var _this = _super.call(this, scene) || this;
  63567. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63568. /**
  63569. * Gets or sets the center of the bounding box associated with the cube texture
  63570. * It must define where the camera used to render the texture was set
  63571. */
  63572. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63573. _this._rotationY = 0;
  63574. _this.name = rootUrl;
  63575. _this.url = rootUrl;
  63576. _this._noMipmap = noMipmap;
  63577. _this.hasAlpha = false;
  63578. _this._format = format;
  63579. _this._prefiltered = prefiltered;
  63580. _this.isCube = true;
  63581. _this._textureMatrix = BABYLON.Matrix.Identity();
  63582. _this._createPolynomials = createPolynomials;
  63583. if (prefiltered) {
  63584. _this.gammaSpace = false;
  63585. }
  63586. if (!rootUrl && !files) {
  63587. return _this;
  63588. }
  63589. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63590. var lastDot = rootUrl.lastIndexOf(".");
  63591. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63592. var isDDS = (extension === ".dds");
  63593. if (!files) {
  63594. if (!isDDS && !extensions) {
  63595. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63596. }
  63597. files = [];
  63598. if (extensions) {
  63599. for (var index = 0; index < extensions.length; index++) {
  63600. files.push(rootUrl + extensions[index]);
  63601. }
  63602. }
  63603. }
  63604. _this._files = files;
  63605. if (!_this._texture) {
  63606. if (!scene.useDelayedTextureLoading) {
  63607. if (prefiltered) {
  63608. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63609. }
  63610. else {
  63611. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63612. }
  63613. }
  63614. else {
  63615. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63616. }
  63617. }
  63618. else if (onLoad) {
  63619. if (_this._texture.isReady) {
  63620. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63621. }
  63622. else {
  63623. _this._texture.onLoadedObservable.add(onLoad);
  63624. }
  63625. }
  63626. return _this;
  63627. }
  63628. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63629. get: function () {
  63630. return this._boundingBoxSize;
  63631. },
  63632. /**
  63633. * Gets or sets the size of the bounding box associated with the cube texture
  63634. * When defined, the cubemap will switch to local mode
  63635. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63636. * @example https://www.babylonjs-playground.com/#RNASML
  63637. */
  63638. set: function (value) {
  63639. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63640. return;
  63641. }
  63642. this._boundingBoxSize = value;
  63643. var scene = this.getScene();
  63644. if (scene) {
  63645. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63646. }
  63647. },
  63648. enumerable: true,
  63649. configurable: true
  63650. });
  63651. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63652. /**
  63653. * Gets texture matrix rotation angle around Y axis radians.
  63654. */
  63655. get: function () {
  63656. return this._rotationY;
  63657. },
  63658. /**
  63659. * Sets texture matrix rotation angle around Y axis in radians.
  63660. */
  63661. set: function (value) {
  63662. this._rotationY = value;
  63663. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63664. },
  63665. enumerable: true,
  63666. configurable: true
  63667. });
  63668. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63669. var rootUrlKey = "";
  63670. files.forEach(function (url) { return rootUrlKey += url; });
  63671. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63672. };
  63673. /**
  63674. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63675. * @param url defines the url of the prefiltered texture
  63676. * @param scene defines the scene the texture is attached to
  63677. * @param forcedExtension defines the extension of the file if different from the url
  63678. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63679. * @return the prefiltered texture
  63680. */
  63681. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63682. if (forcedExtension === void 0) { forcedExtension = null; }
  63683. if (createPolynomials === void 0) { createPolynomials = true; }
  63684. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63685. };
  63686. // Methods
  63687. CubeTexture.prototype.delayLoad = function () {
  63688. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63689. return;
  63690. }
  63691. var scene = this.getScene();
  63692. if (!scene) {
  63693. return;
  63694. }
  63695. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63696. this._texture = this._getFromCache(this.url, this._noMipmap);
  63697. if (!this._texture) {
  63698. if (this._prefiltered) {
  63699. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63700. }
  63701. else {
  63702. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63703. }
  63704. }
  63705. };
  63706. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63707. return this._textureMatrix;
  63708. };
  63709. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63710. this._textureMatrix = value;
  63711. };
  63712. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63713. var texture = BABYLON.SerializationHelper.Parse(function () {
  63714. var prefiltered = false;
  63715. if (parsedTexture.prefiltered) {
  63716. prefiltered = parsedTexture.prefiltered;
  63717. }
  63718. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63719. }, parsedTexture, scene);
  63720. // Local Cubemaps
  63721. if (parsedTexture.boundingBoxPosition) {
  63722. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63723. }
  63724. if (parsedTexture.boundingBoxSize) {
  63725. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63726. }
  63727. // Animations
  63728. if (parsedTexture.animations) {
  63729. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63730. var parsedAnimation = parsedTexture.animations[animationIndex];
  63731. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63732. }
  63733. }
  63734. return texture;
  63735. };
  63736. CubeTexture.prototype.clone = function () {
  63737. var _this = this;
  63738. return BABYLON.SerializationHelper.Clone(function () {
  63739. var scene = _this.getScene();
  63740. if (!scene) {
  63741. return _this;
  63742. }
  63743. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63744. }, this);
  63745. };
  63746. __decorate([
  63747. BABYLON.serialize("rotationY")
  63748. ], CubeTexture.prototype, "_rotationY", void 0);
  63749. return CubeTexture;
  63750. }(BABYLON.BaseTexture));
  63751. BABYLON.CubeTexture = CubeTexture;
  63752. })(BABYLON || (BABYLON = {}));
  63753. //# sourceMappingURL=babylon.cubeTexture.js.map
  63754. var BABYLON;
  63755. (function (BABYLON) {
  63756. var RenderTargetTexture = /** @class */ (function (_super) {
  63757. __extends(RenderTargetTexture, _super);
  63758. /**
  63759. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63760. * or used a shadow, depth texture...
  63761. * @param name The friendly name of the texture
  63762. * @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)
  63763. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63764. * @param generateMipMaps True if mip maps need to be generated after render.
  63765. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63766. * @param type The type of the buffer in the RTT (int, half float, float...)
  63767. * @param isCube True if a cube texture needs to be created
  63768. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63769. * @param generateDepthBuffer True to generate a depth buffer
  63770. * @param generateStencilBuffer True to generate a stencil buffer
  63771. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63772. */
  63773. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63774. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63775. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63776. if (isCube === void 0) { isCube = false; }
  63777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63778. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63779. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63780. if (isMulti === void 0) { isMulti = false; }
  63781. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63782. _this.isCube = isCube;
  63783. /**
  63784. * Use this list to define the list of mesh you want to render.
  63785. */
  63786. _this.renderList = new Array();
  63787. _this.renderParticles = true;
  63788. _this.renderSprites = false;
  63789. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63790. _this.ignoreCameraViewport = false;
  63791. // Events
  63792. /**
  63793. * An event triggered when the texture is unbind.
  63794. */
  63795. _this.onBeforeBindObservable = new BABYLON.Observable();
  63796. /**
  63797. * An event triggered when the texture is unbind.
  63798. */
  63799. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63800. /**
  63801. * An event triggered before rendering the texture
  63802. */
  63803. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63804. /**
  63805. * An event triggered after rendering the texture
  63806. */
  63807. _this.onAfterRenderObservable = new BABYLON.Observable();
  63808. /**
  63809. * An event triggered after the texture clear
  63810. */
  63811. _this.onClearObservable = new BABYLON.Observable();
  63812. _this._currentRefreshId = -1;
  63813. _this._refreshRate = 1;
  63814. _this._samples = 1;
  63815. /**
  63816. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63817. * It must define where the camera used to render the texture is set
  63818. */
  63819. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63820. scene = _this.getScene();
  63821. if (!scene) {
  63822. return _this;
  63823. }
  63824. _this._engine = scene.getEngine();
  63825. _this.name = name;
  63826. _this.isRenderTarget = true;
  63827. _this._initialSizeParameter = size;
  63828. _this._processSizeParameter(size);
  63829. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63830. });
  63831. _this._generateMipMaps = generateMipMaps ? true : false;
  63832. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63833. // Rendering groups
  63834. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63835. if (isMulti) {
  63836. return _this;
  63837. }
  63838. _this._renderTargetOptions = {
  63839. generateMipMaps: generateMipMaps,
  63840. type: type,
  63841. samplingMode: samplingMode,
  63842. generateDepthBuffer: generateDepthBuffer,
  63843. generateStencilBuffer: generateStencilBuffer
  63844. };
  63845. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63846. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63847. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63848. }
  63849. if (isCube) {
  63850. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63851. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63852. _this._textureMatrix = BABYLON.Matrix.Identity();
  63853. }
  63854. else {
  63855. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63856. }
  63857. return _this;
  63858. }
  63859. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63860. get: function () {
  63861. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63862. },
  63863. enumerable: true,
  63864. configurable: true
  63865. });
  63866. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63867. get: function () {
  63868. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63869. },
  63870. enumerable: true,
  63871. configurable: true
  63872. });
  63873. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63874. get: function () {
  63875. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63876. },
  63877. enumerable: true,
  63878. configurable: true
  63879. });
  63880. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63881. set: function (callback) {
  63882. if (this._onAfterUnbindObserver) {
  63883. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63884. }
  63885. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63886. },
  63887. enumerable: true,
  63888. configurable: true
  63889. });
  63890. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63891. set: function (callback) {
  63892. if (this._onBeforeRenderObserver) {
  63893. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63894. }
  63895. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63896. },
  63897. enumerable: true,
  63898. configurable: true
  63899. });
  63900. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63901. set: function (callback) {
  63902. if (this._onAfterRenderObserver) {
  63903. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63904. }
  63905. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63906. },
  63907. enumerable: true,
  63908. configurable: true
  63909. });
  63910. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63911. set: function (callback) {
  63912. if (this._onClearObserver) {
  63913. this.onClearObservable.remove(this._onClearObserver);
  63914. }
  63915. this._onClearObserver = this.onClearObservable.add(callback);
  63916. },
  63917. enumerable: true,
  63918. configurable: true
  63919. });
  63920. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63921. get: function () {
  63922. return this._renderTargetOptions;
  63923. },
  63924. enumerable: true,
  63925. configurable: true
  63926. });
  63927. RenderTargetTexture.prototype._onRatioRescale = function () {
  63928. if (this._sizeRatio) {
  63929. this.resize(this._initialSizeParameter);
  63930. }
  63931. };
  63932. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63933. get: function () {
  63934. return this._boundingBoxSize;
  63935. },
  63936. /**
  63937. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63938. * When defined, the cubemap will switch to local mode
  63939. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63940. * @example https://www.babylonjs-playground.com/#RNASML
  63941. */
  63942. set: function (value) {
  63943. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63944. return;
  63945. }
  63946. this._boundingBoxSize = value;
  63947. var scene = this.getScene();
  63948. if (scene) {
  63949. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63950. }
  63951. },
  63952. enumerable: true,
  63953. configurable: true
  63954. });
  63955. /**
  63956. * Creates a depth stencil texture.
  63957. * This is only available in WebGL 2 or with the depth texture extension available.
  63958. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63959. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63960. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63961. */
  63962. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63963. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63964. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63965. if (generateStencil === void 0) { generateStencil = false; }
  63966. if (!this.getScene()) {
  63967. return;
  63968. }
  63969. var engine = this.getScene().getEngine();
  63970. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63971. bilinearFiltering: bilinearFiltering,
  63972. comparisonFunction: comparisonFunction,
  63973. generateStencil: generateStencil,
  63974. isCube: this.isCube
  63975. });
  63976. engine.setFrameBufferDepthStencilTexture(this);
  63977. };
  63978. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63979. if (size.ratio) {
  63980. this._sizeRatio = size.ratio;
  63981. this._size = {
  63982. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63983. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63984. };
  63985. }
  63986. else {
  63987. this._size = size;
  63988. }
  63989. };
  63990. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63991. get: function () {
  63992. return this._samples;
  63993. },
  63994. set: function (value) {
  63995. if (this._samples === value) {
  63996. return;
  63997. }
  63998. var scene = this.getScene();
  63999. if (!scene) {
  64000. return;
  64001. }
  64002. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64003. },
  64004. enumerable: true,
  64005. configurable: true
  64006. });
  64007. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64008. this._currentRefreshId = -1;
  64009. };
  64010. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64011. get: function () {
  64012. return this._refreshRate;
  64013. },
  64014. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64015. set: function (value) {
  64016. this._refreshRate = value;
  64017. this.resetRefreshCounter();
  64018. },
  64019. enumerable: true,
  64020. configurable: true
  64021. });
  64022. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64023. if (!this._postProcessManager) {
  64024. var scene = this.getScene();
  64025. if (!scene) {
  64026. return;
  64027. }
  64028. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64029. this._postProcesses = new Array();
  64030. }
  64031. this._postProcesses.push(postProcess);
  64032. this._postProcesses[0].autoClear = false;
  64033. };
  64034. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64035. if (!this._postProcesses) {
  64036. return;
  64037. }
  64038. if (dispose) {
  64039. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64040. var postProcess = _a[_i];
  64041. postProcess.dispose();
  64042. }
  64043. }
  64044. this._postProcesses = [];
  64045. };
  64046. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64047. if (!this._postProcesses) {
  64048. return;
  64049. }
  64050. var index = this._postProcesses.indexOf(postProcess);
  64051. if (index === -1) {
  64052. return;
  64053. }
  64054. this._postProcesses.splice(index, 1);
  64055. if (this._postProcesses.length > 0) {
  64056. this._postProcesses[0].autoClear = false;
  64057. }
  64058. };
  64059. RenderTargetTexture.prototype._shouldRender = function () {
  64060. if (this._currentRefreshId === -1) { // At least render once
  64061. this._currentRefreshId = 1;
  64062. return true;
  64063. }
  64064. if (this.refreshRate === this._currentRefreshId) {
  64065. this._currentRefreshId = 1;
  64066. return true;
  64067. }
  64068. this._currentRefreshId++;
  64069. return false;
  64070. };
  64071. RenderTargetTexture.prototype.getRenderSize = function () {
  64072. if (this._size.width) {
  64073. return this._size.width;
  64074. }
  64075. return this._size;
  64076. };
  64077. RenderTargetTexture.prototype.getRenderWidth = function () {
  64078. if (this._size.width) {
  64079. return this._size.width;
  64080. }
  64081. return this._size;
  64082. };
  64083. RenderTargetTexture.prototype.getRenderHeight = function () {
  64084. if (this._size.width) {
  64085. return this._size.height;
  64086. }
  64087. return this._size;
  64088. };
  64089. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64090. get: function () {
  64091. return true;
  64092. },
  64093. enumerable: true,
  64094. configurable: true
  64095. });
  64096. RenderTargetTexture.prototype.scale = function (ratio) {
  64097. var newSize = this.getRenderSize() * ratio;
  64098. this.resize(newSize);
  64099. };
  64100. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64101. if (this.isCube) {
  64102. return this._textureMatrix;
  64103. }
  64104. return _super.prototype.getReflectionTextureMatrix.call(this);
  64105. };
  64106. RenderTargetTexture.prototype.resize = function (size) {
  64107. this.releaseInternalTexture();
  64108. var scene = this.getScene();
  64109. if (!scene) {
  64110. return;
  64111. }
  64112. this._processSizeParameter(size);
  64113. if (this.isCube) {
  64114. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64115. }
  64116. else {
  64117. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64118. }
  64119. };
  64120. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64121. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64122. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64123. var scene = this.getScene();
  64124. if (!scene) {
  64125. return;
  64126. }
  64127. var engine = scene.getEngine();
  64128. if (this.useCameraPostProcesses !== undefined) {
  64129. useCameraPostProcess = this.useCameraPostProcesses;
  64130. }
  64131. if (this._waitingRenderList) {
  64132. this.renderList = [];
  64133. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64134. var id = this._waitingRenderList[index];
  64135. var mesh_1 = scene.getMeshByID(id);
  64136. if (mesh_1) {
  64137. this.renderList.push(mesh_1);
  64138. }
  64139. }
  64140. delete this._waitingRenderList;
  64141. }
  64142. // Is predicate defined?
  64143. if (this.renderListPredicate) {
  64144. if (this.renderList) {
  64145. this.renderList.splice(0); // Clear previous renderList
  64146. }
  64147. else {
  64148. this.renderList = [];
  64149. }
  64150. var scene = this.getScene();
  64151. if (!scene) {
  64152. return;
  64153. }
  64154. var sceneMeshes = scene.meshes;
  64155. for (var index = 0; index < sceneMeshes.length; index++) {
  64156. var mesh = sceneMeshes[index];
  64157. if (this.renderListPredicate(mesh)) {
  64158. this.renderList.push(mesh);
  64159. }
  64160. }
  64161. }
  64162. this.onBeforeBindObservable.notifyObservers(this);
  64163. // Set custom projection.
  64164. // Needs to be before binding to prevent changing the aspect ratio.
  64165. var camera;
  64166. if (this.activeCamera) {
  64167. camera = this.activeCamera;
  64168. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64169. if (this.activeCamera !== scene.activeCamera) {
  64170. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64171. }
  64172. }
  64173. else {
  64174. camera = scene.activeCamera;
  64175. if (camera) {
  64176. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64177. }
  64178. }
  64179. // Prepare renderingManager
  64180. this._renderingManager.reset();
  64181. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64182. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64183. var sceneRenderId = scene.getRenderId();
  64184. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64185. var mesh = currentRenderList[meshIndex];
  64186. if (mesh) {
  64187. if (!mesh.isReady(this.refreshRate === 0)) {
  64188. this.resetRefreshCounter();
  64189. continue;
  64190. }
  64191. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64192. var isMasked = void 0;
  64193. if (!this.renderList && camera) {
  64194. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64195. }
  64196. else {
  64197. isMasked = false;
  64198. }
  64199. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64200. mesh._activate(sceneRenderId);
  64201. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64202. var subMesh = mesh.subMeshes[subIndex];
  64203. scene._activeIndices.addCount(subMesh.indexCount, false);
  64204. this._renderingManager.dispatch(subMesh, mesh);
  64205. }
  64206. }
  64207. }
  64208. }
  64209. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64210. var particleSystem = scene.particleSystems[particleIndex];
  64211. var emitter = particleSystem.emitter;
  64212. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64213. continue;
  64214. }
  64215. if (currentRenderList.indexOf(emitter) >= 0) {
  64216. this._renderingManager.dispatchParticles(particleSystem);
  64217. }
  64218. }
  64219. if (this.isCube) {
  64220. for (var face = 0; face < 6; face++) {
  64221. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64222. scene.incrementRenderId();
  64223. scene.resetCachedMaterial();
  64224. }
  64225. }
  64226. else {
  64227. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64228. }
  64229. this.onAfterUnbindObservable.notifyObservers(this);
  64230. if (scene.activeCamera) {
  64231. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64232. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64233. }
  64234. engine.setViewport(scene.activeCamera.viewport);
  64235. }
  64236. scene.resetCachedMaterial();
  64237. };
  64238. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64239. var minimum = 128;
  64240. var x = renderDimension * scale;
  64241. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64242. // Ensure we don't exceed the render dimension (while staying POT)
  64243. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64244. };
  64245. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64246. var _this = this;
  64247. if (!this._texture) {
  64248. return;
  64249. }
  64250. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64251. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64252. });
  64253. };
  64254. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64255. var scene = this.getScene();
  64256. if (!scene) {
  64257. return;
  64258. }
  64259. var engine = scene.getEngine();
  64260. if (!this._texture) {
  64261. return;
  64262. }
  64263. // Bind
  64264. if (this._postProcessManager) {
  64265. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64266. }
  64267. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64268. if (this._texture) {
  64269. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64270. }
  64271. }
  64272. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64273. // Clear
  64274. if (this.onClearObservable.hasObservers()) {
  64275. this.onClearObservable.notifyObservers(engine);
  64276. }
  64277. else {
  64278. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64279. }
  64280. if (!this._doNotChangeAspectRatio) {
  64281. scene.updateTransformMatrix(true);
  64282. }
  64283. // Render
  64284. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64285. if (this._postProcessManager) {
  64286. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64287. }
  64288. else if (useCameraPostProcess) {
  64289. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64290. }
  64291. if (!this._doNotChangeAspectRatio) {
  64292. scene.updateTransformMatrix(true);
  64293. }
  64294. // Dump ?
  64295. if (dumpForDebug) {
  64296. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64297. }
  64298. // Unbind
  64299. if (!this.isCube || faceIndex === 5) {
  64300. if (this.isCube) {
  64301. if (faceIndex === 5) {
  64302. engine.generateMipMapsForCubemap(this._texture);
  64303. }
  64304. }
  64305. this.unbindFrameBuffer(engine, faceIndex);
  64306. }
  64307. else {
  64308. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64309. }
  64310. };
  64311. /**
  64312. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64313. * This allowed control for front to back rendering or reversly depending of the special needs.
  64314. *
  64315. * @param renderingGroupId The rendering group id corresponding to its index
  64316. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64317. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64318. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64319. */
  64320. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64321. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64322. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64323. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64324. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64325. };
  64326. /**
  64327. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64328. *
  64329. * @param renderingGroupId The rendering group id corresponding to its index
  64330. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64331. */
  64332. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64333. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64334. };
  64335. RenderTargetTexture.prototype.clone = function () {
  64336. var textureSize = this.getSize();
  64337. 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);
  64338. // Base texture
  64339. newTexture.hasAlpha = this.hasAlpha;
  64340. newTexture.level = this.level;
  64341. // RenderTarget Texture
  64342. newTexture.coordinatesMode = this.coordinatesMode;
  64343. if (this.renderList) {
  64344. newTexture.renderList = this.renderList.slice(0);
  64345. }
  64346. return newTexture;
  64347. };
  64348. RenderTargetTexture.prototype.serialize = function () {
  64349. if (!this.name) {
  64350. return null;
  64351. }
  64352. var serializationObject = _super.prototype.serialize.call(this);
  64353. serializationObject.renderTargetSize = this.getRenderSize();
  64354. serializationObject.renderList = [];
  64355. if (this.renderList) {
  64356. for (var index = 0; index < this.renderList.length; index++) {
  64357. serializationObject.renderList.push(this.renderList[index].id);
  64358. }
  64359. }
  64360. return serializationObject;
  64361. };
  64362. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64363. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64364. var objBuffer = this.getInternalTexture();
  64365. var scene = this.getScene();
  64366. if (objBuffer && scene) {
  64367. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64368. }
  64369. };
  64370. RenderTargetTexture.prototype.dispose = function () {
  64371. if (this._postProcessManager) {
  64372. this._postProcessManager.dispose();
  64373. this._postProcessManager = null;
  64374. }
  64375. this.clearPostProcesses(true);
  64376. if (this._resizeObserver) {
  64377. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64378. this._resizeObserver = null;
  64379. }
  64380. this.renderList = null;
  64381. // Remove from custom render targets
  64382. var scene = this.getScene();
  64383. if (!scene) {
  64384. return;
  64385. }
  64386. var index = scene.customRenderTargets.indexOf(this);
  64387. if (index >= 0) {
  64388. scene.customRenderTargets.splice(index, 1);
  64389. }
  64390. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64391. var camera = _a[_i];
  64392. index = camera.customRenderTargets.indexOf(this);
  64393. if (index >= 0) {
  64394. camera.customRenderTargets.splice(index, 1);
  64395. }
  64396. }
  64397. _super.prototype.dispose.call(this);
  64398. };
  64399. RenderTargetTexture.prototype._rebuild = function () {
  64400. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64401. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64402. }
  64403. if (this._postProcessManager) {
  64404. this._postProcessManager._rebuild();
  64405. }
  64406. };
  64407. /**
  64408. * Clear the info related to rendering groups preventing retention point in material dispose.
  64409. */
  64410. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64411. if (this._renderingManager) {
  64412. this._renderingManager.freeRenderingGroups();
  64413. }
  64414. };
  64415. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64416. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64417. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64418. return RenderTargetTexture;
  64419. }(BABYLON.Texture));
  64420. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64421. })(BABYLON || (BABYLON = {}));
  64422. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64423. var BABYLON;
  64424. (function (BABYLON) {
  64425. ;
  64426. var MultiRenderTarget = /** @class */ (function (_super) {
  64427. __extends(MultiRenderTarget, _super);
  64428. function MultiRenderTarget(name, size, count, scene, options) {
  64429. var _this = this;
  64430. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64431. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64432. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64433. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64434. _this._engine = scene.getEngine();
  64435. if (!_this.isSupported) {
  64436. _this.dispose();
  64437. return;
  64438. }
  64439. var types = [];
  64440. var samplingModes = [];
  64441. for (var i = 0; i < count; i++) {
  64442. if (options && options.types && options.types[i] !== undefined) {
  64443. types.push(options.types[i]);
  64444. }
  64445. else {
  64446. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64447. }
  64448. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64449. samplingModes.push(options.samplingModes[i]);
  64450. }
  64451. else {
  64452. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64453. }
  64454. }
  64455. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64456. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64457. _this._size = size;
  64458. _this._multiRenderTargetOptions = {
  64459. samplingModes: samplingModes,
  64460. generateMipMaps: generateMipMaps,
  64461. generateDepthBuffer: generateDepthBuffer,
  64462. generateStencilBuffer: generateStencilBuffer,
  64463. generateDepthTexture: generateDepthTexture,
  64464. types: types,
  64465. textureCount: count
  64466. };
  64467. _this._createInternalTextures();
  64468. _this._createTextures();
  64469. return _this;
  64470. }
  64471. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64472. get: function () {
  64473. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64474. },
  64475. enumerable: true,
  64476. configurable: true
  64477. });
  64478. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64479. get: function () {
  64480. return this._textures;
  64481. },
  64482. enumerable: true,
  64483. configurable: true
  64484. });
  64485. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64486. get: function () {
  64487. return this._textures[this._textures.length - 1];
  64488. },
  64489. enumerable: true,
  64490. configurable: true
  64491. });
  64492. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64493. set: function (wrap) {
  64494. if (this._textures) {
  64495. for (var i = 0; i < this._textures.length; i++) {
  64496. this._textures[i].wrapU = wrap;
  64497. }
  64498. }
  64499. },
  64500. enumerable: true,
  64501. configurable: true
  64502. });
  64503. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64504. set: function (wrap) {
  64505. if (this._textures) {
  64506. for (var i = 0; i < this._textures.length; i++) {
  64507. this._textures[i].wrapV = wrap;
  64508. }
  64509. }
  64510. },
  64511. enumerable: true,
  64512. configurable: true
  64513. });
  64514. MultiRenderTarget.prototype._rebuild = function () {
  64515. this.releaseInternalTextures();
  64516. this._createInternalTextures();
  64517. for (var i = 0; i < this._internalTextures.length; i++) {
  64518. var texture = this._textures[i];
  64519. texture._texture = this._internalTextures[i];
  64520. }
  64521. // Keeps references to frame buffer and stencil/depth buffer
  64522. this._texture = this._internalTextures[0];
  64523. };
  64524. MultiRenderTarget.prototype._createInternalTextures = function () {
  64525. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64526. };
  64527. MultiRenderTarget.prototype._createTextures = function () {
  64528. this._textures = [];
  64529. for (var i = 0; i < this._internalTextures.length; i++) {
  64530. var texture = new BABYLON.Texture(null, this.getScene());
  64531. texture._texture = this._internalTextures[i];
  64532. this._textures.push(texture);
  64533. }
  64534. // Keeps references to frame buffer and stencil/depth buffer
  64535. this._texture = this._internalTextures[0];
  64536. };
  64537. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64538. get: function () {
  64539. return this._samples;
  64540. },
  64541. set: function (value) {
  64542. if (this._samples === value) {
  64543. return;
  64544. }
  64545. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64546. },
  64547. enumerable: true,
  64548. configurable: true
  64549. });
  64550. MultiRenderTarget.prototype.resize = function (size) {
  64551. this.releaseInternalTextures();
  64552. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64553. this._createInternalTextures();
  64554. };
  64555. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64556. var _this = this;
  64557. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64558. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64559. });
  64560. };
  64561. MultiRenderTarget.prototype.dispose = function () {
  64562. this.releaseInternalTextures();
  64563. _super.prototype.dispose.call(this);
  64564. };
  64565. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64566. if (!this._internalTextures) {
  64567. return;
  64568. }
  64569. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64570. if (this._internalTextures[i] !== undefined) {
  64571. this._internalTextures[i].dispose();
  64572. this._internalTextures.splice(i, 1);
  64573. }
  64574. }
  64575. };
  64576. return MultiRenderTarget;
  64577. }(BABYLON.RenderTargetTexture));
  64578. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64579. })(BABYLON || (BABYLON = {}));
  64580. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64581. var BABYLON;
  64582. (function (BABYLON) {
  64583. var MirrorTexture = /** @class */ (function (_super) {
  64584. __extends(MirrorTexture, _super);
  64585. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64586. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64587. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64588. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64589. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64590. _this.scene = scene;
  64591. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64592. _this._transformMatrix = BABYLON.Matrix.Zero();
  64593. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64594. _this._adaptiveBlurKernel = 0;
  64595. _this._blurKernelX = 0;
  64596. _this._blurKernelY = 0;
  64597. _this._blurRatio = 1.0;
  64598. _this.ignoreCameraViewport = true;
  64599. _this._updateGammaSpace();
  64600. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64601. _this._updateGammaSpace;
  64602. });
  64603. _this.onBeforeRenderObservable.add(function () {
  64604. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64605. _this._savedViewMatrix = scene.getViewMatrix();
  64606. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64607. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64608. scene.clipPlane = _this.mirrorPlane;
  64609. scene.getEngine().cullBackFaces = false;
  64610. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64611. });
  64612. _this.onAfterRenderObservable.add(function () {
  64613. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64614. scene.getEngine().cullBackFaces = true;
  64615. scene._mirroredCameraPosition = null;
  64616. delete scene.clipPlane;
  64617. });
  64618. return _this;
  64619. }
  64620. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64621. get: function () {
  64622. return this._blurRatio;
  64623. },
  64624. set: function (value) {
  64625. if (this._blurRatio === value) {
  64626. return;
  64627. }
  64628. this._blurRatio = value;
  64629. this._preparePostProcesses();
  64630. },
  64631. enumerable: true,
  64632. configurable: true
  64633. });
  64634. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64635. set: function (value) {
  64636. this._adaptiveBlurKernel = value;
  64637. this._autoComputeBlurKernel();
  64638. },
  64639. enumerable: true,
  64640. configurable: true
  64641. });
  64642. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64643. set: function (value) {
  64644. this.blurKernelX = value;
  64645. this.blurKernelY = value;
  64646. },
  64647. enumerable: true,
  64648. configurable: true
  64649. });
  64650. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64651. get: function () {
  64652. return this._blurKernelX;
  64653. },
  64654. set: function (value) {
  64655. if (this._blurKernelX === value) {
  64656. return;
  64657. }
  64658. this._blurKernelX = value;
  64659. this._preparePostProcesses();
  64660. },
  64661. enumerable: true,
  64662. configurable: true
  64663. });
  64664. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64665. get: function () {
  64666. return this._blurKernelY;
  64667. },
  64668. set: function (value) {
  64669. if (this._blurKernelY === value) {
  64670. return;
  64671. }
  64672. this._blurKernelY = value;
  64673. this._preparePostProcesses();
  64674. },
  64675. enumerable: true,
  64676. configurable: true
  64677. });
  64678. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64679. var engine = this.getScene().getEngine();
  64680. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64681. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64682. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64683. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64684. };
  64685. MirrorTexture.prototype._onRatioRescale = function () {
  64686. if (this._sizeRatio) {
  64687. this.resize(this._initialSizeParameter);
  64688. if (!this._adaptiveBlurKernel) {
  64689. this._preparePostProcesses();
  64690. }
  64691. }
  64692. if (this._adaptiveBlurKernel) {
  64693. this._autoComputeBlurKernel();
  64694. }
  64695. };
  64696. MirrorTexture.prototype._updateGammaSpace = function () {
  64697. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64698. };
  64699. MirrorTexture.prototype._preparePostProcesses = function () {
  64700. this.clearPostProcesses(true);
  64701. if (this._blurKernelX && this._blurKernelY) {
  64702. var engine = this.getScene().getEngine();
  64703. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64704. 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);
  64705. this._blurX.autoClear = false;
  64706. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64707. this._blurX.inputTexture = this._texture;
  64708. }
  64709. else {
  64710. this._blurX.alwaysForcePOT = true;
  64711. }
  64712. 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);
  64713. this._blurY.autoClear = false;
  64714. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64715. this.addPostProcess(this._blurX);
  64716. this.addPostProcess(this._blurY);
  64717. }
  64718. else {
  64719. if (this._blurY) {
  64720. this.removePostProcess(this._blurY);
  64721. this._blurY.dispose();
  64722. this._blurY = null;
  64723. }
  64724. if (this._blurX) {
  64725. this.removePostProcess(this._blurX);
  64726. this._blurX.dispose();
  64727. this._blurX = null;
  64728. }
  64729. }
  64730. };
  64731. MirrorTexture.prototype.clone = function () {
  64732. var scene = this.getScene();
  64733. if (!scene) {
  64734. return this;
  64735. }
  64736. var textureSize = this.getSize();
  64737. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64738. // Base texture
  64739. newTexture.hasAlpha = this.hasAlpha;
  64740. newTexture.level = this.level;
  64741. // Mirror Texture
  64742. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64743. if (this.renderList) {
  64744. newTexture.renderList = this.renderList.slice(0);
  64745. }
  64746. return newTexture;
  64747. };
  64748. MirrorTexture.prototype.serialize = function () {
  64749. if (!this.name) {
  64750. return null;
  64751. }
  64752. var serializationObject = _super.prototype.serialize.call(this);
  64753. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64754. return serializationObject;
  64755. };
  64756. MirrorTexture.prototype.dispose = function () {
  64757. _super.prototype.dispose.call(this);
  64758. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64759. };
  64760. return MirrorTexture;
  64761. }(BABYLON.RenderTargetTexture));
  64762. BABYLON.MirrorTexture = MirrorTexture;
  64763. })(BABYLON || (BABYLON = {}));
  64764. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64765. var BABYLON;
  64766. (function (BABYLON) {
  64767. /**
  64768. * Creates a refraction texture used by refraction channel of the standard material.
  64769. * @param name the texture name
  64770. * @param size size of the underlying texture
  64771. * @param scene root scene
  64772. */
  64773. var RefractionTexture = /** @class */ (function (_super) {
  64774. __extends(RefractionTexture, _super);
  64775. function RefractionTexture(name, size, scene, generateMipMaps) {
  64776. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64777. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64778. _this.depth = 2.0;
  64779. _this.onBeforeRenderObservable.add(function () {
  64780. scene.clipPlane = _this.refractionPlane;
  64781. });
  64782. _this.onAfterRenderObservable.add(function () {
  64783. delete scene.clipPlane;
  64784. });
  64785. return _this;
  64786. }
  64787. RefractionTexture.prototype.clone = function () {
  64788. var scene = this.getScene();
  64789. if (!scene) {
  64790. return this;
  64791. }
  64792. var textureSize = this.getSize();
  64793. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64794. // Base texture
  64795. newTexture.hasAlpha = this.hasAlpha;
  64796. newTexture.level = this.level;
  64797. // Refraction Texture
  64798. newTexture.refractionPlane = this.refractionPlane.clone();
  64799. if (this.renderList) {
  64800. newTexture.renderList = this.renderList.slice(0);
  64801. }
  64802. newTexture.depth = this.depth;
  64803. return newTexture;
  64804. };
  64805. RefractionTexture.prototype.serialize = function () {
  64806. if (!this.name) {
  64807. return null;
  64808. }
  64809. var serializationObject = _super.prototype.serialize.call(this);
  64810. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64811. serializationObject.depth = this.depth;
  64812. return serializationObject;
  64813. };
  64814. return RefractionTexture;
  64815. }(BABYLON.RenderTargetTexture));
  64816. BABYLON.RefractionTexture = RefractionTexture;
  64817. })(BABYLON || (BABYLON = {}));
  64818. //# sourceMappingURL=babylon.refractionTexture.js.map
  64819. var BABYLON;
  64820. (function (BABYLON) {
  64821. /**
  64822. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64823. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64824. */
  64825. var DynamicTexture = /** @class */ (function (_super) {
  64826. __extends(DynamicTexture, _super);
  64827. /**
  64828. * Creates a {BABYLON.DynamicTexture}
  64829. * @param name defines the name of the texture
  64830. * @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
  64831. * @param scene defines the scene where you want the texture
  64832. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64833. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64834. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64835. */
  64836. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64837. if (scene === void 0) { scene = null; }
  64838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64839. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64840. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64841. _this.name = name;
  64842. _this._engine = _this.getScene().getEngine();
  64843. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64844. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64845. _this._generateMipMaps = generateMipMaps;
  64846. if (options.getContext) {
  64847. _this._canvas = options;
  64848. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64849. }
  64850. else {
  64851. _this._canvas = document.createElement("canvas");
  64852. if (options.width || options.width === 0) {
  64853. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64854. }
  64855. else {
  64856. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64857. }
  64858. }
  64859. var textureSize = _this.getSize();
  64860. _this._canvas.width = textureSize.width;
  64861. _this._canvas.height = textureSize.height;
  64862. _this._context = _this._canvas.getContext("2d");
  64863. return _this;
  64864. }
  64865. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64866. /**
  64867. * Gets the current state of canRescale
  64868. */
  64869. get: function () {
  64870. return true;
  64871. },
  64872. enumerable: true,
  64873. configurable: true
  64874. });
  64875. DynamicTexture.prototype._recreate = function (textureSize) {
  64876. this._canvas.width = textureSize.width;
  64877. this._canvas.height = textureSize.height;
  64878. this.releaseInternalTexture();
  64879. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64880. };
  64881. /**
  64882. * Scales the texture
  64883. * @param ratio the scale factor to apply to both width and height
  64884. */
  64885. DynamicTexture.prototype.scale = function (ratio) {
  64886. var textureSize = this.getSize();
  64887. textureSize.width *= ratio;
  64888. textureSize.height *= ratio;
  64889. this._recreate(textureSize);
  64890. };
  64891. /**
  64892. * Resizes the texture
  64893. * @param width the new width
  64894. * @param height the new height
  64895. */
  64896. DynamicTexture.prototype.scaleTo = function (width, height) {
  64897. var textureSize = this.getSize();
  64898. textureSize.width = width;
  64899. textureSize.height = height;
  64900. this._recreate(textureSize);
  64901. };
  64902. /**
  64903. * Gets the context of the canvas used by the texture
  64904. * @returns the canvas context of the dynamic texture
  64905. */
  64906. DynamicTexture.prototype.getContext = function () {
  64907. return this._context;
  64908. };
  64909. /**
  64910. * Clears the texture
  64911. */
  64912. DynamicTexture.prototype.clear = function () {
  64913. var size = this.getSize();
  64914. this._context.fillRect(0, 0, size.width, size.height);
  64915. };
  64916. /**
  64917. * Updates the texture
  64918. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64919. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64920. */
  64921. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64922. if (premulAlpha === void 0) { premulAlpha = false; }
  64923. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64924. };
  64925. /**
  64926. * Draws text onto the texture
  64927. * @param text defines the text to be drawn
  64928. * @param x defines the placement of the text from the left
  64929. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64930. * @param font defines the font to be used with font-style, font-size, font-name
  64931. * @param color defines the color used for the text
  64932. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64933. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64934. * @param update defines whether texture is immediately update (default is true)
  64935. */
  64936. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64937. if (update === void 0) { update = true; }
  64938. var size = this.getSize();
  64939. if (clearColor) {
  64940. this._context.fillStyle = clearColor;
  64941. this._context.fillRect(0, 0, size.width, size.height);
  64942. }
  64943. this._context.font = font;
  64944. if (x === null || x === undefined) {
  64945. var textSize = this._context.measureText(text);
  64946. x = (size.width - textSize.width) / 2;
  64947. }
  64948. if (y === null || y === undefined) {
  64949. var fontSize = parseInt((font.replace(/\D/g, '')));
  64950. y = (size.height / 2) + (fontSize / 3.65);
  64951. }
  64952. this._context.fillStyle = color;
  64953. this._context.fillText(text, x, y);
  64954. if (update) {
  64955. this.update(invertY);
  64956. }
  64957. };
  64958. /**
  64959. * Clones the texture
  64960. * @returns the clone of the texture.
  64961. */
  64962. DynamicTexture.prototype.clone = function () {
  64963. var scene = this.getScene();
  64964. if (!scene) {
  64965. return this;
  64966. }
  64967. var textureSize = this.getSize();
  64968. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64969. // Base texture
  64970. newTexture.hasAlpha = this.hasAlpha;
  64971. newTexture.level = this.level;
  64972. // Dynamic Texture
  64973. newTexture.wrapU = this.wrapU;
  64974. newTexture.wrapV = this.wrapV;
  64975. return newTexture;
  64976. };
  64977. /** @hidden */
  64978. DynamicTexture.prototype._rebuild = function () {
  64979. this.update();
  64980. };
  64981. return DynamicTexture;
  64982. }(BABYLON.Texture));
  64983. BABYLON.DynamicTexture = DynamicTexture;
  64984. })(BABYLON || (BABYLON = {}));
  64985. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64986. var BABYLON;
  64987. (function (BABYLON) {
  64988. var VideoTexture = /** @class */ (function (_super) {
  64989. __extends(VideoTexture, _super);
  64990. /**
  64991. * Creates a video texture.
  64992. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64993. * @param {string | null} name optional name, will detect from video source, if not defined
  64994. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64995. * @param {BABYLON.Scene} scene is obviously the current scene.
  64996. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64997. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64998. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64999. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65000. */
  65001. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65002. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65003. if (invertY === void 0) { invertY = false; }
  65004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65005. if (settings === void 0) { settings = {
  65006. autoPlay: true,
  65007. loop: true,
  65008. autoUpdateTexture: true,
  65009. }; }
  65010. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65011. _this._stillImageCaptured = false;
  65012. _this._createInternalTexture = function () {
  65013. if (_this._texture != null) {
  65014. return;
  65015. }
  65016. if (!_this._engine.needPOTTextures ||
  65017. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65018. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65019. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65020. }
  65021. else {
  65022. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65023. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65024. _this._generateMipMaps = false;
  65025. }
  65026. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65027. if (!_this.video.autoplay) {
  65028. var oldHandler_1 = _this.video.onplaying;
  65029. _this.video.onplaying = function () {
  65030. _this.video.onplaying = oldHandler_1;
  65031. _this._texture.isReady = true;
  65032. _this._updateInternalTexture();
  65033. _this.video.pause();
  65034. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65035. _this.onLoadObservable.notifyObservers(_this);
  65036. }
  65037. };
  65038. _this.video.play();
  65039. }
  65040. else {
  65041. _this._texture.isReady = true;
  65042. _this._updateInternalTexture();
  65043. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65044. _this.onLoadObservable.notifyObservers(_this);
  65045. }
  65046. }
  65047. };
  65048. _this.reset = function () {
  65049. if (_this._texture == null) {
  65050. return;
  65051. }
  65052. _this._texture.dispose();
  65053. _this._texture = null;
  65054. };
  65055. _this._updateInternalTexture = function (e) {
  65056. if (_this._texture == null || !_this._texture.isReady) {
  65057. return;
  65058. }
  65059. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65060. return;
  65061. }
  65062. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65063. };
  65064. _this._engine = _this.getScene().getEngine();
  65065. _this._generateMipMaps = generateMipMaps;
  65066. _this._samplingMode = samplingMode;
  65067. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65068. _this.name = name || _this._getName(src);
  65069. _this.video = _this._getVideo(src);
  65070. if (settings.autoPlay !== undefined) {
  65071. _this.video.autoplay = settings.autoPlay;
  65072. }
  65073. if (settings.loop !== undefined) {
  65074. _this.video.loop = settings.loop;
  65075. }
  65076. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65077. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65078. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65079. _this.video.addEventListener("emptied", _this.reset);
  65080. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65081. _this._createInternalTexture();
  65082. }
  65083. return _this;
  65084. }
  65085. VideoTexture.prototype._getName = function (src) {
  65086. if (src instanceof HTMLVideoElement) {
  65087. return src.currentSrc;
  65088. }
  65089. if (typeof src === "object") {
  65090. return src.toString();
  65091. }
  65092. return src;
  65093. };
  65094. ;
  65095. VideoTexture.prototype._getVideo = function (src) {
  65096. if (src instanceof HTMLVideoElement) {
  65097. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65098. return src;
  65099. }
  65100. var video = document.createElement("video");
  65101. if (typeof src === "string") {
  65102. BABYLON.Tools.SetCorsBehavior(src, video);
  65103. video.src = src;
  65104. }
  65105. else {
  65106. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65107. src.forEach(function (url) {
  65108. var source = document.createElement("source");
  65109. source.src = url;
  65110. video.appendChild(source);
  65111. });
  65112. }
  65113. return video;
  65114. };
  65115. ;
  65116. /**
  65117. * Internal method to initiate `update`.
  65118. */
  65119. VideoTexture.prototype._rebuild = function () {
  65120. this.update();
  65121. };
  65122. /**
  65123. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65124. */
  65125. VideoTexture.prototype.update = function () {
  65126. if (!this.autoUpdateTexture) {
  65127. // Expecting user to call `updateTexture` manually
  65128. return;
  65129. }
  65130. this.updateTexture(true);
  65131. };
  65132. /**
  65133. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65134. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65135. */
  65136. VideoTexture.prototype.updateTexture = function (isVisible) {
  65137. if (!isVisible) {
  65138. return;
  65139. }
  65140. if (this.video.paused && this._stillImageCaptured) {
  65141. return;
  65142. }
  65143. this._stillImageCaptured = true;
  65144. this._updateInternalTexture();
  65145. };
  65146. /**
  65147. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65148. * @param url New url.
  65149. */
  65150. VideoTexture.prototype.updateURL = function (url) {
  65151. this.video.src = url;
  65152. };
  65153. VideoTexture.prototype.dispose = function () {
  65154. _super.prototype.dispose.call(this);
  65155. this.video.removeEventListener("canplay", this._createInternalTexture);
  65156. this.video.removeEventListener("paused", this._updateInternalTexture);
  65157. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65158. this.video.removeEventListener("emptied", this.reset);
  65159. this.video.pause();
  65160. };
  65161. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65162. var video = document.createElement("video");
  65163. var constraintsDeviceId;
  65164. if (constraints && constraints.deviceId) {
  65165. constraintsDeviceId = {
  65166. exact: constraints.deviceId,
  65167. };
  65168. }
  65169. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65170. if (navigator.mediaDevices) {
  65171. navigator.mediaDevices.getUserMedia({ video: constraints })
  65172. .then(function (stream) {
  65173. if (video.mozSrcObject !== undefined) {
  65174. // hack for Firefox < 19
  65175. video.mozSrcObject = stream;
  65176. }
  65177. else {
  65178. video.srcObject = stream;
  65179. }
  65180. var onPlaying = function () {
  65181. if (onReady) {
  65182. onReady(new VideoTexture("video", video, scene, true, true));
  65183. }
  65184. video.removeEventListener("playing", onPlaying);
  65185. };
  65186. video.addEventListener("playing", onPlaying);
  65187. video.play();
  65188. })
  65189. .catch(function (err) {
  65190. BABYLON.Tools.Error(err.name);
  65191. });
  65192. }
  65193. else {
  65194. navigator.getUserMedia =
  65195. navigator.getUserMedia ||
  65196. navigator.webkitGetUserMedia ||
  65197. navigator.mozGetUserMedia ||
  65198. navigator.msGetUserMedia;
  65199. if (navigator.getUserMedia) {
  65200. navigator.getUserMedia({
  65201. video: {
  65202. deviceId: constraintsDeviceId,
  65203. width: {
  65204. min: (constraints && constraints.minWidth) || 256,
  65205. max: (constraints && constraints.maxWidth) || 640,
  65206. },
  65207. height: {
  65208. min: (constraints && constraints.minHeight) || 256,
  65209. max: (constraints && constraints.maxHeight) || 480,
  65210. },
  65211. },
  65212. }, function (stream) {
  65213. if (video.mozSrcObject !== undefined) {
  65214. // hack for Firefox < 19
  65215. video.mozSrcObject = stream;
  65216. }
  65217. else {
  65218. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65219. }
  65220. video.play();
  65221. if (onReady) {
  65222. onReady(new VideoTexture("video", video, scene, true, true));
  65223. }
  65224. }, function (e) {
  65225. BABYLON.Tools.Error(e.name);
  65226. });
  65227. }
  65228. }
  65229. };
  65230. return VideoTexture;
  65231. }(BABYLON.Texture));
  65232. BABYLON.VideoTexture = VideoTexture;
  65233. })(BABYLON || (BABYLON = {}));
  65234. //# sourceMappingURL=babylon.videoTexture.js.map
  65235. var BABYLON;
  65236. (function (BABYLON) {
  65237. var RawTexture = /** @class */ (function (_super) {
  65238. __extends(RawTexture, _super);
  65239. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65240. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65241. if (invertY === void 0) { invertY = false; }
  65242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65243. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65244. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65245. _this.format = format;
  65246. _this._engine = scene.getEngine();
  65247. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65248. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65249. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65250. return _this;
  65251. }
  65252. RawTexture.prototype.update = function (data) {
  65253. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65254. };
  65255. // Statics
  65256. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65257. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65258. if (invertY === void 0) { invertY = false; }
  65259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65260. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65261. };
  65262. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65263. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65264. if (invertY === void 0) { invertY = false; }
  65265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65266. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65267. };
  65268. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65269. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65270. if (invertY === void 0) { invertY = false; }
  65271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65272. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65273. };
  65274. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65275. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65276. if (invertY === void 0) { invertY = false; }
  65277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65278. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65279. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65280. };
  65281. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65282. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65283. if (invertY === void 0) { invertY = false; }
  65284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65285. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65286. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65287. };
  65288. return RawTexture;
  65289. }(BABYLON.Texture));
  65290. BABYLON.RawTexture = RawTexture;
  65291. })(BABYLON || (BABYLON = {}));
  65292. //# sourceMappingURL=babylon.rawTexture.js.map
  65293. var BABYLON;
  65294. (function (BABYLON) {
  65295. /**
  65296. * Class used to store 3D textures containing user data
  65297. */
  65298. var RawTexture3D = /** @class */ (function (_super) {
  65299. __extends(RawTexture3D, _super);
  65300. /**
  65301. * Create a new RawTexture3D
  65302. * @param data defines the data of the texture
  65303. * @param width defines the width of the texture
  65304. * @param height defines the height of the texture
  65305. * @param depth defines the depth of the texture
  65306. * @param format defines the texture format to use
  65307. * @param scene defines the hosting scene
  65308. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65309. * @param invertY defines if texture must be stored with Y axis inverted
  65310. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65311. */
  65312. function RawTexture3D(data, width, height, depth,
  65313. /** Gets or sets the texture format to use*/
  65314. format, scene, generateMipMaps, invertY, samplingMode) {
  65315. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65316. if (invertY === void 0) { invertY = false; }
  65317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65318. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65319. _this.format = format;
  65320. _this._engine = scene.getEngine();
  65321. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  65322. _this.is3D = true;
  65323. return _this;
  65324. }
  65325. /**
  65326. * Update the texture with new data
  65327. * @param data defines the data to store in the texture
  65328. */
  65329. RawTexture3D.prototype.update = function (data) {
  65330. if (!this._texture) {
  65331. return;
  65332. }
  65333. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  65334. };
  65335. return RawTexture3D;
  65336. }(BABYLON.Texture));
  65337. BABYLON.RawTexture3D = RawTexture3D;
  65338. })(BABYLON || (BABYLON = {}));
  65339. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65340. var BABYLON;
  65341. (function (BABYLON) {
  65342. /**
  65343. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65344. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65345. */
  65346. var PostProcess = /** @class */ (function () {
  65347. /**
  65348. * Creates a new instance PostProcess
  65349. * @param name The name of the PostProcess.
  65350. * @param fragmentUrl The url of the fragment shader to be used.
  65351. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65352. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65353. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65354. * @param camera The camera to apply the render pass to.
  65355. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65356. * @param engine The engine which the post process will be applied. (default: current engine)
  65357. * @param reusable If the post process can be reused on the same frame. (default: false)
  65358. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65359. * @param textureType Type of textures used when performing the post process. (default: 0)
  65360. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65361. * @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
  65362. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65363. */
  65364. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65366. if (defines === void 0) { defines = null; }
  65367. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65368. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65369. if (blockCompilation === void 0) { blockCompilation = false; }
  65370. this.name = name;
  65371. /**
  65372. * Width of the texture to apply the post process on
  65373. */
  65374. this.width = -1;
  65375. /**
  65376. * Height of the texture to apply the post process on
  65377. */
  65378. this.height = -1;
  65379. /**
  65380. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65381. */
  65382. this._outputTexture = null;
  65383. /**
  65384. * If the buffer needs to be cleared before applying the post process. (default: true)
  65385. * Should be set to false if shader will overwrite all previous pixels.
  65386. */
  65387. this.autoClear = true;
  65388. /**
  65389. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65390. */
  65391. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65392. /**
  65393. * Animations to be used for the post processing
  65394. */
  65395. this.animations = new Array();
  65396. /**
  65397. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65398. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65399. */
  65400. this.enablePixelPerfectMode = false;
  65401. /**
  65402. * Force the postprocess to be applied without taking in account viewport
  65403. */
  65404. this.forceFullscreenViewport = true;
  65405. /**
  65406. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65407. */
  65408. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65409. /**
  65410. * Force textures to be a power of two (default: false)
  65411. */
  65412. this.alwaysForcePOT = false;
  65413. /**
  65414. * Number of sample textures (default: 1)
  65415. */
  65416. this.samples = 1;
  65417. /**
  65418. * Modify the scale of the post process to be the same as the viewport (default: false)
  65419. */
  65420. this.adaptScaleToCurrentViewport = false;
  65421. this._reusable = false;
  65422. /**
  65423. * Smart array of input and output textures for the post process.
  65424. */
  65425. this._textures = new BABYLON.SmartArray(2);
  65426. /**
  65427. * The index in _textures that corresponds to the output texture.
  65428. */
  65429. this._currentRenderTextureInd = 0;
  65430. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65431. this._texelSize = BABYLON.Vector2.Zero();
  65432. // Events
  65433. /**
  65434. * An event triggered when the postprocess is activated.
  65435. */
  65436. this.onActivateObservable = new BABYLON.Observable();
  65437. /**
  65438. * An event triggered when the postprocess changes its size.
  65439. */
  65440. this.onSizeChangedObservable = new BABYLON.Observable();
  65441. /**
  65442. * An event triggered when the postprocess applies its effect.
  65443. */
  65444. this.onApplyObservable = new BABYLON.Observable();
  65445. /**
  65446. * An event triggered before rendering the postprocess
  65447. */
  65448. this.onBeforeRenderObservable = new BABYLON.Observable();
  65449. /**
  65450. * An event triggered after rendering the postprocess
  65451. */
  65452. this.onAfterRenderObservable = new BABYLON.Observable();
  65453. if (camera != null) {
  65454. this._camera = camera;
  65455. this._scene = camera.getScene();
  65456. camera.attachPostProcess(this);
  65457. this._engine = this._scene.getEngine();
  65458. this._scene.postProcesses.push(this);
  65459. }
  65460. else if (engine) {
  65461. this._engine = engine;
  65462. this._engine.postProcesses.push(this);
  65463. }
  65464. this._options = options;
  65465. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65466. this._reusable = reusable || false;
  65467. this._textureType = textureType;
  65468. this._samplers = samplers || [];
  65469. this._samplers.push("textureSampler");
  65470. this._fragmentUrl = fragmentUrl;
  65471. this._vertexUrl = vertexUrl;
  65472. this._parameters = parameters || [];
  65473. this._parameters.push("scale");
  65474. this._indexParameters = indexParameters;
  65475. if (!blockCompilation) {
  65476. this.updateEffect(defines);
  65477. }
  65478. }
  65479. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65480. /**
  65481. * A function that is added to the onActivateObservable
  65482. */
  65483. set: function (callback) {
  65484. if (this._onActivateObserver) {
  65485. this.onActivateObservable.remove(this._onActivateObserver);
  65486. }
  65487. if (callback) {
  65488. this._onActivateObserver = this.onActivateObservable.add(callback);
  65489. }
  65490. },
  65491. enumerable: true,
  65492. configurable: true
  65493. });
  65494. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65495. /**
  65496. * A function that is added to the onSizeChangedObservable
  65497. */
  65498. set: function (callback) {
  65499. if (this._onSizeChangedObserver) {
  65500. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65501. }
  65502. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65503. },
  65504. enumerable: true,
  65505. configurable: true
  65506. });
  65507. Object.defineProperty(PostProcess.prototype, "onApply", {
  65508. /**
  65509. * A function that is added to the onApplyObservable
  65510. */
  65511. set: function (callback) {
  65512. if (this._onApplyObserver) {
  65513. this.onApplyObservable.remove(this._onApplyObserver);
  65514. }
  65515. this._onApplyObserver = this.onApplyObservable.add(callback);
  65516. },
  65517. enumerable: true,
  65518. configurable: true
  65519. });
  65520. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65521. /**
  65522. * A function that is added to the onBeforeRenderObservable
  65523. */
  65524. set: function (callback) {
  65525. if (this._onBeforeRenderObserver) {
  65526. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65527. }
  65528. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65529. },
  65530. enumerable: true,
  65531. configurable: true
  65532. });
  65533. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65534. /**
  65535. * A function that is added to the onAfterRenderObservable
  65536. */
  65537. set: function (callback) {
  65538. if (this._onAfterRenderObserver) {
  65539. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65540. }
  65541. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65542. },
  65543. enumerable: true,
  65544. configurable: true
  65545. });
  65546. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65547. /**
  65548. * 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
  65549. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65550. */
  65551. get: function () {
  65552. return this._textures.data[this._currentRenderTextureInd];
  65553. },
  65554. set: function (value) {
  65555. this._forcedOutputTexture = value;
  65556. },
  65557. enumerable: true,
  65558. configurable: true
  65559. });
  65560. /**
  65561. * Gets the camera which post process is applied to.
  65562. * @returns The camera the post process is applied to.
  65563. */
  65564. PostProcess.prototype.getCamera = function () {
  65565. return this._camera;
  65566. };
  65567. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65568. /**
  65569. * Gets the texel size of the postprocess.
  65570. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65571. */
  65572. get: function () {
  65573. if (this._shareOutputWithPostProcess) {
  65574. return this._shareOutputWithPostProcess.texelSize;
  65575. }
  65576. if (this._forcedOutputTexture) {
  65577. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65578. }
  65579. return this._texelSize;
  65580. },
  65581. enumerable: true,
  65582. configurable: true
  65583. });
  65584. /**
  65585. * Gets the engine which this post process belongs to.
  65586. * @returns The engine the post process was enabled with.
  65587. */
  65588. PostProcess.prototype.getEngine = function () {
  65589. return this._engine;
  65590. };
  65591. /**
  65592. * The effect that is created when initializing the post process.
  65593. * @returns The created effect corrisponding the the postprocess.
  65594. */
  65595. PostProcess.prototype.getEffect = function () {
  65596. return this._effect;
  65597. };
  65598. /**
  65599. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65600. * @param postProcess The post process to share the output with.
  65601. * @returns This post process.
  65602. */
  65603. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65604. this._disposeTextures();
  65605. this._shareOutputWithPostProcess = postProcess;
  65606. return this;
  65607. };
  65608. /**
  65609. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65610. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65611. */
  65612. PostProcess.prototype.useOwnOutput = function () {
  65613. if (this._textures.length == 0) {
  65614. this._textures = new BABYLON.SmartArray(2);
  65615. }
  65616. this._shareOutputWithPostProcess = null;
  65617. };
  65618. /**
  65619. * Updates the effect with the current post process compile time values and recompiles the shader.
  65620. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65621. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65622. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65623. * @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
  65624. * @param onCompiled Called when the shader has been compiled.
  65625. * @param onError Called if there is an error when compiling a shader.
  65626. */
  65627. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65628. if (defines === void 0) { defines = null; }
  65629. if (uniforms === void 0) { uniforms = null; }
  65630. if (samplers === void 0) { samplers = null; }
  65631. 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);
  65632. };
  65633. /**
  65634. * The post process is reusable if it can be used multiple times within one frame.
  65635. * @returns If the post process is reusable
  65636. */
  65637. PostProcess.prototype.isReusable = function () {
  65638. return this._reusable;
  65639. };
  65640. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65641. PostProcess.prototype.markTextureDirty = function () {
  65642. this.width = -1;
  65643. };
  65644. /**
  65645. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65646. * 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.
  65647. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65648. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65649. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65650. * @returns The target texture that was bound to be written to.
  65651. */
  65652. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65653. var _this = this;
  65654. if (sourceTexture === void 0) { sourceTexture = null; }
  65655. camera = camera || this._camera;
  65656. var scene = camera.getScene();
  65657. var engine = scene.getEngine();
  65658. var maxSize = engine.getCaps().maxTextureSize;
  65659. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65660. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65661. // 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
  65662. var webVRCamera = camera.parent;
  65663. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65664. requiredWidth /= 2;
  65665. }
  65666. var desiredWidth = (this._options.width || requiredWidth);
  65667. var desiredHeight = this._options.height || requiredHeight;
  65668. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65669. if (this.adaptScaleToCurrentViewport) {
  65670. var currentViewport = engine.currentViewport;
  65671. if (currentViewport) {
  65672. desiredWidth *= currentViewport.width;
  65673. desiredHeight *= currentViewport.height;
  65674. }
  65675. }
  65676. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65677. if (!this._options.width) {
  65678. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65679. }
  65680. if (!this._options.height) {
  65681. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65682. }
  65683. }
  65684. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65685. if (this._textures.length > 0) {
  65686. for (var i = 0; i < this._textures.length; i++) {
  65687. this._engine._releaseTexture(this._textures.data[i]);
  65688. }
  65689. this._textures.reset();
  65690. }
  65691. this.width = desiredWidth;
  65692. this.height = desiredHeight;
  65693. var textureSize = { width: this.width, height: this.height };
  65694. var textureOptions = {
  65695. generateMipMaps: false,
  65696. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65697. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65698. samplingMode: this.renderTargetSamplingMode,
  65699. type: this._textureType
  65700. };
  65701. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65702. if (this._reusable) {
  65703. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65704. }
  65705. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65706. this.onSizeChangedObservable.notifyObservers(this);
  65707. }
  65708. this._textures.forEach(function (texture) {
  65709. if (texture.samples !== _this.samples) {
  65710. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65711. }
  65712. });
  65713. }
  65714. var target;
  65715. if (this._shareOutputWithPostProcess) {
  65716. target = this._shareOutputWithPostProcess.inputTexture;
  65717. }
  65718. else if (this._forcedOutputTexture) {
  65719. target = this._forcedOutputTexture;
  65720. this.width = this._forcedOutputTexture.width;
  65721. this.height = this._forcedOutputTexture.height;
  65722. }
  65723. else {
  65724. target = this.inputTexture;
  65725. }
  65726. // Bind the input of this post process to be used as the output of the previous post process.
  65727. if (this.enablePixelPerfectMode) {
  65728. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65729. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65730. }
  65731. else {
  65732. this._scaleRatio.copyFromFloats(1, 1);
  65733. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65734. }
  65735. this.onActivateObservable.notifyObservers(camera);
  65736. // Clear
  65737. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65738. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65739. }
  65740. if (this._reusable) {
  65741. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65742. }
  65743. return target;
  65744. };
  65745. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65746. /**
  65747. * If the post process is supported.
  65748. */
  65749. get: function () {
  65750. return this._effect.isSupported;
  65751. },
  65752. enumerable: true,
  65753. configurable: true
  65754. });
  65755. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65756. /**
  65757. * The aspect ratio of the output texture.
  65758. */
  65759. get: function () {
  65760. if (this._shareOutputWithPostProcess) {
  65761. return this._shareOutputWithPostProcess.aspectRatio;
  65762. }
  65763. if (this._forcedOutputTexture) {
  65764. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65765. }
  65766. return this.width / this.height;
  65767. },
  65768. enumerable: true,
  65769. configurable: true
  65770. });
  65771. /**
  65772. * Get a value indicating if the post-process is ready to be used
  65773. * @returns true if the post-process is ready (shader is compiled)
  65774. */
  65775. PostProcess.prototype.isReady = function () {
  65776. return this._effect && this._effect.isReady();
  65777. };
  65778. /**
  65779. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65780. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65781. */
  65782. PostProcess.prototype.apply = function () {
  65783. // Check
  65784. if (!this._effect || !this._effect.isReady())
  65785. return null;
  65786. // States
  65787. this._engine.enableEffect(this._effect);
  65788. this._engine.setState(false);
  65789. this._engine.setDepthBuffer(false);
  65790. this._engine.setDepthWrite(false);
  65791. // Alpha
  65792. this._engine.setAlphaMode(this.alphaMode);
  65793. if (this.alphaConstants) {
  65794. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65795. }
  65796. // Bind the output texture of the preivous post process as the input to this post process.
  65797. var source;
  65798. if (this._shareOutputWithPostProcess) {
  65799. source = this._shareOutputWithPostProcess.inputTexture;
  65800. }
  65801. else if (this._forcedOutputTexture) {
  65802. source = this._forcedOutputTexture;
  65803. }
  65804. else {
  65805. source = this.inputTexture;
  65806. }
  65807. this._effect._bindTexture("textureSampler", source);
  65808. // Parameters
  65809. this._effect.setVector2("scale", this._scaleRatio);
  65810. this.onApplyObservable.notifyObservers(this._effect);
  65811. return this._effect;
  65812. };
  65813. PostProcess.prototype._disposeTextures = function () {
  65814. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65815. return;
  65816. }
  65817. if (this._textures.length > 0) {
  65818. for (var i = 0; i < this._textures.length; i++) {
  65819. this._engine._releaseTexture(this._textures.data[i]);
  65820. }
  65821. }
  65822. this._textures.dispose();
  65823. };
  65824. /**
  65825. * Disposes the post process.
  65826. * @param camera The camera to dispose the post process on.
  65827. */
  65828. PostProcess.prototype.dispose = function (camera) {
  65829. camera = camera || this._camera;
  65830. this._disposeTextures();
  65831. if (this._scene) {
  65832. var index_1 = this._scene.postProcesses.indexOf(this);
  65833. if (index_1 !== -1) {
  65834. this._scene.postProcesses.splice(index_1, 1);
  65835. }
  65836. }
  65837. else {
  65838. var index_2 = this._engine.postProcesses.indexOf(this);
  65839. if (index_2 !== -1) {
  65840. this._engine.postProcesses.splice(index_2, 1);
  65841. }
  65842. }
  65843. if (!camera) {
  65844. return;
  65845. }
  65846. camera.detachPostProcess(this);
  65847. var index = camera._postProcesses.indexOf(this);
  65848. if (index === 0 && camera._postProcesses.length > 0) {
  65849. var firstPostProcess = this._camera._getFirstPostProcess();
  65850. if (firstPostProcess) {
  65851. firstPostProcess.markTextureDirty();
  65852. }
  65853. }
  65854. this.onActivateObservable.clear();
  65855. this.onAfterRenderObservable.clear();
  65856. this.onApplyObservable.clear();
  65857. this.onBeforeRenderObservable.clear();
  65858. this.onSizeChangedObservable.clear();
  65859. };
  65860. return PostProcess;
  65861. }());
  65862. BABYLON.PostProcess = PostProcess;
  65863. })(BABYLON || (BABYLON = {}));
  65864. //# sourceMappingURL=babylon.postProcess.js.map
  65865. var BABYLON;
  65866. (function (BABYLON) {
  65867. var PassPostProcess = /** @class */ (function (_super) {
  65868. __extends(PassPostProcess, _super);
  65869. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65870. if (camera === void 0) { camera = null; }
  65871. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65872. if (blockCompilation === void 0) { blockCompilation = false; }
  65873. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65874. }
  65875. return PassPostProcess;
  65876. }(BABYLON.PostProcess));
  65877. BABYLON.PassPostProcess = PassPostProcess;
  65878. })(BABYLON || (BABYLON = {}));
  65879. //# sourceMappingURL=babylon.passPostProcess.js.map
  65880. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65881. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65882. s = arguments[i];
  65883. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65884. t[p] = s[p];
  65885. }
  65886. return t;
  65887. };
  65888. var BABYLON;
  65889. (function (BABYLON) {
  65890. /**
  65891. * Default implementation IShadowGenerator.
  65892. * This is the main object responsible of generating shadows in the framework.
  65893. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65894. */
  65895. var ShadowGenerator = /** @class */ (function () {
  65896. /**
  65897. * Creates a ShadowGenerator object.
  65898. * A ShadowGenerator is the required tool to use the shadows.
  65899. * Each light casting shadows needs to use its own ShadowGenerator.
  65900. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65901. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65902. * @param light The light object generating the shadows.
  65903. * @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.
  65904. */
  65905. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65906. this._bias = 0.00005;
  65907. this._normalBias = 0;
  65908. this._blurBoxOffset = 1;
  65909. this._blurScale = 2;
  65910. this._blurKernel = 1;
  65911. this._useKernelBlur = false;
  65912. this._filter = ShadowGenerator.FILTER_NONE;
  65913. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65914. this._contactHardeningLightSizeUVRatio = 0.1;
  65915. this._darkness = 0;
  65916. this._transparencyShadow = false;
  65917. /**
  65918. * Controls the extent to which the shadows fade out at the edge of the frustum
  65919. * Used only by directionals and spots
  65920. */
  65921. this.frustumEdgeFalloff = 0;
  65922. /**
  65923. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65924. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65925. * It might on the other hand introduce peter panning.
  65926. */
  65927. this.forceBackFacesOnly = false;
  65928. this._lightDirection = BABYLON.Vector3.Zero();
  65929. this._viewMatrix = BABYLON.Matrix.Zero();
  65930. this._projectionMatrix = BABYLON.Matrix.Zero();
  65931. this._transformMatrix = BABYLON.Matrix.Zero();
  65932. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65933. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65934. this._currentFaceIndex = 0;
  65935. this._currentFaceIndexCache = 0;
  65936. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65937. this._mapSize = mapSize;
  65938. this._light = light;
  65939. this._scene = light.getScene();
  65940. light._shadowGenerator = this;
  65941. // Texture type fallback from float to int if not supported.
  65942. var caps = this._scene.getEngine().getCaps();
  65943. if (!useFullFloatFirst) {
  65944. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65945. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65946. }
  65947. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65948. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65949. }
  65950. else {
  65951. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65952. }
  65953. }
  65954. else {
  65955. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65956. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65957. }
  65958. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65959. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65960. }
  65961. else {
  65962. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65963. }
  65964. }
  65965. this._initializeGenerator();
  65966. this._applyFilterValues();
  65967. }
  65968. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65969. /**
  65970. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65971. */
  65972. get: function () {
  65973. return this._bias;
  65974. },
  65975. /**
  65976. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65977. */
  65978. set: function (bias) {
  65979. this._bias = bias;
  65980. },
  65981. enumerable: true,
  65982. configurable: true
  65983. });
  65984. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65985. /**
  65986. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65987. */
  65988. get: function () {
  65989. return this._normalBias;
  65990. },
  65991. /**
  65992. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65993. */
  65994. set: function (normalBias) {
  65995. this._normalBias = normalBias;
  65996. },
  65997. enumerable: true,
  65998. configurable: true
  65999. });
  66000. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66001. /**
  66002. * Gets the blur box offset: offset applied during the blur pass.
  66003. * Only usefull if useKernelBlur = false
  66004. */
  66005. get: function () {
  66006. return this._blurBoxOffset;
  66007. },
  66008. /**
  66009. * Sets the blur box offset: offset applied during the blur pass.
  66010. * Only usefull if useKernelBlur = false
  66011. */
  66012. set: function (value) {
  66013. if (this._blurBoxOffset === value) {
  66014. return;
  66015. }
  66016. this._blurBoxOffset = value;
  66017. this._disposeBlurPostProcesses();
  66018. },
  66019. enumerable: true,
  66020. configurable: true
  66021. });
  66022. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66023. /**
  66024. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66025. * 2 means half of the size.
  66026. */
  66027. get: function () {
  66028. return this._blurScale;
  66029. },
  66030. /**
  66031. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66032. * 2 means half of the size.
  66033. */
  66034. set: function (value) {
  66035. if (this._blurScale === value) {
  66036. return;
  66037. }
  66038. this._blurScale = value;
  66039. this._disposeBlurPostProcesses();
  66040. },
  66041. enumerable: true,
  66042. configurable: true
  66043. });
  66044. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66045. /**
  66046. * Gets the blur kernel: kernel size of the blur pass.
  66047. * Only usefull if useKernelBlur = true
  66048. */
  66049. get: function () {
  66050. return this._blurKernel;
  66051. },
  66052. /**
  66053. * Sets the blur kernel: kernel size of the blur pass.
  66054. * Only usefull if useKernelBlur = true
  66055. */
  66056. set: function (value) {
  66057. if (this._blurKernel === value) {
  66058. return;
  66059. }
  66060. this._blurKernel = value;
  66061. this._disposeBlurPostProcesses();
  66062. },
  66063. enumerable: true,
  66064. configurable: true
  66065. });
  66066. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66067. /**
  66068. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66069. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66070. */
  66071. get: function () {
  66072. return this._useKernelBlur;
  66073. },
  66074. /**
  66075. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66076. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66077. */
  66078. set: function (value) {
  66079. if (this._useKernelBlur === value) {
  66080. return;
  66081. }
  66082. this._useKernelBlur = value;
  66083. this._disposeBlurPostProcesses();
  66084. },
  66085. enumerable: true,
  66086. configurable: true
  66087. });
  66088. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66089. /**
  66090. * Gets the depth scale used in ESM mode.
  66091. */
  66092. get: function () {
  66093. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66094. },
  66095. /**
  66096. * Sets the depth scale used in ESM mode.
  66097. * This can override the scale stored on the light.
  66098. */
  66099. set: function (value) {
  66100. this._depthScale = value;
  66101. },
  66102. enumerable: true,
  66103. configurable: true
  66104. });
  66105. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66106. /**
  66107. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66108. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66109. */
  66110. get: function () {
  66111. return this._filter;
  66112. },
  66113. /**
  66114. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66115. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66116. */
  66117. set: function (value) {
  66118. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66119. if (this._light.needCube()) {
  66120. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66121. this.useExponentialShadowMap = true;
  66122. return;
  66123. }
  66124. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66125. this.useCloseExponentialShadowMap = true;
  66126. return;
  66127. }
  66128. // PCF on cubemap would also be expensive
  66129. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66130. this.usePoissonSampling = true;
  66131. return;
  66132. }
  66133. }
  66134. // Weblg1 fallback for PCF.
  66135. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66136. if (this._scene.getEngine().webGLVersion === 1) {
  66137. this.usePoissonSampling = true;
  66138. return;
  66139. }
  66140. }
  66141. if (this._filter === value) {
  66142. return;
  66143. }
  66144. this._filter = value;
  66145. this._disposeBlurPostProcesses();
  66146. this._applyFilterValues();
  66147. this._light._markMeshesAsLightDirty();
  66148. },
  66149. enumerable: true,
  66150. configurable: true
  66151. });
  66152. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66153. /**
  66154. * Gets if the current filter is set to Poisson Sampling.
  66155. */
  66156. get: function () {
  66157. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66158. },
  66159. /**
  66160. * Sets the current filter to Poisson Sampling.
  66161. */
  66162. set: function (value) {
  66163. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66164. return;
  66165. }
  66166. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66167. },
  66168. enumerable: true,
  66169. configurable: true
  66170. });
  66171. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66172. /**
  66173. * Gets if the current filter is set to VSM.
  66174. * DEPRECATED. Should use useExponentialShadowMap instead.
  66175. */
  66176. get: function () {
  66177. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66178. return this.useExponentialShadowMap;
  66179. },
  66180. /**
  66181. * Sets the current filter is to VSM.
  66182. * DEPRECATED. Should use useExponentialShadowMap instead.
  66183. */
  66184. set: function (value) {
  66185. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66186. this.useExponentialShadowMap = value;
  66187. },
  66188. enumerable: true,
  66189. configurable: true
  66190. });
  66191. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66192. /**
  66193. * Gets if the current filter is set to blurred VSM.
  66194. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66195. */
  66196. get: function () {
  66197. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66198. return this.useBlurExponentialShadowMap;
  66199. },
  66200. /**
  66201. * Sets the current filter is to blurred VSM.
  66202. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66203. */
  66204. set: function (value) {
  66205. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66206. this.useBlurExponentialShadowMap = value;
  66207. },
  66208. enumerable: true,
  66209. configurable: true
  66210. });
  66211. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66212. /**
  66213. * Gets if the current filter is set to ESM.
  66214. */
  66215. get: function () {
  66216. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66217. },
  66218. /**
  66219. * Sets the current filter is to ESM.
  66220. */
  66221. set: function (value) {
  66222. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66223. return;
  66224. }
  66225. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66226. },
  66227. enumerable: true,
  66228. configurable: true
  66229. });
  66230. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66231. /**
  66232. * Gets if the current filter is set to filtered ESM.
  66233. */
  66234. get: function () {
  66235. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66236. },
  66237. /**
  66238. * Gets if the current filter is set to filtered ESM.
  66239. */
  66240. set: function (value) {
  66241. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66242. return;
  66243. }
  66244. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66245. },
  66246. enumerable: true,
  66247. configurable: true
  66248. });
  66249. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66250. /**
  66251. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66252. * exponential to prevent steep falloff artifacts).
  66253. */
  66254. get: function () {
  66255. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66256. },
  66257. /**
  66258. * Sets the current filter to "close ESM" (using the inverse of the
  66259. * exponential to prevent steep falloff artifacts).
  66260. */
  66261. set: function (value) {
  66262. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66263. return;
  66264. }
  66265. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66266. },
  66267. enumerable: true,
  66268. configurable: true
  66269. });
  66270. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66271. /**
  66272. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66273. * exponential to prevent steep falloff artifacts).
  66274. */
  66275. get: function () {
  66276. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66277. },
  66278. /**
  66279. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66280. * exponential to prevent steep falloff artifacts).
  66281. */
  66282. set: function (value) {
  66283. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66284. return;
  66285. }
  66286. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66287. },
  66288. enumerable: true,
  66289. configurable: true
  66290. });
  66291. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66292. /**
  66293. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66294. */
  66295. get: function () {
  66296. return this.filter === ShadowGenerator.FILTER_PCF;
  66297. },
  66298. /**
  66299. * Sets the current filter to "PCF" (percentage closer filtering).
  66300. */
  66301. set: function (value) {
  66302. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66303. return;
  66304. }
  66305. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66306. },
  66307. enumerable: true,
  66308. configurable: true
  66309. });
  66310. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66311. /**
  66312. * Gets the PCF or PCSS Quality.
  66313. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66314. */
  66315. get: function () {
  66316. return this._filteringQuality;
  66317. },
  66318. /**
  66319. * Sets the PCF or PCSS Quality.
  66320. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66321. */
  66322. set: function (filteringQuality) {
  66323. this._filteringQuality = filteringQuality;
  66324. },
  66325. enumerable: true,
  66326. configurable: true
  66327. });
  66328. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66329. /**
  66330. * Gets if the current filter is set to "PCSS" (contact hardening).
  66331. */
  66332. get: function () {
  66333. return this.filter === ShadowGenerator.FILTER_PCSS;
  66334. },
  66335. /**
  66336. * Sets the current filter to "PCSS" (contact hardening).
  66337. */
  66338. set: function (value) {
  66339. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66340. return;
  66341. }
  66342. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66343. },
  66344. enumerable: true,
  66345. configurable: true
  66346. });
  66347. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66348. /**
  66349. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66350. * Using a ratio helps keeping shape stability independently of the map size.
  66351. *
  66352. * It does not account for the light projection as it was having too much
  66353. * instability during the light setup or during light position changes.
  66354. *
  66355. * Only valid if useContactHardeningShadow is true.
  66356. */
  66357. get: function () {
  66358. return this._contactHardeningLightSizeUVRatio;
  66359. },
  66360. /**
  66361. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66362. * Using a ratio helps keeping shape stability independently of the map size.
  66363. *
  66364. * It does not account for the light projection as it was having too much
  66365. * instability during the light setup or during light position changes.
  66366. *
  66367. * Only valid if useContactHardeningShadow is true.
  66368. */
  66369. set: function (contactHardeningLightSizeUVRatio) {
  66370. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66371. },
  66372. enumerable: true,
  66373. configurable: true
  66374. });
  66375. /**
  66376. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66377. * 0 means strongest and 1 would means no shadow.
  66378. * @returns the darkness.
  66379. */
  66380. ShadowGenerator.prototype.getDarkness = function () {
  66381. return this._darkness;
  66382. };
  66383. /**
  66384. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66385. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66386. * @returns the shadow generator allowing fluent coding.
  66387. */
  66388. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66389. if (darkness >= 1.0)
  66390. this._darkness = 1.0;
  66391. else if (darkness <= 0.0)
  66392. this._darkness = 0.0;
  66393. else
  66394. this._darkness = darkness;
  66395. return this;
  66396. };
  66397. /**
  66398. * Sets the ability to have transparent shadow (boolean).
  66399. * @param transparent True if transparent else False
  66400. * @returns the shadow generator allowing fluent coding
  66401. */
  66402. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66403. this._transparencyShadow = transparent;
  66404. return this;
  66405. };
  66406. /**
  66407. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66408. * @returns The render target texture if present otherwise, null
  66409. */
  66410. ShadowGenerator.prototype.getShadowMap = function () {
  66411. return this._shadowMap;
  66412. };
  66413. /**
  66414. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66415. * @returns The render target texture if the shadow map is present otherwise, null
  66416. */
  66417. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66418. if (this._shadowMap2) {
  66419. return this._shadowMap2;
  66420. }
  66421. return this._shadowMap;
  66422. };
  66423. /**
  66424. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66425. * @param mesh Mesh to add
  66426. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66427. * @returns the Shadow Generator itself
  66428. */
  66429. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66430. if (includeDescendants === void 0) { includeDescendants = true; }
  66431. if (!this._shadowMap) {
  66432. return this;
  66433. }
  66434. if (!this._shadowMap.renderList) {
  66435. this._shadowMap.renderList = [];
  66436. }
  66437. this._shadowMap.renderList.push(mesh);
  66438. if (includeDescendants) {
  66439. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66440. }
  66441. return this;
  66442. var _a;
  66443. };
  66444. /**
  66445. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66446. * @param mesh Mesh to remove
  66447. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66448. * @returns the Shadow Generator itself
  66449. */
  66450. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66451. if (includeDescendants === void 0) { includeDescendants = true; }
  66452. if (!this._shadowMap || !this._shadowMap.renderList) {
  66453. return this;
  66454. }
  66455. var index = this._shadowMap.renderList.indexOf(mesh);
  66456. if (index !== -1) {
  66457. this._shadowMap.renderList.splice(index, 1);
  66458. }
  66459. if (includeDescendants) {
  66460. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66461. var child = _a[_i];
  66462. this.removeShadowCaster(child);
  66463. }
  66464. }
  66465. return this;
  66466. };
  66467. /**
  66468. * Returns the associated light object.
  66469. * @returns the light generating the shadow
  66470. */
  66471. ShadowGenerator.prototype.getLight = function () {
  66472. return this._light;
  66473. };
  66474. ShadowGenerator.prototype._initializeGenerator = function () {
  66475. this._light._markMeshesAsLightDirty();
  66476. this._initializeShadowMap();
  66477. };
  66478. ShadowGenerator.prototype._initializeShadowMap = function () {
  66479. var _this = this;
  66480. // Render target
  66481. var engine = this._scene.getEngine();
  66482. if (engine.webGLVersion > 1) {
  66483. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66484. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66485. }
  66486. else {
  66487. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66488. }
  66489. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66490. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66491. this._shadowMap.anisotropicFilteringLevel = 1;
  66492. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66493. this._shadowMap.renderParticles = false;
  66494. this._shadowMap.ignoreCameraViewport = true;
  66495. // Record Face Index before render.
  66496. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66497. _this._currentFaceIndex = faceIndex;
  66498. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66499. engine.setColorWrite(false);
  66500. }
  66501. });
  66502. // Custom render function.
  66503. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66504. // Blur if required afer render.
  66505. this._shadowMap.onAfterUnbindObservable.add(function () {
  66506. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66507. engine.setColorWrite(true);
  66508. }
  66509. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66510. return;
  66511. }
  66512. var shadowMap = _this.getShadowMapForRendering();
  66513. if (shadowMap) {
  66514. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66515. }
  66516. });
  66517. // Clear according to the chosen filter.
  66518. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66519. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66520. this._shadowMap.onClearObservable.add(function (engine) {
  66521. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66522. engine.clear(clearOne, false, true, false);
  66523. }
  66524. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66525. engine.clear(clearZero, true, true, false);
  66526. }
  66527. else {
  66528. engine.clear(clearOne, true, true, false);
  66529. }
  66530. });
  66531. };
  66532. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66533. var _this = this;
  66534. var engine = this._scene.getEngine();
  66535. var targetSize = this._mapSize / this.blurScale;
  66536. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66537. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66538. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66539. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66540. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66541. }
  66542. if (this.useKernelBlur) {
  66543. 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);
  66544. this._kernelBlurXPostprocess.width = targetSize;
  66545. this._kernelBlurXPostprocess.height = targetSize;
  66546. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66547. effect.setTexture("textureSampler", _this._shadowMap);
  66548. });
  66549. 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);
  66550. this._kernelBlurXPostprocess.autoClear = false;
  66551. this._kernelBlurYPostprocess.autoClear = false;
  66552. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66553. this._kernelBlurXPostprocess.packedFloat = true;
  66554. this._kernelBlurYPostprocess.packedFloat = true;
  66555. }
  66556. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66557. }
  66558. else {
  66559. 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);
  66560. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66561. effect.setFloat2("screenSize", targetSize, targetSize);
  66562. effect.setTexture("textureSampler", _this._shadowMap);
  66563. });
  66564. this._boxBlurPostprocess.autoClear = false;
  66565. this._blurPostProcesses = [this._boxBlurPostprocess];
  66566. }
  66567. };
  66568. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66569. var index;
  66570. var engine = this._scene.getEngine();
  66571. if (depthOnlySubMeshes.length) {
  66572. engine.setColorWrite(false);
  66573. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66574. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66575. }
  66576. engine.setColorWrite(true);
  66577. }
  66578. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66579. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66580. }
  66581. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66582. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66583. }
  66584. if (this._transparencyShadow) {
  66585. for (index = 0; index < transparentSubMeshes.length; index++) {
  66586. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66587. }
  66588. }
  66589. };
  66590. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66591. var _this = this;
  66592. var mesh = subMesh.getRenderingMesh();
  66593. var scene = this._scene;
  66594. var engine = scene.getEngine();
  66595. var material = subMesh.getMaterial();
  66596. if (!material) {
  66597. return;
  66598. }
  66599. // Culling
  66600. engine.setState(material.backFaceCulling);
  66601. // Managing instances
  66602. var batch = mesh._getInstancesRenderList(subMesh._id);
  66603. if (batch.mustReturn) {
  66604. return;
  66605. }
  66606. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66607. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66608. engine.enableEffect(this._effect);
  66609. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66610. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66611. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66612. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66613. this._effect.setVector3("lightData", this._cachedDirection);
  66614. }
  66615. else {
  66616. this._effect.setVector3("lightData", this._cachedPosition);
  66617. }
  66618. if (scene.activeCamera) {
  66619. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66620. }
  66621. // Alpha test
  66622. if (material && material.needAlphaTesting()) {
  66623. var alphaTexture = material.getAlphaTestTexture();
  66624. if (alphaTexture) {
  66625. this._effect.setTexture("diffuseSampler", alphaTexture);
  66626. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66627. }
  66628. }
  66629. // Bones
  66630. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66631. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66632. }
  66633. // Morph targets
  66634. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66635. if (this.forceBackFacesOnly) {
  66636. engine.setState(true, 0, false, true);
  66637. }
  66638. // Draw
  66639. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66640. if (this.forceBackFacesOnly) {
  66641. engine.setState(true, 0, false, false);
  66642. }
  66643. }
  66644. else {
  66645. // Need to reset refresh rate of the shadowMap
  66646. if (this._shadowMap) {
  66647. this._shadowMap.resetRefreshCounter();
  66648. }
  66649. }
  66650. };
  66651. ShadowGenerator.prototype._applyFilterValues = function () {
  66652. if (!this._shadowMap) {
  66653. return;
  66654. }
  66655. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66656. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66657. }
  66658. else {
  66659. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66660. }
  66661. };
  66662. /**
  66663. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66664. * @param onCompiled Callback triggered at the and of the effects compilation
  66665. * @param options Sets of optional options forcing the compilation with different modes
  66666. */
  66667. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66668. var _this = this;
  66669. var localOptions = __assign({ useInstances: false }, options);
  66670. var shadowMap = this.getShadowMap();
  66671. if (!shadowMap) {
  66672. if (onCompiled) {
  66673. onCompiled(this);
  66674. }
  66675. return;
  66676. }
  66677. var renderList = shadowMap.renderList;
  66678. if (!renderList) {
  66679. if (onCompiled) {
  66680. onCompiled(this);
  66681. }
  66682. return;
  66683. }
  66684. var subMeshes = new Array();
  66685. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66686. var mesh = renderList_1[_i];
  66687. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66688. }
  66689. if (subMeshes.length === 0) {
  66690. if (onCompiled) {
  66691. onCompiled(this);
  66692. }
  66693. return;
  66694. }
  66695. var currentIndex = 0;
  66696. var checkReady = function () {
  66697. if (!_this._scene || !_this._scene.getEngine()) {
  66698. return;
  66699. }
  66700. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66701. currentIndex++;
  66702. if (currentIndex >= subMeshes.length) {
  66703. if (onCompiled) {
  66704. onCompiled(_this);
  66705. }
  66706. return;
  66707. }
  66708. }
  66709. setTimeout(checkReady, 16);
  66710. };
  66711. checkReady();
  66712. };
  66713. /**
  66714. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66715. * @param options Sets of optional options forcing the compilation with different modes
  66716. * @returns A promise that resolves when the compilation completes
  66717. */
  66718. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66719. var _this = this;
  66720. return new Promise(function (resolve) {
  66721. _this.forceCompilation(function () {
  66722. resolve();
  66723. }, options);
  66724. });
  66725. };
  66726. /**
  66727. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66728. * @param subMesh The submesh we want to render in the shadow map
  66729. * @param useInstances Defines wether will draw in the map using instances
  66730. * @returns true if ready otherwise, false
  66731. */
  66732. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66733. var defines = [];
  66734. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66735. defines.push("#define FLOAT");
  66736. }
  66737. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66738. defines.push("#define ESM");
  66739. }
  66740. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66741. defines.push("#define DEPTHTEXTURE");
  66742. }
  66743. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66744. var mesh = subMesh.getMesh();
  66745. var material = subMesh.getMaterial();
  66746. // Normal bias.
  66747. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66748. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66749. defines.push("#define NORMAL");
  66750. if (mesh.nonUniformScaling) {
  66751. defines.push("#define NONUNIFORMSCALING");
  66752. }
  66753. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66754. defines.push("#define DIRECTIONINLIGHTDATA");
  66755. }
  66756. }
  66757. // Alpha test
  66758. if (material && material.needAlphaTesting()) {
  66759. var alphaTexture = material.getAlphaTestTexture();
  66760. if (alphaTexture) {
  66761. defines.push("#define ALPHATEST");
  66762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66763. attribs.push(BABYLON.VertexBuffer.UVKind);
  66764. defines.push("#define UV1");
  66765. }
  66766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66767. if (alphaTexture.coordinatesIndex === 1) {
  66768. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66769. defines.push("#define UV2");
  66770. }
  66771. }
  66772. }
  66773. }
  66774. // Bones
  66775. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66776. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66777. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66778. if (mesh.numBoneInfluencers > 4) {
  66779. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66780. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66781. }
  66782. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66783. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66784. }
  66785. else {
  66786. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66787. }
  66788. // Morph targets
  66789. var manager = mesh.morphTargetManager;
  66790. var morphInfluencers = 0;
  66791. if (manager) {
  66792. if (manager.numInfluencers > 0) {
  66793. defines.push("#define MORPHTARGETS");
  66794. morphInfluencers = manager.numInfluencers;
  66795. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66796. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66797. }
  66798. }
  66799. // Instances
  66800. if (useInstances) {
  66801. defines.push("#define INSTANCES");
  66802. attribs.push("world0");
  66803. attribs.push("world1");
  66804. attribs.push("world2");
  66805. attribs.push("world3");
  66806. }
  66807. // Get correct effect
  66808. var join = defines.join("\n");
  66809. if (this._cachedDefines !== join) {
  66810. this._cachedDefines = join;
  66811. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66812. }
  66813. if (!this._effect.isReady()) {
  66814. return false;
  66815. }
  66816. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66817. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66818. this._initializeBlurRTTAndPostProcesses();
  66819. }
  66820. }
  66821. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66822. return false;
  66823. }
  66824. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66825. return false;
  66826. }
  66827. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66828. return false;
  66829. }
  66830. return true;
  66831. };
  66832. /**
  66833. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66834. * @param defines Defines of the material we want to update
  66835. * @param lightIndex Index of the light in the enabled light list of the material
  66836. */
  66837. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66838. var scene = this._scene;
  66839. var light = this._light;
  66840. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66841. return;
  66842. }
  66843. defines["SHADOW" + lightIndex] = true;
  66844. if (this.useContactHardeningShadow) {
  66845. defines["SHADOWPCSS" + lightIndex] = true;
  66846. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66847. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66848. }
  66849. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66850. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66851. }
  66852. // else default to high.
  66853. }
  66854. if (this.usePercentageCloserFiltering) {
  66855. defines["SHADOWPCF" + lightIndex] = true;
  66856. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66857. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66858. }
  66859. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66860. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66861. }
  66862. // else default to high.
  66863. }
  66864. else if (this.usePoissonSampling) {
  66865. defines["SHADOWPOISSON" + lightIndex] = true;
  66866. }
  66867. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66868. defines["SHADOWESM" + lightIndex] = true;
  66869. }
  66870. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66871. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66872. }
  66873. if (light.needCube()) {
  66874. defines["SHADOWCUBE" + lightIndex] = true;
  66875. }
  66876. };
  66877. /**
  66878. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66879. * defined in the generator but impacting the effect).
  66880. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66881. * @param effect The effect we are binfing the information for
  66882. */
  66883. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66884. var light = this._light;
  66885. var scene = this._scene;
  66886. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66887. return;
  66888. }
  66889. var camera = scene.activeCamera;
  66890. if (!camera) {
  66891. return;
  66892. }
  66893. var shadowMap = this.getShadowMap();
  66894. if (!shadowMap) {
  66895. return;
  66896. }
  66897. if (!light.needCube()) {
  66898. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66899. }
  66900. // Only PCF uses depth stencil texture.
  66901. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66902. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66903. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66904. }
  66905. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66906. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66907. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66908. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66909. }
  66910. else {
  66911. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66912. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66913. }
  66914. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66915. };
  66916. /**
  66917. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66918. * (eq to shadow prjection matrix * light transform matrix)
  66919. * @returns The transform matrix used to create the shadow map
  66920. */
  66921. ShadowGenerator.prototype.getTransformMatrix = function () {
  66922. var scene = this._scene;
  66923. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66924. return this._transformMatrix;
  66925. }
  66926. this._currentRenderID = scene.getRenderId();
  66927. this._currentFaceIndexCache = this._currentFaceIndex;
  66928. var lightPosition = this._light.position;
  66929. if (this._light.computeTransformedInformation()) {
  66930. lightPosition = this._light.transformedPosition;
  66931. }
  66932. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66933. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66934. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66935. }
  66936. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66937. this._cachedPosition.copyFrom(lightPosition);
  66938. this._cachedDirection.copyFrom(this._lightDirection);
  66939. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66940. var shadowMap = this.getShadowMap();
  66941. if (shadowMap) {
  66942. var renderList = shadowMap.renderList;
  66943. if (renderList) {
  66944. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66945. }
  66946. }
  66947. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66948. }
  66949. return this._transformMatrix;
  66950. };
  66951. /**
  66952. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66953. * Cube and 2D textures for instance.
  66954. */
  66955. ShadowGenerator.prototype.recreateShadowMap = function () {
  66956. var shadowMap = this._shadowMap;
  66957. if (!shadowMap) {
  66958. return;
  66959. }
  66960. // Track render list.
  66961. var renderList = shadowMap.renderList;
  66962. // Clean up existing data.
  66963. this._disposeRTTandPostProcesses();
  66964. // Reinitializes.
  66965. this._initializeGenerator();
  66966. // Reaffect the filter to ensure a correct fallback if necessary.
  66967. this.filter = this.filter;
  66968. // Reaffect the filter.
  66969. this._applyFilterValues();
  66970. // Reaffect Render List.
  66971. this._shadowMap.renderList = renderList;
  66972. };
  66973. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66974. if (this._shadowMap2) {
  66975. this._shadowMap2.dispose();
  66976. this._shadowMap2 = null;
  66977. }
  66978. if (this._boxBlurPostprocess) {
  66979. this._boxBlurPostprocess.dispose();
  66980. this._boxBlurPostprocess = null;
  66981. }
  66982. if (this._kernelBlurXPostprocess) {
  66983. this._kernelBlurXPostprocess.dispose();
  66984. this._kernelBlurXPostprocess = null;
  66985. }
  66986. if (this._kernelBlurYPostprocess) {
  66987. this._kernelBlurYPostprocess.dispose();
  66988. this._kernelBlurYPostprocess = null;
  66989. }
  66990. this._blurPostProcesses = [];
  66991. };
  66992. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66993. if (this._shadowMap) {
  66994. this._shadowMap.dispose();
  66995. this._shadowMap = null;
  66996. }
  66997. this._disposeBlurPostProcesses();
  66998. };
  66999. /**
  67000. * Disposes the ShadowGenerator.
  67001. * Returns nothing.
  67002. */
  67003. ShadowGenerator.prototype.dispose = function () {
  67004. this._disposeRTTandPostProcesses();
  67005. if (this._light) {
  67006. this._light._shadowGenerator = null;
  67007. this._light._markMeshesAsLightDirty();
  67008. }
  67009. };
  67010. /**
  67011. * Serializes the shadow generator setup to a json object.
  67012. * @returns The serialized JSON object
  67013. */
  67014. ShadowGenerator.prototype.serialize = function () {
  67015. var serializationObject = {};
  67016. var shadowMap = this.getShadowMap();
  67017. if (!shadowMap) {
  67018. return serializationObject;
  67019. }
  67020. serializationObject.lightId = this._light.id;
  67021. serializationObject.mapSize = shadowMap.getRenderSize();
  67022. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67023. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67024. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67025. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67026. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67027. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67028. serializationObject.depthScale = this.depthScale;
  67029. serializationObject.darkness = this.getDarkness();
  67030. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67031. serializationObject.blurKernel = this.blurKernel;
  67032. serializationObject.blurScale = this.blurScale;
  67033. serializationObject.useKernelBlur = this.useKernelBlur;
  67034. serializationObject.transparencyShadow = this._transparencyShadow;
  67035. serializationObject.bias = this.bias;
  67036. serializationObject.normalBias = this.normalBias;
  67037. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67038. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67039. serializationObject.filteringQuality = this.filteringQuality;
  67040. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67041. serializationObject.renderList = [];
  67042. if (shadowMap.renderList) {
  67043. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67044. var mesh = shadowMap.renderList[meshIndex];
  67045. serializationObject.renderList.push(mesh.id);
  67046. }
  67047. }
  67048. return serializationObject;
  67049. };
  67050. /**
  67051. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67052. * @param parsedShadowGenerator The JSON object to parse
  67053. * @param scene The scene to create the shadow map for
  67054. * @returns The parsed shadow generator
  67055. */
  67056. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67057. //casting to point light, as light is missing the position attr and typescript complains.
  67058. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67059. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67060. var shadowMap = shadowGenerator.getShadowMap();
  67061. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67062. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67063. meshes.forEach(function (mesh) {
  67064. if (!shadowMap) {
  67065. return;
  67066. }
  67067. if (!shadowMap.renderList) {
  67068. shadowMap.renderList = [];
  67069. }
  67070. shadowMap.renderList.push(mesh);
  67071. });
  67072. }
  67073. if (parsedShadowGenerator.usePoissonSampling) {
  67074. shadowGenerator.usePoissonSampling = true;
  67075. }
  67076. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67077. shadowGenerator.useExponentialShadowMap = true;
  67078. }
  67079. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67080. shadowGenerator.useBlurExponentialShadowMap = true;
  67081. }
  67082. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67083. shadowGenerator.useCloseExponentialShadowMap = true;
  67084. }
  67085. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67086. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67087. }
  67088. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67089. shadowGenerator.usePercentageCloserFiltering = true;
  67090. }
  67091. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67092. shadowGenerator.useContactHardeningShadow = true;
  67093. }
  67094. if (parsedShadowGenerator.filteringQuality) {
  67095. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67096. }
  67097. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67098. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67099. }
  67100. // Backward compat
  67101. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67102. shadowGenerator.useExponentialShadowMap = true;
  67103. }
  67104. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67105. shadowGenerator.useBlurExponentialShadowMap = true;
  67106. }
  67107. if (parsedShadowGenerator.depthScale) {
  67108. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67109. }
  67110. if (parsedShadowGenerator.blurScale) {
  67111. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67112. }
  67113. if (parsedShadowGenerator.blurBoxOffset) {
  67114. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67115. }
  67116. if (parsedShadowGenerator.useKernelBlur) {
  67117. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67118. }
  67119. if (parsedShadowGenerator.blurKernel) {
  67120. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67121. }
  67122. if (parsedShadowGenerator.bias !== undefined) {
  67123. shadowGenerator.bias = parsedShadowGenerator.bias;
  67124. }
  67125. if (parsedShadowGenerator.normalBias !== undefined) {
  67126. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67127. }
  67128. if (parsedShadowGenerator.darkness) {
  67129. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67130. }
  67131. if (parsedShadowGenerator.transparencyShadow) {
  67132. shadowGenerator.setTransparencyShadow(true);
  67133. }
  67134. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67135. return shadowGenerator;
  67136. };
  67137. /**
  67138. * Shadow generator mode None: no filtering applied.
  67139. */
  67140. ShadowGenerator.FILTER_NONE = 0;
  67141. /**
  67142. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67143. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67144. */
  67145. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67146. /**
  67147. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67148. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67149. */
  67150. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67151. /**
  67152. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67153. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67154. */
  67155. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67156. /**
  67157. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67158. * edge artifacts on steep falloff.
  67159. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67160. */
  67161. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67162. /**
  67163. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67164. * edge artifacts on steep falloff.
  67165. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67166. */
  67167. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67168. /**
  67169. * Shadow generator mode PCF: Percentage Closer Filtering
  67170. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67171. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67172. */
  67173. ShadowGenerator.FILTER_PCF = 6;
  67174. /**
  67175. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67176. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67177. * Contact Hardening
  67178. */
  67179. ShadowGenerator.FILTER_PCSS = 7;
  67180. /**
  67181. * Reserved for PCF and PCSS
  67182. * Highest Quality.
  67183. *
  67184. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67185. *
  67186. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67187. */
  67188. ShadowGenerator.QUALITY_HIGH = 0;
  67189. /**
  67190. * Reserved for PCF and PCSS
  67191. * Good tradeoff for quality/perf cross devices
  67192. *
  67193. * Execute PCF on a 3*3 kernel.
  67194. *
  67195. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67196. */
  67197. ShadowGenerator.QUALITY_MEDIUM = 1;
  67198. /**
  67199. * Reserved for PCF and PCSS
  67200. * The lowest quality but the fastest.
  67201. *
  67202. * Execute PCF on a 1*1 kernel.
  67203. *
  67204. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67205. */
  67206. ShadowGenerator.QUALITY_LOW = 2;
  67207. return ShadowGenerator;
  67208. }());
  67209. BABYLON.ShadowGenerator = ShadowGenerator;
  67210. })(BABYLON || (BABYLON = {}));
  67211. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67212. var BABYLON;
  67213. (function (BABYLON) {
  67214. var DefaultLoadingScreen = /** @class */ (function () {
  67215. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67216. if (_loadingText === void 0) { _loadingText = ""; }
  67217. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67218. var _this = this;
  67219. this._renderingCanvas = _renderingCanvas;
  67220. this._loadingText = _loadingText;
  67221. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67222. // Resize
  67223. this._resizeLoadingUI = function () {
  67224. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67225. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67226. if (!_this._loadingDiv) {
  67227. return;
  67228. }
  67229. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67230. _this._loadingDiv.style.left = canvasRect.left + "px";
  67231. _this._loadingDiv.style.top = canvasRect.top + "px";
  67232. _this._loadingDiv.style.width = canvasRect.width + "px";
  67233. _this._loadingDiv.style.height = canvasRect.height + "px";
  67234. };
  67235. }
  67236. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67237. if (this._loadingDiv) {
  67238. // Do not add a loading screen if there is already one
  67239. return;
  67240. }
  67241. this._loadingDiv = document.createElement("div");
  67242. this._loadingDiv.id = "babylonjsLoadingDiv";
  67243. this._loadingDiv.style.opacity = "0";
  67244. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67245. this._loadingDiv.style.pointerEvents = "none";
  67246. // Loading text
  67247. this._loadingTextDiv = document.createElement("div");
  67248. this._loadingTextDiv.style.position = "absolute";
  67249. this._loadingTextDiv.style.left = "0";
  67250. this._loadingTextDiv.style.top = "50%";
  67251. this._loadingTextDiv.style.marginTop = "80px";
  67252. this._loadingTextDiv.style.width = "100%";
  67253. this._loadingTextDiv.style.height = "20px";
  67254. this._loadingTextDiv.style.fontFamily = "Arial";
  67255. this._loadingTextDiv.style.fontSize = "14px";
  67256. this._loadingTextDiv.style.color = "white";
  67257. this._loadingTextDiv.style.textAlign = "center";
  67258. this._loadingTextDiv.innerHTML = "Loading";
  67259. this._loadingDiv.appendChild(this._loadingTextDiv);
  67260. //set the predefined text
  67261. this._loadingTextDiv.innerHTML = this._loadingText;
  67262. // Generating keyframes
  67263. var style = document.createElement('style');
  67264. style.type = 'text/css';
  67265. 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 }";
  67266. style.innerHTML = keyFrames;
  67267. document.getElementsByTagName('head')[0].appendChild(style);
  67268. // Loading img
  67269. var imgBack = new Image();
  67270. 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";
  67271. imgBack.style.position = "absolute";
  67272. imgBack.style.left = "50%";
  67273. imgBack.style.top = "50%";
  67274. imgBack.style.marginLeft = "-60px";
  67275. imgBack.style.marginTop = "-60px";
  67276. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67277. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67278. imgBack.style.transformOrigin = "50% 50%";
  67279. imgBack.style.webkitTransformOrigin = "50% 50%";
  67280. this._loadingDiv.appendChild(imgBack);
  67281. this._resizeLoadingUI();
  67282. window.addEventListener("resize", this._resizeLoadingUI);
  67283. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67284. document.body.appendChild(this._loadingDiv);
  67285. this._loadingDiv.style.opacity = "1";
  67286. };
  67287. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67288. var _this = this;
  67289. if (!this._loadingDiv) {
  67290. return;
  67291. }
  67292. var onTransitionEnd = function () {
  67293. if (!_this._loadingDiv) {
  67294. return;
  67295. }
  67296. document.body.removeChild(_this._loadingDiv);
  67297. window.removeEventListener("resize", _this._resizeLoadingUI);
  67298. _this._loadingDiv = null;
  67299. };
  67300. this._loadingDiv.style.opacity = "0";
  67301. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67302. };
  67303. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67304. set: function (text) {
  67305. this._loadingText = text;
  67306. if (this._loadingTextDiv) {
  67307. this._loadingTextDiv.innerHTML = this._loadingText;
  67308. }
  67309. },
  67310. enumerable: true,
  67311. configurable: true
  67312. });
  67313. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67314. get: function () {
  67315. return this._loadingDivBackgroundColor;
  67316. },
  67317. set: function (color) {
  67318. this._loadingDivBackgroundColor = color;
  67319. if (!this._loadingDiv) {
  67320. return;
  67321. }
  67322. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67323. },
  67324. enumerable: true,
  67325. configurable: true
  67326. });
  67327. return DefaultLoadingScreen;
  67328. }());
  67329. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67330. })(BABYLON || (BABYLON = {}));
  67331. //# sourceMappingURL=babylon.loadingScreen.js.map
  67332. var BABYLON;
  67333. (function (BABYLON) {
  67334. var SceneLoaderProgressEvent = /** @class */ (function () {
  67335. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67336. this.lengthComputable = lengthComputable;
  67337. this.loaded = loaded;
  67338. this.total = total;
  67339. }
  67340. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67341. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67342. };
  67343. return SceneLoaderProgressEvent;
  67344. }());
  67345. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67346. var SceneLoader = /** @class */ (function () {
  67347. function SceneLoader() {
  67348. }
  67349. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67350. get: function () {
  67351. return 0;
  67352. },
  67353. enumerable: true,
  67354. configurable: true
  67355. });
  67356. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67357. get: function () {
  67358. return 1;
  67359. },
  67360. enumerable: true,
  67361. configurable: true
  67362. });
  67363. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67364. get: function () {
  67365. return 2;
  67366. },
  67367. enumerable: true,
  67368. configurable: true
  67369. });
  67370. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67371. get: function () {
  67372. return 3;
  67373. },
  67374. enumerable: true,
  67375. configurable: true
  67376. });
  67377. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67378. get: function () {
  67379. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67380. },
  67381. set: function (value) {
  67382. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67383. },
  67384. enumerable: true,
  67385. configurable: true
  67386. });
  67387. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67388. get: function () {
  67389. return SceneLoader._ShowLoadingScreen;
  67390. },
  67391. set: function (value) {
  67392. SceneLoader._ShowLoadingScreen = value;
  67393. },
  67394. enumerable: true,
  67395. configurable: true
  67396. });
  67397. Object.defineProperty(SceneLoader, "loggingLevel", {
  67398. get: function () {
  67399. return SceneLoader._loggingLevel;
  67400. },
  67401. set: function (value) {
  67402. SceneLoader._loggingLevel = value;
  67403. },
  67404. enumerable: true,
  67405. configurable: true
  67406. });
  67407. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67408. get: function () {
  67409. return SceneLoader._CleanBoneMatrixWeights;
  67410. },
  67411. set: function (value) {
  67412. SceneLoader._CleanBoneMatrixWeights = value;
  67413. },
  67414. enumerable: true,
  67415. configurable: true
  67416. });
  67417. SceneLoader._getDefaultPlugin = function () {
  67418. return SceneLoader._registeredPlugins[".babylon"];
  67419. };
  67420. SceneLoader._getPluginForExtension = function (extension) {
  67421. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67422. if (registeredPlugin) {
  67423. return registeredPlugin;
  67424. }
  67425. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67426. return SceneLoader._getDefaultPlugin();
  67427. };
  67428. SceneLoader._getPluginForDirectLoad = function (data) {
  67429. for (var extension in SceneLoader._registeredPlugins) {
  67430. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67431. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67432. return SceneLoader._registeredPlugins[extension];
  67433. }
  67434. }
  67435. return SceneLoader._getDefaultPlugin();
  67436. };
  67437. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67438. if (sceneFilename.name) {
  67439. sceneFilename = sceneFilename.name;
  67440. }
  67441. var queryStringPosition = sceneFilename.indexOf("?");
  67442. if (queryStringPosition !== -1) {
  67443. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67444. }
  67445. var dotPosition = sceneFilename.lastIndexOf(".");
  67446. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67447. return SceneLoader._getPluginForExtension(extension);
  67448. };
  67449. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67450. SceneLoader._getDirectLoad = function (sceneFilename) {
  67451. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67452. return sceneFilename.substr(5);
  67453. }
  67454. return null;
  67455. };
  67456. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67457. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67458. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67459. var plugin;
  67460. if (registeredPlugin.plugin.createPlugin) {
  67461. plugin = registeredPlugin.plugin.createPlugin();
  67462. }
  67463. else {
  67464. plugin = registeredPlugin.plugin;
  67465. }
  67466. var useArrayBuffer = registeredPlugin.isBinary;
  67467. var database;
  67468. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67469. var dataCallback = function (data, responseURL) {
  67470. if (scene.isDisposed) {
  67471. onError("Scene has been disposed");
  67472. return;
  67473. }
  67474. scene.database = database;
  67475. onSuccess(plugin, data, responseURL);
  67476. };
  67477. var request = null;
  67478. var pluginDisposed = false;
  67479. var onDisposeObservable = plugin.onDisposeObservable;
  67480. if (onDisposeObservable) {
  67481. onDisposeObservable.add(function () {
  67482. pluginDisposed = true;
  67483. if (request) {
  67484. request.abort();
  67485. request = null;
  67486. }
  67487. onDispose();
  67488. });
  67489. }
  67490. var manifestChecked = function () {
  67491. if (pluginDisposed) {
  67492. return;
  67493. }
  67494. var url = rootUrl + sceneFilename;
  67495. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67496. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67497. } : undefined, database, useArrayBuffer, function (request, exception) {
  67498. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67499. });
  67500. };
  67501. if (directLoad) {
  67502. dataCallback(directLoad);
  67503. return plugin;
  67504. }
  67505. if (rootUrl.indexOf("file:") === -1) {
  67506. var engine = scene.getEngine();
  67507. var canUseOfflineSupport = engine.enableOfflineSupport;
  67508. if (canUseOfflineSupport) {
  67509. // Also check for exceptions
  67510. var exceptionFound = false;
  67511. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67512. var regex = _a[_i];
  67513. if (regex.test(rootUrl + sceneFilename)) {
  67514. exceptionFound = true;
  67515. break;
  67516. }
  67517. }
  67518. canUseOfflineSupport = !exceptionFound;
  67519. }
  67520. if (canUseOfflineSupport) {
  67521. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67522. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67523. }
  67524. else {
  67525. manifestChecked();
  67526. }
  67527. }
  67528. // Loading file from disk via input file or drag'n'drop
  67529. else {
  67530. var fileOrString = sceneFilename;
  67531. if (fileOrString.name) { // File
  67532. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67533. }
  67534. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67535. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67536. }
  67537. else {
  67538. onError("Unable to find file named " + sceneFilename);
  67539. }
  67540. }
  67541. return plugin;
  67542. };
  67543. // Public functions
  67544. SceneLoader.GetPluginForExtension = function (extension) {
  67545. return SceneLoader._getPluginForExtension(extension).plugin;
  67546. };
  67547. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67548. return !!SceneLoader._registeredPlugins[extension];
  67549. };
  67550. SceneLoader.RegisterPlugin = function (plugin) {
  67551. if (typeof plugin.extensions === "string") {
  67552. var extension = plugin.extensions;
  67553. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67554. plugin: plugin,
  67555. isBinary: false
  67556. };
  67557. }
  67558. else {
  67559. var extensions = plugin.extensions;
  67560. Object.keys(extensions).forEach(function (extension) {
  67561. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67562. plugin: plugin,
  67563. isBinary: extensions[extension].isBinary
  67564. };
  67565. });
  67566. }
  67567. };
  67568. /**
  67569. * Import meshes into a scene
  67570. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67571. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67572. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67573. * @param scene the instance of BABYLON.Scene to append to
  67574. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67575. * @param onProgress a callback with a progress event for each file being loaded
  67576. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67577. * @param pluginExtension the extension used to determine the plugin
  67578. * @returns The loaded plugin
  67579. */
  67580. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67581. if (sceneFilename === void 0) { sceneFilename = ""; }
  67582. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67583. if (onSuccess === void 0) { onSuccess = null; }
  67584. if (onProgress === void 0) { onProgress = null; }
  67585. if (onError === void 0) { onError = null; }
  67586. if (pluginExtension === void 0) { pluginExtension = null; }
  67587. if (!scene) {
  67588. BABYLON.Tools.Error("No scene available to import mesh to");
  67589. return null;
  67590. }
  67591. if (!sceneFilename) {
  67592. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67593. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67594. }
  67595. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67596. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67597. return null;
  67598. }
  67599. var loadingToken = {};
  67600. scene._addPendingData(loadingToken);
  67601. var disposeHandler = function () {
  67602. scene._removePendingData(loadingToken);
  67603. };
  67604. var errorHandler = function (message, exception) {
  67605. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67606. if (onError) {
  67607. onError(scene, errorMessage, exception);
  67608. }
  67609. else {
  67610. BABYLON.Tools.Error(errorMessage);
  67611. // should the exception be thrown?
  67612. }
  67613. disposeHandler();
  67614. };
  67615. var progressHandler = onProgress ? function (event) {
  67616. try {
  67617. onProgress(event);
  67618. }
  67619. catch (e) {
  67620. errorHandler("Error in onProgress callback", e);
  67621. }
  67622. } : undefined;
  67623. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67624. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67625. if (onSuccess) {
  67626. try {
  67627. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67628. }
  67629. catch (e) {
  67630. errorHandler("Error in onSuccess callback", e);
  67631. }
  67632. }
  67633. scene._removePendingData(loadingToken);
  67634. };
  67635. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67636. if (plugin.rewriteRootURL) {
  67637. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67638. }
  67639. if (sceneFilename === "") {
  67640. if (sceneFilename === "") {
  67641. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67642. }
  67643. }
  67644. if (plugin.importMesh) {
  67645. var syncedPlugin = plugin;
  67646. var meshes = new Array();
  67647. var particleSystems = new Array();
  67648. var skeletons = new Array();
  67649. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67650. return;
  67651. }
  67652. scene.loadingPluginName = plugin.name;
  67653. successHandler(meshes, particleSystems, skeletons, []);
  67654. }
  67655. else {
  67656. var asyncedPlugin = plugin;
  67657. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67658. scene.loadingPluginName = plugin.name;
  67659. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67660. }).catch(function (error) {
  67661. errorHandler(error.message, error);
  67662. });
  67663. }
  67664. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67665. };
  67666. /**
  67667. * Import meshes into a scene
  67668. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67669. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67670. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67671. * @param scene the instance of BABYLON.Scene to append to
  67672. * @param onProgress a callback with a progress event for each file being loaded
  67673. * @param pluginExtension the extension used to determine the plugin
  67674. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67675. */
  67676. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67677. if (sceneFilename === void 0) { sceneFilename = ""; }
  67678. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67679. if (onProgress === void 0) { onProgress = null; }
  67680. if (pluginExtension === void 0) { pluginExtension = null; }
  67681. return new Promise(function (resolve, reject) {
  67682. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67683. resolve({
  67684. meshes: meshes,
  67685. particleSystems: particleSystems,
  67686. skeletons: skeletons,
  67687. animationGroups: animationGroups
  67688. });
  67689. }, onProgress, function (scene, message, exception) {
  67690. reject(exception || new Error(message));
  67691. }, pluginExtension);
  67692. });
  67693. };
  67694. /**
  67695. * Load a scene
  67696. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67697. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67698. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67699. * @param onSuccess a callback with the scene when import succeeds
  67700. * @param onProgress a callback with a progress event for each file being loaded
  67701. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67702. * @param pluginExtension the extension used to determine the plugin
  67703. * @returns The loaded plugin
  67704. */
  67705. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67706. if (onSuccess === void 0) { onSuccess = null; }
  67707. if (onProgress === void 0) { onProgress = null; }
  67708. if (onError === void 0) { onError = null; }
  67709. if (pluginExtension === void 0) { pluginExtension = null; }
  67710. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67711. };
  67712. /**
  67713. * Load a scene
  67714. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67715. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67716. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67717. * @param onProgress a callback with a progress event for each file being loaded
  67718. * @param pluginExtension the extension used to determine the plugin
  67719. * @returns The loaded scene
  67720. */
  67721. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67722. if (onProgress === void 0) { onProgress = null; }
  67723. if (pluginExtension === void 0) { pluginExtension = null; }
  67724. return new Promise(function (resolve, reject) {
  67725. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67726. resolve(scene);
  67727. }, onProgress, function (scene, message, exception) {
  67728. reject(exception || new Error(message));
  67729. }, pluginExtension);
  67730. });
  67731. };
  67732. /**
  67733. * Append a scene
  67734. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67735. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67736. * @param scene is the instance of BABYLON.Scene to append to
  67737. * @param onSuccess a callback with the scene when import succeeds
  67738. * @param onProgress a callback with a progress event for each file being loaded
  67739. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67740. * @param pluginExtension the extension used to determine the plugin
  67741. * @returns The loaded plugin
  67742. */
  67743. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67744. if (sceneFilename === void 0) { sceneFilename = ""; }
  67745. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67746. if (onSuccess === void 0) { onSuccess = null; }
  67747. if (onProgress === void 0) { onProgress = null; }
  67748. if (onError === void 0) { onError = null; }
  67749. if (pluginExtension === void 0) { pluginExtension = null; }
  67750. if (!scene) {
  67751. BABYLON.Tools.Error("No scene available to append to");
  67752. return null;
  67753. }
  67754. if (!sceneFilename) {
  67755. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67756. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67757. }
  67758. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67759. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67760. return null;
  67761. }
  67762. if (SceneLoader.ShowLoadingScreen) {
  67763. scene.getEngine().displayLoadingUI();
  67764. }
  67765. var loadingToken = {};
  67766. scene._addPendingData(loadingToken);
  67767. var disposeHandler = function () {
  67768. scene._removePendingData(loadingToken);
  67769. scene.getEngine().hideLoadingUI();
  67770. };
  67771. var errorHandler = function (message, exception) {
  67772. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67773. if (onError) {
  67774. onError(scene, errorMessage, exception);
  67775. }
  67776. else {
  67777. BABYLON.Tools.Error(errorMessage);
  67778. // should the exception be thrown?
  67779. }
  67780. disposeHandler();
  67781. };
  67782. var progressHandler = onProgress ? function (event) {
  67783. try {
  67784. onProgress(event);
  67785. }
  67786. catch (e) {
  67787. errorHandler("Error in onProgress callback", e);
  67788. }
  67789. } : undefined;
  67790. var successHandler = function () {
  67791. if (onSuccess) {
  67792. try {
  67793. onSuccess(scene);
  67794. }
  67795. catch (e) {
  67796. errorHandler("Error in onSuccess callback", e);
  67797. }
  67798. }
  67799. scene._removePendingData(loadingToken);
  67800. };
  67801. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67802. if (sceneFilename === "") {
  67803. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67804. }
  67805. if (plugin.load) {
  67806. var syncedPlugin = plugin;
  67807. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67808. return;
  67809. }
  67810. scene.loadingPluginName = plugin.name;
  67811. successHandler();
  67812. }
  67813. else {
  67814. var asyncedPlugin = plugin;
  67815. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67816. scene.loadingPluginName = plugin.name;
  67817. successHandler();
  67818. }).catch(function (error) {
  67819. errorHandler(error.message, error);
  67820. });
  67821. }
  67822. if (SceneLoader.ShowLoadingScreen) {
  67823. scene.executeWhenReady(function () {
  67824. scene.getEngine().hideLoadingUI();
  67825. });
  67826. }
  67827. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67828. };
  67829. /**
  67830. * Append a scene
  67831. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67832. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67833. * @param scene is the instance of BABYLON.Scene to append to
  67834. * @param onProgress a callback with a progress event for each file being loaded
  67835. * @param pluginExtension the extension used to determine the plugin
  67836. * @returns The given scene
  67837. */
  67838. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67839. if (sceneFilename === void 0) { sceneFilename = ""; }
  67840. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67841. if (onProgress === void 0) { onProgress = null; }
  67842. if (pluginExtension === void 0) { pluginExtension = null; }
  67843. return new Promise(function (resolve, reject) {
  67844. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67845. resolve(scene);
  67846. }, onProgress, function (scene, message, exception) {
  67847. reject(exception || new Error(message));
  67848. }, pluginExtension);
  67849. });
  67850. };
  67851. /**
  67852. * Load a scene into an asset container
  67853. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67854. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67855. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67856. * @param onSuccess a callback with the scene when import succeeds
  67857. * @param onProgress a callback with a progress event for each file being loaded
  67858. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67859. * @param pluginExtension the extension used to determine the plugin
  67860. * @returns The loaded plugin
  67861. */
  67862. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67863. if (sceneFilename === void 0) { sceneFilename = ""; }
  67864. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67865. if (onSuccess === void 0) { onSuccess = null; }
  67866. if (onProgress === void 0) { onProgress = null; }
  67867. if (onError === void 0) { onError = null; }
  67868. if (pluginExtension === void 0) { pluginExtension = null; }
  67869. if (!scene) {
  67870. BABYLON.Tools.Error("No scene available to load asset container to");
  67871. return null;
  67872. }
  67873. if (!sceneFilename) {
  67874. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67875. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67876. }
  67877. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67878. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67879. return null;
  67880. }
  67881. var loadingToken = {};
  67882. scene._addPendingData(loadingToken);
  67883. var disposeHandler = function () {
  67884. scene._removePendingData(loadingToken);
  67885. };
  67886. var errorHandler = function (message, exception) {
  67887. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67888. if (onError) {
  67889. onError(scene, errorMessage, exception);
  67890. }
  67891. else {
  67892. BABYLON.Tools.Error(errorMessage);
  67893. // should the exception be thrown?
  67894. }
  67895. disposeHandler();
  67896. };
  67897. var progressHandler = onProgress ? function (event) {
  67898. try {
  67899. onProgress(event);
  67900. }
  67901. catch (e) {
  67902. errorHandler("Error in onProgress callback", e);
  67903. }
  67904. } : undefined;
  67905. var successHandler = function (assets) {
  67906. if (onSuccess) {
  67907. try {
  67908. onSuccess(assets);
  67909. }
  67910. catch (e) {
  67911. errorHandler("Error in onSuccess callback", e);
  67912. }
  67913. }
  67914. scene._removePendingData(loadingToken);
  67915. };
  67916. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67917. if (plugin.loadAssetContainer) {
  67918. var syncedPlugin = plugin;
  67919. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67920. if (!assetContainer) {
  67921. return;
  67922. }
  67923. scene.loadingPluginName = plugin.name;
  67924. successHandler(assetContainer);
  67925. }
  67926. else if (plugin.loadAssetContainerAsync) {
  67927. var asyncedPlugin = plugin;
  67928. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67929. scene.loadingPluginName = plugin.name;
  67930. successHandler(assetContainer);
  67931. }).catch(function (error) {
  67932. errorHandler(error.message, error);
  67933. });
  67934. }
  67935. else {
  67936. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67937. }
  67938. if (SceneLoader.ShowLoadingScreen) {
  67939. scene.executeWhenReady(function () {
  67940. scene.getEngine().hideLoadingUI();
  67941. });
  67942. }
  67943. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67944. };
  67945. /**
  67946. * Load a scene into an asset container
  67947. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67948. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67949. * @param scene is the instance of BABYLON.Scene to append to
  67950. * @param onProgress a callback with a progress event for each file being loaded
  67951. * @param pluginExtension the extension used to determine the plugin
  67952. * @returns The loaded asset container
  67953. */
  67954. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67955. if (sceneFilename === void 0) { sceneFilename = ""; }
  67956. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67957. if (onProgress === void 0) { onProgress = null; }
  67958. if (pluginExtension === void 0) { pluginExtension = null; }
  67959. return new Promise(function (resolve, reject) {
  67960. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67961. resolve(assetContainer);
  67962. }, onProgress, function (scene, message, exception) {
  67963. reject(exception || new Error(message));
  67964. }, pluginExtension);
  67965. });
  67966. };
  67967. // Flags
  67968. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67969. SceneLoader._ShowLoadingScreen = true;
  67970. SceneLoader._CleanBoneMatrixWeights = false;
  67971. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67972. // Members
  67973. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67974. SceneLoader._registeredPlugins = {};
  67975. return SceneLoader;
  67976. }());
  67977. BABYLON.SceneLoader = SceneLoader;
  67978. ;
  67979. })(BABYLON || (BABYLON = {}));
  67980. //# sourceMappingURL=babylon.sceneLoader.js.map
  67981. var BABYLON;
  67982. (function (BABYLON) {
  67983. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67984. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67985. var parsedMaterial = parsedData.materials[index];
  67986. if (parsedMaterial.id === id) {
  67987. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67988. }
  67989. }
  67990. return null;
  67991. };
  67992. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67993. for (var i in names) {
  67994. if (mesh.name === names[i]) {
  67995. hierarchyIds.push(mesh.id);
  67996. return true;
  67997. }
  67998. }
  67999. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68000. hierarchyIds.push(mesh.id);
  68001. return true;
  68002. }
  68003. return false;
  68004. };
  68005. var logOperation = function (operation, producer) {
  68006. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68007. };
  68008. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68009. if (addToScene === void 0) { addToScene = false; }
  68010. var container = new BABYLON.AssetContainer(scene);
  68011. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68012. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68013. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68014. // and avoid problems with multiple concurrent .babylon loads.
  68015. var log = "importScene has failed JSON parse";
  68016. try {
  68017. var parsedData = JSON.parse(data);
  68018. log = "";
  68019. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68020. var index;
  68021. var cache;
  68022. // Lights
  68023. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68024. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68025. var parsedLight = parsedData.lights[index];
  68026. var light = BABYLON.Light.Parse(parsedLight, scene);
  68027. if (light) {
  68028. container.lights.push(light);
  68029. log += (index === 0 ? "\n\tLights:" : "");
  68030. log += "\n\t\t" + light.toString(fullDetails);
  68031. }
  68032. }
  68033. }
  68034. // Animations
  68035. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68036. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68037. var parsedAnimation = parsedData.animations[index];
  68038. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68039. scene.animations.push(animation);
  68040. container.animations.push(animation);
  68041. log += (index === 0 ? "\n\tAnimations:" : "");
  68042. log += "\n\t\t" + animation.toString(fullDetails);
  68043. }
  68044. }
  68045. // Materials
  68046. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68047. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68048. var parsedMaterial = parsedData.materials[index];
  68049. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68050. container.materials.push(mat);
  68051. log += (index === 0 ? "\n\tMaterials:" : "");
  68052. log += "\n\t\t" + mat.toString(fullDetails);
  68053. }
  68054. }
  68055. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68056. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68057. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68058. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68059. container.multiMaterials.push(mmat);
  68060. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68061. log += "\n\t\t" + mmat.toString(fullDetails);
  68062. }
  68063. }
  68064. // Morph targets
  68065. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68066. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68067. var managerData = _a[_i];
  68068. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68069. }
  68070. }
  68071. // Skeletons
  68072. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68073. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68074. var parsedSkeleton = parsedData.skeletons[index];
  68075. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68076. container.skeletons.push(skeleton);
  68077. log += (index === 0 ? "\n\tSkeletons:" : "");
  68078. log += "\n\t\t" + skeleton.toString(fullDetails);
  68079. }
  68080. }
  68081. // Geometries
  68082. var geometries = parsedData.geometries;
  68083. if (geometries !== undefined && geometries !== null) {
  68084. var addedGeometry = new Array();
  68085. // Boxes
  68086. var boxes = geometries.boxes;
  68087. if (boxes !== undefined && boxes !== null) {
  68088. for (index = 0, cache = boxes.length; index < cache; index++) {
  68089. var parsedBox = boxes[index];
  68090. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68091. }
  68092. }
  68093. // Spheres
  68094. var spheres = geometries.spheres;
  68095. if (spheres !== undefined && spheres !== null) {
  68096. for (index = 0, cache = spheres.length; index < cache; index++) {
  68097. var parsedSphere = spheres[index];
  68098. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68099. }
  68100. }
  68101. // Cylinders
  68102. var cylinders = geometries.cylinders;
  68103. if (cylinders !== undefined && cylinders !== null) {
  68104. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68105. var parsedCylinder = cylinders[index];
  68106. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68107. }
  68108. }
  68109. // Toruses
  68110. var toruses = geometries.toruses;
  68111. if (toruses !== undefined && toruses !== null) {
  68112. for (index = 0, cache = toruses.length; index < cache; index++) {
  68113. var parsedTorus = toruses[index];
  68114. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68115. }
  68116. }
  68117. // Grounds
  68118. var grounds = geometries.grounds;
  68119. if (grounds !== undefined && grounds !== null) {
  68120. for (index = 0, cache = grounds.length; index < cache; index++) {
  68121. var parsedGround = grounds[index];
  68122. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68123. }
  68124. }
  68125. // Planes
  68126. var planes = geometries.planes;
  68127. if (planes !== undefined && planes !== null) {
  68128. for (index = 0, cache = planes.length; index < cache; index++) {
  68129. var parsedPlane = planes[index];
  68130. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68131. }
  68132. }
  68133. // TorusKnots
  68134. var torusKnots = geometries.torusKnots;
  68135. if (torusKnots !== undefined && torusKnots !== null) {
  68136. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68137. var parsedTorusKnot = torusKnots[index];
  68138. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68139. }
  68140. }
  68141. // VertexData
  68142. var vertexData = geometries.vertexData;
  68143. if (vertexData !== undefined && vertexData !== null) {
  68144. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68145. var parsedVertexData = vertexData[index];
  68146. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68147. }
  68148. }
  68149. addedGeometry.forEach(function (g) {
  68150. if (g) {
  68151. container.geometries.push(g);
  68152. }
  68153. });
  68154. }
  68155. // Transform nodes
  68156. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68157. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68158. var parsedTransformNode = parsedData.transformNodes[index];
  68159. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68160. container.transformNodes.push(node);
  68161. }
  68162. }
  68163. // Meshes
  68164. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68165. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68166. var parsedMesh = parsedData.meshes[index];
  68167. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68168. container.meshes.push(mesh);
  68169. log += (index === 0 ? "\n\tMeshes:" : "");
  68170. log += "\n\t\t" + mesh.toString(fullDetails);
  68171. }
  68172. }
  68173. // Cameras
  68174. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68175. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68176. var parsedCamera = parsedData.cameras[index];
  68177. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68178. container.cameras.push(camera);
  68179. log += (index === 0 ? "\n\tCameras:" : "");
  68180. log += "\n\t\t" + camera.toString(fullDetails);
  68181. }
  68182. }
  68183. // Browsing all the graph to connect the dots
  68184. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68185. var camera = scene.cameras[index];
  68186. if (camera._waitingParentId) {
  68187. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68188. camera._waitingParentId = null;
  68189. }
  68190. }
  68191. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68192. var light_1 = scene.lights[index];
  68193. if (light_1 && light_1._waitingParentId) {
  68194. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68195. light_1._waitingParentId = null;
  68196. }
  68197. }
  68198. // Sounds
  68199. // TODO: add sound
  68200. var loadedSounds = [];
  68201. var loadedSound;
  68202. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68203. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68204. var parsedSound = parsedData.sounds[index];
  68205. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68206. if (!parsedSound.url)
  68207. parsedSound.url = parsedSound.name;
  68208. if (!loadedSounds[parsedSound.url]) {
  68209. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68210. loadedSounds[parsedSound.url] = loadedSound;
  68211. container.sounds.push(loadedSound);
  68212. }
  68213. else {
  68214. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68215. }
  68216. }
  68217. else {
  68218. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68219. }
  68220. }
  68221. }
  68222. loadedSounds = [];
  68223. // Connect parents & children and parse actions
  68224. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68225. var transformNode = scene.transformNodes[index];
  68226. if (transformNode._waitingParentId) {
  68227. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68228. transformNode._waitingParentId = null;
  68229. }
  68230. }
  68231. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68232. var mesh = scene.meshes[index];
  68233. if (mesh._waitingParentId) {
  68234. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68235. mesh._waitingParentId = null;
  68236. }
  68237. if (mesh._waitingActions) {
  68238. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68239. mesh._waitingActions = null;
  68240. }
  68241. }
  68242. // freeze world matrix application
  68243. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68244. var currentMesh = scene.meshes[index];
  68245. if (currentMesh._waitingFreezeWorldMatrix) {
  68246. currentMesh.freezeWorldMatrix();
  68247. currentMesh._waitingFreezeWorldMatrix = null;
  68248. }
  68249. else {
  68250. currentMesh.computeWorldMatrix(true);
  68251. }
  68252. }
  68253. // Particles Systems
  68254. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68255. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68256. var parsedParticleSystem = parsedData.particleSystems[index];
  68257. if (parsedParticleSystem.activeParticleCount) {
  68258. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68259. container.particleSystems.push(ps);
  68260. }
  68261. else {
  68262. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68263. container.particleSystems.push(ps);
  68264. }
  68265. }
  68266. }
  68267. // Lens flares
  68268. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68269. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68270. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68271. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68272. container.lensFlareSystems.push(lf);
  68273. }
  68274. }
  68275. // Shadows
  68276. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68277. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68278. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68279. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68280. container.shadowGenerators.push(sg);
  68281. }
  68282. }
  68283. // Lights exclusions / inclusions
  68284. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68285. var light_2 = scene.lights[index];
  68286. // Excluded check
  68287. if (light_2._excludedMeshesIds.length > 0) {
  68288. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68289. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68290. if (excludedMesh) {
  68291. light_2.excludedMeshes.push(excludedMesh);
  68292. }
  68293. }
  68294. light_2._excludedMeshesIds = [];
  68295. }
  68296. // Included check
  68297. if (light_2._includedOnlyMeshesIds.length > 0) {
  68298. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68299. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68300. if (includedOnlyMesh) {
  68301. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68302. }
  68303. }
  68304. light_2._includedOnlyMeshesIds = [];
  68305. }
  68306. }
  68307. // Effect layers
  68308. if (parsedData.effectLayers) {
  68309. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68310. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68311. container.effectLayers.push(effectLayer);
  68312. }
  68313. }
  68314. // Actions (scene)
  68315. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68316. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68317. }
  68318. if (!addToScene) {
  68319. container.removeAllFromScene();
  68320. }
  68321. }
  68322. catch (err) {
  68323. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68324. if (onError) {
  68325. onError(msg, err);
  68326. }
  68327. else {
  68328. BABYLON.Tools.Log(msg);
  68329. throw err;
  68330. }
  68331. }
  68332. finally {
  68333. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68334. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68335. }
  68336. }
  68337. return container;
  68338. };
  68339. BABYLON.SceneLoader.RegisterPlugin({
  68340. name: "babylon.js",
  68341. extensions: ".babylon",
  68342. canDirectLoad: function (data) {
  68343. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68344. return true;
  68345. }
  68346. return false;
  68347. },
  68348. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68349. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68350. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68351. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68352. // and avoid problems with multiple concurrent .babylon loads.
  68353. var log = "importMesh has failed JSON parse";
  68354. try {
  68355. var parsedData = JSON.parse(data);
  68356. log = "";
  68357. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68358. if (!meshesNames) {
  68359. meshesNames = null;
  68360. }
  68361. else if (!Array.isArray(meshesNames)) {
  68362. meshesNames = [meshesNames];
  68363. }
  68364. var hierarchyIds = new Array();
  68365. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68366. var loadedSkeletonsIds = [];
  68367. var loadedMaterialsIds = [];
  68368. var index;
  68369. var cache;
  68370. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68371. var parsedMesh = parsedData.meshes[index];
  68372. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68373. if (meshesNames !== null) {
  68374. // Remove found mesh name from list.
  68375. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68376. }
  68377. //Geometry?
  68378. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68379. //does the file contain geometries?
  68380. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68381. //find the correct geometry and add it to the scene
  68382. var found = false;
  68383. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68384. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68385. return;
  68386. }
  68387. else {
  68388. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68389. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68390. switch (geometryType) {
  68391. case "boxes":
  68392. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68393. break;
  68394. case "spheres":
  68395. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68396. break;
  68397. case "cylinders":
  68398. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68399. break;
  68400. case "toruses":
  68401. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68402. break;
  68403. case "grounds":
  68404. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68405. break;
  68406. case "planes":
  68407. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68408. break;
  68409. case "torusKnots":
  68410. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68411. break;
  68412. case "vertexData":
  68413. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68414. break;
  68415. }
  68416. found = true;
  68417. }
  68418. });
  68419. }
  68420. });
  68421. if (found === false) {
  68422. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68423. }
  68424. }
  68425. }
  68426. // Material ?
  68427. if (parsedMesh.materialId) {
  68428. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68429. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68430. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68431. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68432. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68433. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68434. var subMatId = parsedMultiMaterial.materials[matIndex];
  68435. loadedMaterialsIds.push(subMatId);
  68436. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68437. if (mat) {
  68438. log += "\n\tMaterial " + mat.toString(fullDetails);
  68439. }
  68440. }
  68441. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68442. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68443. if (mmat) {
  68444. materialFound = true;
  68445. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68446. }
  68447. break;
  68448. }
  68449. }
  68450. }
  68451. if (materialFound === false) {
  68452. loadedMaterialsIds.push(parsedMesh.materialId);
  68453. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68454. if (!mat) {
  68455. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68456. }
  68457. else {
  68458. log += "\n\tMaterial " + mat.toString(fullDetails);
  68459. }
  68460. }
  68461. }
  68462. // Skeleton ?
  68463. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68464. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68465. if (skeletonAlreadyLoaded === false) {
  68466. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68467. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68468. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68469. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68470. skeletons.push(skeleton);
  68471. loadedSkeletonsIds.push(parsedSkeleton.id);
  68472. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68473. }
  68474. }
  68475. }
  68476. }
  68477. // Morph targets ?
  68478. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68479. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68480. var managerData = _a[_i];
  68481. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68482. }
  68483. }
  68484. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68485. meshes.push(mesh);
  68486. log += "\n\tMesh " + mesh.toString(fullDetails);
  68487. }
  68488. }
  68489. // Connecting parents
  68490. var currentMesh;
  68491. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68492. currentMesh = scene.meshes[index];
  68493. if (currentMesh._waitingParentId) {
  68494. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68495. currentMesh._waitingParentId = null;
  68496. }
  68497. }
  68498. // freeze and compute world matrix application
  68499. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68500. currentMesh = scene.meshes[index];
  68501. if (currentMesh._waitingFreezeWorldMatrix) {
  68502. currentMesh.freezeWorldMatrix();
  68503. currentMesh._waitingFreezeWorldMatrix = null;
  68504. }
  68505. else {
  68506. currentMesh.computeWorldMatrix(true);
  68507. }
  68508. }
  68509. }
  68510. // Particles
  68511. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68512. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68513. var parsedParticleSystem = parsedData.particleSystems[index];
  68514. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68515. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68516. }
  68517. }
  68518. }
  68519. return true;
  68520. }
  68521. catch (err) {
  68522. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68523. if (onError) {
  68524. onError(msg, err);
  68525. }
  68526. else {
  68527. BABYLON.Tools.Log(msg);
  68528. throw err;
  68529. }
  68530. }
  68531. finally {
  68532. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68533. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68534. }
  68535. }
  68536. return false;
  68537. },
  68538. load: function (scene, data, rootUrl, onError) {
  68539. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68540. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68541. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68542. // and avoid problems with multiple concurrent .babylon loads.
  68543. var log = "importScene has failed JSON parse";
  68544. try {
  68545. var parsedData = JSON.parse(data);
  68546. log = "";
  68547. // Scene
  68548. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68549. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68550. }
  68551. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68552. scene.autoClear = parsedData.autoClear;
  68553. }
  68554. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68555. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68556. }
  68557. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68558. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68559. }
  68560. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68561. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68562. }
  68563. // Fog
  68564. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68565. scene.fogMode = parsedData.fogMode;
  68566. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68567. scene.fogStart = parsedData.fogStart;
  68568. scene.fogEnd = parsedData.fogEnd;
  68569. scene.fogDensity = parsedData.fogDensity;
  68570. log += "\tFog mode for scene: ";
  68571. switch (scene.fogMode) {
  68572. // getters not compiling, so using hardcoded
  68573. case 1:
  68574. log += "exp\n";
  68575. break;
  68576. case 2:
  68577. log += "exp2\n";
  68578. break;
  68579. case 3:
  68580. log += "linear\n";
  68581. break;
  68582. }
  68583. }
  68584. //Physics
  68585. if (parsedData.physicsEnabled) {
  68586. var physicsPlugin;
  68587. if (parsedData.physicsEngine === "cannon") {
  68588. physicsPlugin = new BABYLON.CannonJSPlugin();
  68589. }
  68590. else if (parsedData.physicsEngine === "oimo") {
  68591. physicsPlugin = new BABYLON.OimoJSPlugin();
  68592. }
  68593. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68594. //else - default engine, which is currently oimo
  68595. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68596. scene.enablePhysics(physicsGravity, physicsPlugin);
  68597. }
  68598. // Metadata
  68599. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68600. scene.metadata = parsedData.metadata;
  68601. }
  68602. //collisions, if defined. otherwise, default is true
  68603. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68604. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68605. }
  68606. scene.workerCollisions = !!parsedData.workerCollisions;
  68607. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68608. if (!container) {
  68609. return false;
  68610. }
  68611. if (parsedData.autoAnimate) {
  68612. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68613. }
  68614. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68615. scene.setActiveCameraByID(parsedData.activeCameraID);
  68616. }
  68617. // Environment texture
  68618. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68619. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68620. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68621. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68622. if (parsedData.environmentTextureRotationY) {
  68623. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68624. }
  68625. scene.environmentTexture = hdrTexture;
  68626. }
  68627. else {
  68628. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68629. if (parsedData.environmentTextureRotationY) {
  68630. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68631. }
  68632. scene.environmentTexture = cubeTexture;
  68633. }
  68634. if (parsedData.createDefaultSkybox === true) {
  68635. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68636. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68637. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68638. }
  68639. }
  68640. // Finish
  68641. return true;
  68642. }
  68643. catch (err) {
  68644. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68645. if (onError) {
  68646. onError(msg, err);
  68647. }
  68648. else {
  68649. BABYLON.Tools.Log(msg);
  68650. throw err;
  68651. }
  68652. }
  68653. finally {
  68654. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68655. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68656. }
  68657. }
  68658. return false;
  68659. },
  68660. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68661. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68662. return container;
  68663. }
  68664. });
  68665. })(BABYLON || (BABYLON = {}));
  68666. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68667. var BABYLON;
  68668. (function (BABYLON) {
  68669. var FilesInput = /** @class */ (function () {
  68670. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68671. this.onProcessFileCallback = function () { return true; };
  68672. this._engine = engine;
  68673. this._currentScene = scene;
  68674. this._sceneLoadedCallback = sceneLoadedCallback;
  68675. this._progressCallback = progressCallback;
  68676. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68677. this._textureLoadingCallback = textureLoadingCallback;
  68678. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68679. this._onReloadCallback = onReloadCallback;
  68680. this._errorCallback = errorCallback;
  68681. }
  68682. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68683. var _this = this;
  68684. if (elementToMonitor) {
  68685. this._elementToMonitor = elementToMonitor;
  68686. this._dragEnterHandler = function (e) { _this.drag(e); };
  68687. this._dragOverHandler = function (e) { _this.drag(e); };
  68688. this._dropHandler = function (e) { _this.drop(e); };
  68689. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68690. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68691. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68692. }
  68693. };
  68694. FilesInput.prototype.dispose = function () {
  68695. if (!this._elementToMonitor) {
  68696. return;
  68697. }
  68698. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68699. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68700. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68701. };
  68702. FilesInput.prototype.renderFunction = function () {
  68703. if (this._additionalRenderLoopLogicCallback) {
  68704. this._additionalRenderLoopLogicCallback();
  68705. }
  68706. if (this._currentScene) {
  68707. if (this._textureLoadingCallback) {
  68708. var remaining = this._currentScene.getWaitingItemsCount();
  68709. if (remaining > 0) {
  68710. this._textureLoadingCallback(remaining);
  68711. }
  68712. }
  68713. this._currentScene.render();
  68714. }
  68715. };
  68716. FilesInput.prototype.drag = function (e) {
  68717. e.stopPropagation();
  68718. e.preventDefault();
  68719. };
  68720. FilesInput.prototype.drop = function (eventDrop) {
  68721. eventDrop.stopPropagation();
  68722. eventDrop.preventDefault();
  68723. this.loadFiles(eventDrop);
  68724. };
  68725. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68726. var _this = this;
  68727. var reader = folder.createReader();
  68728. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68729. reader.readEntries(function (entries) {
  68730. remaining.count += entries.length;
  68731. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68732. var entry = entries_1[_i];
  68733. if (entry.isFile) {
  68734. entry.file(function (file) {
  68735. file.correctName = relativePath + file.name;
  68736. files.push(file);
  68737. if (--remaining.count === 0) {
  68738. callback();
  68739. }
  68740. });
  68741. }
  68742. else if (entry.isDirectory) {
  68743. _this._traverseFolder(entry, files, remaining, callback);
  68744. }
  68745. }
  68746. if (--remaining.count) {
  68747. callback();
  68748. }
  68749. });
  68750. };
  68751. FilesInput.prototype._processFiles = function (files) {
  68752. for (var i = 0; i < files.length; i++) {
  68753. var name = files[i].correctName.toLowerCase();
  68754. var extension = name.split('.').pop();
  68755. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68756. continue;
  68757. }
  68758. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68759. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68760. this._sceneFileToLoad = files[i];
  68761. }
  68762. else {
  68763. FilesInput.FilesToLoad[name] = files[i];
  68764. }
  68765. }
  68766. };
  68767. FilesInput.prototype.loadFiles = function (event) {
  68768. var _this = this;
  68769. if (this._startingProcessingFilesCallback)
  68770. this._startingProcessingFilesCallback();
  68771. // Handling data transfer via drag'n'drop
  68772. if (event && event.dataTransfer && event.dataTransfer.files) {
  68773. this._filesToLoad = event.dataTransfer.files;
  68774. }
  68775. // Handling files from input files
  68776. if (event && event.target && event.target.files) {
  68777. this._filesToLoad = event.target.files;
  68778. }
  68779. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68780. var files_1 = new Array();
  68781. var folders = [];
  68782. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68783. for (var i = 0; i < this._filesToLoad.length; i++) {
  68784. var fileToLoad = this._filesToLoad[i];
  68785. var name_1 = fileToLoad.name.toLowerCase();
  68786. var entry = void 0;
  68787. fileToLoad.correctName = name_1;
  68788. if (items) {
  68789. var item = items[i];
  68790. if (item.getAsEntry) {
  68791. entry = item.getAsEntry();
  68792. }
  68793. else if (item.webkitGetAsEntry) {
  68794. entry = item.webkitGetAsEntry();
  68795. }
  68796. }
  68797. if (!entry) {
  68798. files_1.push(fileToLoad);
  68799. }
  68800. else {
  68801. if (entry.isDirectory) {
  68802. folders.push(entry);
  68803. }
  68804. else {
  68805. files_1.push(fileToLoad);
  68806. }
  68807. }
  68808. }
  68809. if (folders.length === 0) {
  68810. this._processFiles(files_1);
  68811. this._processReload();
  68812. }
  68813. else {
  68814. var remaining = { count: folders.length };
  68815. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68816. var folder = folders_1[_i];
  68817. this._traverseFolder(folder, files_1, remaining, function () {
  68818. _this._processFiles(files_1);
  68819. if (remaining.count === 0) {
  68820. _this._processReload();
  68821. }
  68822. });
  68823. }
  68824. }
  68825. }
  68826. };
  68827. FilesInput.prototype._processReload = function () {
  68828. if (this._onReloadCallback) {
  68829. this._onReloadCallback(this._sceneFileToLoad);
  68830. }
  68831. else {
  68832. this.reload();
  68833. }
  68834. };
  68835. FilesInput.prototype.reload = function () {
  68836. var _this = this;
  68837. // If a scene file has been provided
  68838. if (this._sceneFileToLoad) {
  68839. if (this._currentScene) {
  68840. if (BABYLON.Tools.errorsCount > 0) {
  68841. BABYLON.Tools.ClearLogCache();
  68842. }
  68843. this._engine.stopRenderLoop();
  68844. }
  68845. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68846. if (_this._progressCallback) {
  68847. _this._progressCallback(progress);
  68848. }
  68849. }).then(function (scene) {
  68850. if (_this._currentScene) {
  68851. _this._currentScene.dispose();
  68852. }
  68853. _this._currentScene = scene;
  68854. if (_this._sceneLoadedCallback) {
  68855. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68856. }
  68857. // Wait for textures and shaders to be ready
  68858. _this._currentScene.executeWhenReady(function () {
  68859. _this._engine.runRenderLoop(function () {
  68860. _this.renderFunction();
  68861. });
  68862. });
  68863. }).catch(function (error) {
  68864. if (_this._errorCallback) {
  68865. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68866. }
  68867. });
  68868. }
  68869. else {
  68870. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68871. }
  68872. };
  68873. FilesInput.FilesToLoad = {};
  68874. return FilesInput;
  68875. }());
  68876. BABYLON.FilesInput = FilesInput;
  68877. })(BABYLON || (BABYLON = {}));
  68878. //# sourceMappingURL=babylon.filesInput.js.map
  68879. var BABYLON;
  68880. (function (BABYLON) {
  68881. /**
  68882. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68883. * The underlying implementation relies on an associative array to ensure the best performances.
  68884. * The value can be anything including 'null' but except 'undefined'
  68885. */
  68886. var StringDictionary = /** @class */ (function () {
  68887. function StringDictionary() {
  68888. this._count = 0;
  68889. this._data = {};
  68890. }
  68891. /**
  68892. * This will clear this dictionary and copy the content from the 'source' one.
  68893. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68894. * @param source the dictionary to take the content from and copy to this dictionary
  68895. */
  68896. StringDictionary.prototype.copyFrom = function (source) {
  68897. var _this = this;
  68898. this.clear();
  68899. source.forEach(function (t, v) { return _this.add(t, v); });
  68900. };
  68901. /**
  68902. * Get a value based from its key
  68903. * @param key the given key to get the matching value from
  68904. * @return the value if found, otherwise undefined is returned
  68905. */
  68906. StringDictionary.prototype.get = function (key) {
  68907. var val = this._data[key];
  68908. if (val !== undefined) {
  68909. return val;
  68910. }
  68911. return undefined;
  68912. };
  68913. /**
  68914. * Get a value from its key or add it if it doesn't exist.
  68915. * This method will ensure you that a given key/data will be present in the dictionary.
  68916. * @param key the given key to get the matching value from
  68917. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68918. * The factory will only be invoked if there's no data for the given key.
  68919. * @return the value corresponding to the key.
  68920. */
  68921. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68922. var val = this.get(key);
  68923. if (val !== undefined) {
  68924. return val;
  68925. }
  68926. val = factory(key);
  68927. if (val) {
  68928. this.add(key, val);
  68929. }
  68930. return val;
  68931. };
  68932. /**
  68933. * Get a value from its key if present in the dictionary otherwise add it
  68934. * @param key the key to get the value from
  68935. * @param val if there's no such key/value pair in the dictionary add it with this value
  68936. * @return the value corresponding to the key
  68937. */
  68938. StringDictionary.prototype.getOrAdd = function (key, val) {
  68939. var curVal = this.get(key);
  68940. if (curVal !== undefined) {
  68941. return curVal;
  68942. }
  68943. this.add(key, val);
  68944. return val;
  68945. };
  68946. /**
  68947. * Check if there's a given key in the dictionary
  68948. * @param key the key to check for
  68949. * @return true if the key is present, false otherwise
  68950. */
  68951. StringDictionary.prototype.contains = function (key) {
  68952. return this._data[key] !== undefined;
  68953. };
  68954. /**
  68955. * Add a new key and its corresponding value
  68956. * @param key the key to add
  68957. * @param value the value corresponding to the key
  68958. * @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
  68959. */
  68960. StringDictionary.prototype.add = function (key, value) {
  68961. if (this._data[key] !== undefined) {
  68962. return false;
  68963. }
  68964. this._data[key] = value;
  68965. ++this._count;
  68966. return true;
  68967. };
  68968. StringDictionary.prototype.set = function (key, value) {
  68969. if (this._data[key] === undefined) {
  68970. return false;
  68971. }
  68972. this._data[key] = value;
  68973. return true;
  68974. };
  68975. /**
  68976. * Get the element of the given key and remove it from the dictionary
  68977. * @param key
  68978. */
  68979. StringDictionary.prototype.getAndRemove = function (key) {
  68980. var val = this.get(key);
  68981. if (val !== undefined) {
  68982. delete this._data[key];
  68983. --this._count;
  68984. return val;
  68985. }
  68986. return null;
  68987. };
  68988. /**
  68989. * Remove a key/value from the dictionary.
  68990. * @param key the key to remove
  68991. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68992. */
  68993. StringDictionary.prototype.remove = function (key) {
  68994. if (this.contains(key)) {
  68995. delete this._data[key];
  68996. --this._count;
  68997. return true;
  68998. }
  68999. return false;
  69000. };
  69001. /**
  69002. * Clear the whole content of the dictionary
  69003. */
  69004. StringDictionary.prototype.clear = function () {
  69005. this._data = {};
  69006. this._count = 0;
  69007. };
  69008. Object.defineProperty(StringDictionary.prototype, "count", {
  69009. get: function () {
  69010. return this._count;
  69011. },
  69012. enumerable: true,
  69013. configurable: true
  69014. });
  69015. /**
  69016. * Execute a callback on each key/val of the dictionary.
  69017. * Note that you can remove any element in this dictionary in the callback implementation
  69018. * @param callback the callback to execute on a given key/value pair
  69019. */
  69020. StringDictionary.prototype.forEach = function (callback) {
  69021. for (var cur in this._data) {
  69022. var val = this._data[cur];
  69023. callback(cur, val);
  69024. }
  69025. };
  69026. /**
  69027. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69028. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69029. * Note that you can remove any element in this dictionary in the callback implementation
  69030. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69031. */
  69032. StringDictionary.prototype.first = function (callback) {
  69033. for (var cur in this._data) {
  69034. var val = this._data[cur];
  69035. var res = callback(cur, val);
  69036. if (res) {
  69037. return res;
  69038. }
  69039. }
  69040. return null;
  69041. };
  69042. return StringDictionary;
  69043. }());
  69044. BABYLON.StringDictionary = StringDictionary;
  69045. })(BABYLON || (BABYLON = {}));
  69046. //# sourceMappingURL=babylon.stringDictionary.js.map
  69047. var BABYLON;
  69048. (function (BABYLON) {
  69049. var Tags = /** @class */ (function () {
  69050. function Tags() {
  69051. }
  69052. Tags.EnableFor = function (obj) {
  69053. obj._tags = obj._tags || {};
  69054. obj.hasTags = function () {
  69055. return Tags.HasTags(obj);
  69056. };
  69057. obj.addTags = function (tagsString) {
  69058. return Tags.AddTagsTo(obj, tagsString);
  69059. };
  69060. obj.removeTags = function (tagsString) {
  69061. return Tags.RemoveTagsFrom(obj, tagsString);
  69062. };
  69063. obj.matchesTagsQuery = function (tagsQuery) {
  69064. return Tags.MatchesQuery(obj, tagsQuery);
  69065. };
  69066. };
  69067. Tags.DisableFor = function (obj) {
  69068. delete obj._tags;
  69069. delete obj.hasTags;
  69070. delete obj.addTags;
  69071. delete obj.removeTags;
  69072. delete obj.matchesTagsQuery;
  69073. };
  69074. Tags.HasTags = function (obj) {
  69075. if (!obj._tags) {
  69076. return false;
  69077. }
  69078. return !BABYLON.Tools.IsEmpty(obj._tags);
  69079. };
  69080. Tags.GetTags = function (obj, asString) {
  69081. if (asString === void 0) { asString = true; }
  69082. if (!obj._tags) {
  69083. return null;
  69084. }
  69085. if (asString) {
  69086. var tagsArray = [];
  69087. for (var tag in obj._tags) {
  69088. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69089. tagsArray.push(tag);
  69090. }
  69091. }
  69092. return tagsArray.join(" ");
  69093. }
  69094. else {
  69095. return obj._tags;
  69096. }
  69097. };
  69098. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69099. // a tag cannot start with '||', '&&', and '!'
  69100. // it cannot contain whitespaces
  69101. Tags.AddTagsTo = function (obj, tagsString) {
  69102. if (!tagsString) {
  69103. return;
  69104. }
  69105. if (typeof tagsString !== "string") {
  69106. return;
  69107. }
  69108. var tags = tagsString.split(" ");
  69109. tags.forEach(function (tag, index, array) {
  69110. Tags._AddTagTo(obj, tag);
  69111. });
  69112. };
  69113. Tags._AddTagTo = function (obj, tag) {
  69114. tag = tag.trim();
  69115. if (tag === "" || tag === "true" || tag === "false") {
  69116. return;
  69117. }
  69118. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69119. return;
  69120. }
  69121. Tags.EnableFor(obj);
  69122. obj._tags[tag] = true;
  69123. };
  69124. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69125. if (!Tags.HasTags(obj)) {
  69126. return;
  69127. }
  69128. var tags = tagsString.split(" ");
  69129. for (var t in tags) {
  69130. Tags._RemoveTagFrom(obj, tags[t]);
  69131. }
  69132. };
  69133. Tags._RemoveTagFrom = function (obj, tag) {
  69134. delete obj._tags[tag];
  69135. };
  69136. Tags.MatchesQuery = function (obj, tagsQuery) {
  69137. if (tagsQuery === undefined) {
  69138. return true;
  69139. }
  69140. if (tagsQuery === "") {
  69141. return Tags.HasTags(obj);
  69142. }
  69143. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69144. };
  69145. return Tags;
  69146. }());
  69147. BABYLON.Tags = Tags;
  69148. })(BABYLON || (BABYLON = {}));
  69149. //# sourceMappingURL=babylon.tags.js.map
  69150. var BABYLON;
  69151. (function (BABYLON) {
  69152. /**
  69153. * Class used to evalaute queries containing `and` and `or` operators
  69154. */
  69155. var AndOrNotEvaluator = /** @class */ (function () {
  69156. function AndOrNotEvaluator() {
  69157. }
  69158. /**
  69159. * Evaluate a query
  69160. * @param query defines the query to evaluate
  69161. * @param evaluateCallback defines the callback used to filter result
  69162. * @returns true if the query matches
  69163. */
  69164. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69165. if (!query.match(/\([^\(\)]*\)/g)) {
  69166. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69167. }
  69168. else {
  69169. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69170. // remove parenthesis
  69171. r = r.slice(1, r.length - 1);
  69172. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69173. });
  69174. }
  69175. if (query === "true") {
  69176. return true;
  69177. }
  69178. if (query === "false") {
  69179. return false;
  69180. }
  69181. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69182. };
  69183. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69184. evaluateCallback = evaluateCallback || (function (r) {
  69185. return r === "true" ? true : false;
  69186. });
  69187. var result;
  69188. var or = parenthesisContent.split("||");
  69189. for (var i in or) {
  69190. if (or.hasOwnProperty(i)) {
  69191. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69192. var and = ori.split("&&");
  69193. if (and.length > 1) {
  69194. for (var j = 0; j < and.length; ++j) {
  69195. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69196. if (andj !== "true" && andj !== "false") {
  69197. if (andj[0] === "!") {
  69198. result = !evaluateCallback(andj.substring(1));
  69199. }
  69200. else {
  69201. result = evaluateCallback(andj);
  69202. }
  69203. }
  69204. else {
  69205. result = andj === "true" ? true : false;
  69206. }
  69207. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69208. ori = "false";
  69209. break;
  69210. }
  69211. }
  69212. }
  69213. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69214. result = true;
  69215. break;
  69216. }
  69217. // result equals false (or undefined)
  69218. if (ori !== "true" && ori !== "false") {
  69219. if (ori[0] === "!") {
  69220. result = !evaluateCallback(ori.substring(1));
  69221. }
  69222. else {
  69223. result = evaluateCallback(ori);
  69224. }
  69225. }
  69226. else {
  69227. result = ori === "true" ? true : false;
  69228. }
  69229. }
  69230. }
  69231. // the whole parenthesis scope is replaced by 'true' or 'false'
  69232. return result ? "true" : "false";
  69233. };
  69234. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69235. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69236. // remove whitespaces
  69237. r = r.replace(/[\s]/g, function () { return ""; });
  69238. return r.length % 2 ? "!" : "";
  69239. });
  69240. booleanString = booleanString.trim();
  69241. if (booleanString === "!true") {
  69242. booleanString = "false";
  69243. }
  69244. else if (booleanString === "!false") {
  69245. booleanString = "true";
  69246. }
  69247. return booleanString;
  69248. };
  69249. return AndOrNotEvaluator;
  69250. }());
  69251. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69252. })(BABYLON || (BABYLON = {}));
  69253. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69254. var BABYLON;
  69255. (function (BABYLON) {
  69256. /**
  69257. * Class used to enable access to IndexedDB
  69258. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69259. */
  69260. var Database = /** @class */ (function () {
  69261. /**
  69262. * Creates a new Database
  69263. * @param urlToScene defines the url to load the scene
  69264. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69265. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69266. */
  69267. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69268. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69269. var _this = this;
  69270. // Handling various flavors of prefixed version of IndexedDB
  69271. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69272. this.callbackManifestChecked = callbackManifestChecked;
  69273. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69274. this.db = null;
  69275. this._enableSceneOffline = false;
  69276. this._enableTexturesOffline = false;
  69277. this.manifestVersionFound = 0;
  69278. this.mustUpdateRessources = false;
  69279. this.hasReachedQuota = false;
  69280. if (!Database.IDBStorageEnabled) {
  69281. this.callbackManifestChecked(true);
  69282. }
  69283. else {
  69284. if (disableManifestCheck) {
  69285. this._enableSceneOffline = true;
  69286. this._enableTexturesOffline = true;
  69287. this.manifestVersionFound = 1;
  69288. BABYLON.Tools.SetImmediate(function () {
  69289. _this.callbackManifestChecked(true);
  69290. });
  69291. }
  69292. else {
  69293. this._checkManifestFile();
  69294. }
  69295. }
  69296. }
  69297. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69298. /**
  69299. * Gets a boolean indicating if scene must be saved in the database
  69300. */
  69301. get: function () {
  69302. return this._enableSceneOffline;
  69303. },
  69304. enumerable: true,
  69305. configurable: true
  69306. });
  69307. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69308. /**
  69309. * Gets a boolean indicating if textures must be saved in the database
  69310. */
  69311. get: function () {
  69312. return this._enableTexturesOffline;
  69313. },
  69314. enumerable: true,
  69315. configurable: true
  69316. });
  69317. Database.prototype._checkManifestFile = function () {
  69318. var _this = this;
  69319. var noManifestFile = function () {
  69320. _this._enableSceneOffline = false;
  69321. _this._enableTexturesOffline = false;
  69322. _this.callbackManifestChecked(false);
  69323. };
  69324. var timeStampUsed = false;
  69325. var manifestURL = this.currentSceneUrl + ".manifest";
  69326. var xhr = new XMLHttpRequest();
  69327. if (navigator.onLine) {
  69328. // Adding a timestamp to by-pass browsers' cache
  69329. timeStampUsed = true;
  69330. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69331. }
  69332. xhr.open("GET", manifestURL, true);
  69333. xhr.addEventListener("load", function () {
  69334. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69335. try {
  69336. var manifestFile = JSON.parse(xhr.response);
  69337. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69338. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69339. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69340. _this.manifestVersionFound = manifestFile.version;
  69341. }
  69342. if (_this.callbackManifestChecked) {
  69343. _this.callbackManifestChecked(true);
  69344. }
  69345. }
  69346. catch (ex) {
  69347. noManifestFile();
  69348. }
  69349. }
  69350. else {
  69351. noManifestFile();
  69352. }
  69353. }, false);
  69354. xhr.addEventListener("error", function (event) {
  69355. if (timeStampUsed) {
  69356. timeStampUsed = false;
  69357. // Let's retry without the timeStamp
  69358. // It could fail when coupled with HTML5 Offline API
  69359. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69360. xhr.open("GET", retryManifestURL, true);
  69361. xhr.send();
  69362. }
  69363. else {
  69364. noManifestFile();
  69365. }
  69366. }, false);
  69367. try {
  69368. xhr.send();
  69369. }
  69370. catch (ex) {
  69371. BABYLON.Tools.Error("Error on XHR send request.");
  69372. this.callbackManifestChecked(false);
  69373. }
  69374. };
  69375. /**
  69376. * Open the database and make it available
  69377. * @param successCallback defines the callback to call on success
  69378. * @param errorCallback defines the callback to call on error
  69379. */
  69380. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69381. var _this = this;
  69382. var handleError = function () {
  69383. _this.isSupported = false;
  69384. if (errorCallback)
  69385. errorCallback();
  69386. };
  69387. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69388. // Your browser doesn't support IndexedDB
  69389. this.isSupported = false;
  69390. if (errorCallback)
  69391. errorCallback();
  69392. }
  69393. else {
  69394. // If the DB hasn't been opened or created yet
  69395. if (!this.db) {
  69396. this.hasReachedQuota = false;
  69397. this.isSupported = true;
  69398. var request = this.idbFactory.open("babylonjs", 1);
  69399. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69400. request.onerror = function (event) {
  69401. handleError();
  69402. };
  69403. // executes when a version change transaction cannot complete due to other active transactions
  69404. request.onblocked = function (event) {
  69405. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69406. handleError();
  69407. };
  69408. // DB has been opened successfully
  69409. request.onsuccess = function (event) {
  69410. _this.db = request.result;
  69411. successCallback();
  69412. };
  69413. // Initialization of the DB. Creating Scenes & Textures stores
  69414. request.onupgradeneeded = function (event) {
  69415. _this.db = (event.target).result;
  69416. if (_this.db) {
  69417. try {
  69418. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69419. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69420. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69421. }
  69422. catch (ex) {
  69423. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69424. handleError();
  69425. }
  69426. }
  69427. };
  69428. }
  69429. // DB has already been created and opened
  69430. else {
  69431. if (successCallback)
  69432. successCallback();
  69433. }
  69434. }
  69435. };
  69436. /**
  69437. * Loads an image from the database
  69438. * @param url defines the url to load from
  69439. * @param image defines the target DOM image
  69440. */
  69441. Database.prototype.loadImageFromDB = function (url, image) {
  69442. var _this = this;
  69443. var completeURL = Database._ReturnFullUrlLocation(url);
  69444. var saveAndLoadImage = function () {
  69445. if (!_this.hasReachedQuota && _this.db !== null) {
  69446. // the texture is not yet in the DB, let's try to save it
  69447. _this._saveImageIntoDBAsync(completeURL, image);
  69448. }
  69449. // If the texture is not in the DB and we've reached the DB quota limit
  69450. // let's load it directly from the web
  69451. else {
  69452. image.src = url;
  69453. }
  69454. };
  69455. if (!this.mustUpdateRessources) {
  69456. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69457. }
  69458. // First time we're download the images or update requested in the manifest file by a version change
  69459. else {
  69460. saveAndLoadImage();
  69461. }
  69462. };
  69463. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69464. if (this.isSupported && this.db !== null) {
  69465. var texture;
  69466. var transaction = this.db.transaction(["textures"]);
  69467. transaction.onabort = function (event) {
  69468. image.src = url;
  69469. };
  69470. transaction.oncomplete = function (event) {
  69471. var blobTextureURL;
  69472. if (texture) {
  69473. var URL = window.URL || window.webkitURL;
  69474. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69475. image.onerror = function () {
  69476. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69477. image.src = url;
  69478. };
  69479. image.src = blobTextureURL;
  69480. }
  69481. else {
  69482. notInDBCallback();
  69483. }
  69484. };
  69485. var getRequest = transaction.objectStore("textures").get(url);
  69486. getRequest.onsuccess = function (event) {
  69487. texture = (event.target).result;
  69488. };
  69489. getRequest.onerror = function (event) {
  69490. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69491. image.src = url;
  69492. };
  69493. }
  69494. else {
  69495. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69496. image.src = url;
  69497. }
  69498. };
  69499. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69500. var _this = this;
  69501. if (this.isSupported) {
  69502. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69503. var generateBlobUrl = function () {
  69504. var blobTextureURL;
  69505. if (blob) {
  69506. var URL = window.URL || window.webkitURL;
  69507. try {
  69508. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69509. }
  69510. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69511. catch (ex) {
  69512. blobTextureURL = URL.createObjectURL(blob);
  69513. }
  69514. }
  69515. if (blobTextureURL) {
  69516. image.src = blobTextureURL;
  69517. }
  69518. };
  69519. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69520. var xhr = new XMLHttpRequest(), blob;
  69521. xhr.open("GET", url, true);
  69522. xhr.responseType = "blob";
  69523. xhr.addEventListener("load", function () {
  69524. if (xhr.status === 200 && _this.db) {
  69525. // Blob as response (XHR2)
  69526. blob = xhr.response;
  69527. var transaction = _this.db.transaction(["textures"], "readwrite");
  69528. // the transaction could abort because of a QuotaExceededError error
  69529. transaction.onabort = function (event) {
  69530. try {
  69531. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69532. var srcElement = (event.srcElement || event.target);
  69533. var error = srcElement.error;
  69534. if (error && error.name === "QuotaExceededError") {
  69535. _this.hasReachedQuota = true;
  69536. }
  69537. }
  69538. catch (ex) { }
  69539. generateBlobUrl();
  69540. };
  69541. transaction.oncomplete = function (event) {
  69542. generateBlobUrl();
  69543. };
  69544. var newTexture = { textureUrl: url, data: blob };
  69545. try {
  69546. // Put the blob into the dabase
  69547. var addRequest = transaction.objectStore("textures").put(newTexture);
  69548. addRequest.onsuccess = function (event) {
  69549. };
  69550. addRequest.onerror = function (event) {
  69551. generateBlobUrl();
  69552. };
  69553. }
  69554. catch (ex) {
  69555. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69556. if (ex.code === 25) {
  69557. Database.IsUASupportingBlobStorage = false;
  69558. }
  69559. image.src = url;
  69560. }
  69561. }
  69562. else {
  69563. image.src = url;
  69564. }
  69565. }, false);
  69566. xhr.addEventListener("error", function (event) {
  69567. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69568. image.src = url;
  69569. }, false);
  69570. xhr.send();
  69571. }
  69572. else {
  69573. image.src = url;
  69574. }
  69575. }
  69576. else {
  69577. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69578. image.src = url;
  69579. }
  69580. };
  69581. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69582. var _this = this;
  69583. var updateVersion = function () {
  69584. // the version is not yet in the DB or we need to update it
  69585. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69586. };
  69587. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69588. };
  69589. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69590. var _this = this;
  69591. if (this.isSupported && this.db) {
  69592. var version;
  69593. try {
  69594. var transaction = this.db.transaction(["versions"]);
  69595. transaction.oncomplete = function (event) {
  69596. if (version) {
  69597. // If the version in the JSON file is different from the version in DB
  69598. if (_this.manifestVersionFound !== version.data) {
  69599. _this.mustUpdateRessources = true;
  69600. updateInDBCallback();
  69601. }
  69602. else {
  69603. callback(version.data);
  69604. }
  69605. }
  69606. // version was not found in DB
  69607. else {
  69608. _this.mustUpdateRessources = true;
  69609. updateInDBCallback();
  69610. }
  69611. };
  69612. transaction.onabort = function (event) {
  69613. callback(-1);
  69614. };
  69615. var getRequest = transaction.objectStore("versions").get(url);
  69616. getRequest.onsuccess = function (event) {
  69617. version = (event.target).result;
  69618. };
  69619. getRequest.onerror = function (event) {
  69620. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69621. callback(-1);
  69622. };
  69623. }
  69624. catch (ex) {
  69625. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69626. callback(-1);
  69627. }
  69628. }
  69629. else {
  69630. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69631. callback(-1);
  69632. }
  69633. };
  69634. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69635. var _this = this;
  69636. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69637. try {
  69638. // Open a transaction to the database
  69639. var transaction = this.db.transaction(["versions"], "readwrite");
  69640. // the transaction could abort because of a QuotaExceededError error
  69641. transaction.onabort = function (event) {
  69642. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69643. var error = event.srcElement['error'];
  69644. if (error && error.name === "QuotaExceededError") {
  69645. _this.hasReachedQuota = true;
  69646. }
  69647. }
  69648. catch (ex) { }
  69649. callback(-1);
  69650. };
  69651. transaction.oncomplete = function (event) {
  69652. callback(_this.manifestVersionFound);
  69653. };
  69654. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69655. // Put the scene into the database
  69656. var addRequest = transaction.objectStore("versions").put(newVersion);
  69657. addRequest.onsuccess = function (event) {
  69658. };
  69659. addRequest.onerror = function (event) {
  69660. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69661. };
  69662. }
  69663. catch (ex) {
  69664. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69665. callback(-1);
  69666. }
  69667. }
  69668. else {
  69669. callback(-1);
  69670. }
  69671. };
  69672. /**
  69673. * Loads a file from database
  69674. * @param url defines the URL to load from
  69675. * @param sceneLoaded defines a callback to call on success
  69676. * @param progressCallBack defines a callback to call when progress changed
  69677. * @param errorCallback defines a callback to call on error
  69678. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69679. */
  69680. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69681. var _this = this;
  69682. var completeUrl = Database._ReturnFullUrlLocation(url);
  69683. var saveAndLoadFile = function () {
  69684. // the scene is not yet in the DB, let's try to save it
  69685. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69686. };
  69687. this._checkVersionFromDB(completeUrl, function (version) {
  69688. if (version !== -1) {
  69689. if (!_this.mustUpdateRessources) {
  69690. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69691. }
  69692. else {
  69693. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69694. }
  69695. }
  69696. else {
  69697. if (errorCallback) {
  69698. errorCallback();
  69699. }
  69700. }
  69701. });
  69702. };
  69703. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69704. if (this.isSupported && this.db) {
  69705. var targetStore;
  69706. if (url.indexOf(".babylon") !== -1) {
  69707. targetStore = "scenes";
  69708. }
  69709. else {
  69710. targetStore = "textures";
  69711. }
  69712. var file;
  69713. var transaction = this.db.transaction([targetStore]);
  69714. transaction.oncomplete = function (event) {
  69715. if (file) {
  69716. callback(file.data);
  69717. }
  69718. // file was not found in DB
  69719. else {
  69720. notInDBCallback();
  69721. }
  69722. };
  69723. transaction.onabort = function (event) {
  69724. notInDBCallback();
  69725. };
  69726. var getRequest = transaction.objectStore(targetStore).get(url);
  69727. getRequest.onsuccess = function (event) {
  69728. file = (event.target).result;
  69729. };
  69730. getRequest.onerror = function (event) {
  69731. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69732. notInDBCallback();
  69733. };
  69734. }
  69735. else {
  69736. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69737. callback();
  69738. }
  69739. };
  69740. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69741. var _this = this;
  69742. if (this.isSupported) {
  69743. var targetStore;
  69744. if (url.indexOf(".babylon") !== -1) {
  69745. targetStore = "scenes";
  69746. }
  69747. else {
  69748. targetStore = "textures";
  69749. }
  69750. // Create XHR
  69751. var xhr = new XMLHttpRequest();
  69752. var fileData;
  69753. xhr.open("GET", url, true);
  69754. if (useArrayBuffer) {
  69755. xhr.responseType = "arraybuffer";
  69756. }
  69757. if (progressCallback) {
  69758. xhr.onprogress = progressCallback;
  69759. }
  69760. xhr.addEventListener("load", function () {
  69761. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69762. // Blob as response (XHR2)
  69763. //fileData = xhr.responseText;
  69764. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69765. if (!_this.hasReachedQuota && _this.db) {
  69766. // Open a transaction to the database
  69767. var transaction = _this.db.transaction([targetStore], "readwrite");
  69768. // the transaction could abort because of a QuotaExceededError error
  69769. transaction.onabort = function (event) {
  69770. try {
  69771. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69772. var error = event.srcElement['error'];
  69773. if (error && error.name === "QuotaExceededError") {
  69774. _this.hasReachedQuota = true;
  69775. }
  69776. }
  69777. catch (ex) { }
  69778. callback(fileData);
  69779. };
  69780. transaction.oncomplete = function (event) {
  69781. callback(fileData);
  69782. };
  69783. var newFile;
  69784. if (targetStore === "scenes") {
  69785. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69786. }
  69787. else {
  69788. newFile = { textureUrl: url, data: fileData };
  69789. }
  69790. try {
  69791. // Put the scene into the database
  69792. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69793. addRequest.onsuccess = function (event) {
  69794. };
  69795. addRequest.onerror = function (event) {
  69796. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69797. };
  69798. }
  69799. catch (ex) {
  69800. callback(fileData);
  69801. }
  69802. }
  69803. else {
  69804. callback(fileData);
  69805. }
  69806. }
  69807. else {
  69808. callback();
  69809. }
  69810. }, false);
  69811. xhr.addEventListener("error", function (event) {
  69812. BABYLON.Tools.Error("error on XHR request.");
  69813. callback();
  69814. }, false);
  69815. xhr.send();
  69816. }
  69817. else {
  69818. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69819. callback();
  69820. }
  69821. };
  69822. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69823. Database.IsUASupportingBlobStorage = true;
  69824. /** Gets a boolean indicating if Database storate is enabled */
  69825. Database.IDBStorageEnabled = true;
  69826. Database._ParseURL = function (url) {
  69827. var a = document.createElement('a');
  69828. a.href = url;
  69829. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69830. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69831. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69832. return absLocation;
  69833. };
  69834. Database._ReturnFullUrlLocation = function (url) {
  69835. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69836. return (Database._ParseURL(window.location.href) + url);
  69837. }
  69838. else {
  69839. return url;
  69840. }
  69841. };
  69842. return Database;
  69843. }());
  69844. BABYLON.Database = Database;
  69845. })(BABYLON || (BABYLON = {}));
  69846. //# sourceMappingURL=babylon.database.js.map
  69847. var BABYLON;
  69848. (function (BABYLON) {
  69849. var FresnelParameters = /** @class */ (function () {
  69850. function FresnelParameters() {
  69851. this._isEnabled = true;
  69852. this.leftColor = BABYLON.Color3.White();
  69853. this.rightColor = BABYLON.Color3.Black();
  69854. this.bias = 0;
  69855. this.power = 1;
  69856. }
  69857. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69858. get: function () {
  69859. return this._isEnabled;
  69860. },
  69861. set: function (value) {
  69862. if (this._isEnabled === value) {
  69863. return;
  69864. }
  69865. this._isEnabled = value;
  69866. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69867. },
  69868. enumerable: true,
  69869. configurable: true
  69870. });
  69871. FresnelParameters.prototype.clone = function () {
  69872. var newFresnelParameters = new FresnelParameters();
  69873. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69874. return newFresnelParameters;
  69875. };
  69876. FresnelParameters.prototype.serialize = function () {
  69877. var serializationObject = {};
  69878. serializationObject.isEnabled = this.isEnabled;
  69879. serializationObject.leftColor = this.leftColor.asArray();
  69880. serializationObject.rightColor = this.rightColor.asArray();
  69881. serializationObject.bias = this.bias;
  69882. serializationObject.power = this.power;
  69883. return serializationObject;
  69884. };
  69885. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69886. var fresnelParameters = new FresnelParameters();
  69887. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69888. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69889. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69890. fresnelParameters.bias = parsedFresnelParameters.bias;
  69891. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69892. return fresnelParameters;
  69893. };
  69894. return FresnelParameters;
  69895. }());
  69896. BABYLON.FresnelParameters = FresnelParameters;
  69897. })(BABYLON || (BABYLON = {}));
  69898. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69899. var BABYLON;
  69900. (function (BABYLON) {
  69901. var MultiMaterial = /** @class */ (function (_super) {
  69902. __extends(MultiMaterial, _super);
  69903. function MultiMaterial(name, scene) {
  69904. var _this = _super.call(this, name, scene, true) || this;
  69905. scene.multiMaterials.push(_this);
  69906. _this.subMaterials = new Array();
  69907. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69908. return _this;
  69909. }
  69910. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69911. get: function () {
  69912. return this._subMaterials;
  69913. },
  69914. set: function (value) {
  69915. this._subMaterials = value;
  69916. this._hookArray(value);
  69917. },
  69918. enumerable: true,
  69919. configurable: true
  69920. });
  69921. MultiMaterial.prototype._hookArray = function (array) {
  69922. var _this = this;
  69923. var oldPush = array.push;
  69924. array.push = function () {
  69925. var items = [];
  69926. for (var _i = 0; _i < arguments.length; _i++) {
  69927. items[_i] = arguments[_i];
  69928. }
  69929. var result = oldPush.apply(array, items);
  69930. _this._markAllSubMeshesAsTexturesDirty();
  69931. return result;
  69932. };
  69933. var oldSplice = array.splice;
  69934. array.splice = function (index, deleteCount) {
  69935. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69936. _this._markAllSubMeshesAsTexturesDirty();
  69937. return deleted;
  69938. };
  69939. };
  69940. // Properties
  69941. MultiMaterial.prototype.getSubMaterial = function (index) {
  69942. if (index < 0 || index >= this.subMaterials.length) {
  69943. return this.getScene().defaultMaterial;
  69944. }
  69945. return this.subMaterials[index];
  69946. };
  69947. MultiMaterial.prototype.getActiveTextures = function () {
  69948. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69949. if (subMaterial) {
  69950. return subMaterial.getActiveTextures();
  69951. }
  69952. else {
  69953. return [];
  69954. }
  69955. }));
  69956. var _a;
  69957. };
  69958. // Methods
  69959. MultiMaterial.prototype.getClassName = function () {
  69960. return "MultiMaterial";
  69961. };
  69962. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69963. for (var index = 0; index < this.subMaterials.length; index++) {
  69964. var subMaterial = this.subMaterials[index];
  69965. if (subMaterial) {
  69966. if (subMaterial.storeEffectOnSubMeshes) {
  69967. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69968. return false;
  69969. }
  69970. continue;
  69971. }
  69972. if (!subMaterial.isReady(mesh)) {
  69973. return false;
  69974. }
  69975. }
  69976. }
  69977. return true;
  69978. };
  69979. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69980. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69981. for (var index = 0; index < this.subMaterials.length; index++) {
  69982. var subMaterial = null;
  69983. var current = this.subMaterials[index];
  69984. if (cloneChildren && current) {
  69985. subMaterial = current.clone(name + "-" + current.name);
  69986. }
  69987. else {
  69988. subMaterial = this.subMaterials[index];
  69989. }
  69990. newMultiMaterial.subMaterials.push(subMaterial);
  69991. }
  69992. return newMultiMaterial;
  69993. };
  69994. MultiMaterial.prototype.serialize = function () {
  69995. var serializationObject = {};
  69996. serializationObject.name = this.name;
  69997. serializationObject.id = this.id;
  69998. if (BABYLON.Tags) {
  69999. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70000. }
  70001. serializationObject.materials = [];
  70002. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70003. var subMat = this.subMaterials[matIndex];
  70004. if (subMat) {
  70005. serializationObject.materials.push(subMat.id);
  70006. }
  70007. else {
  70008. serializationObject.materials.push(null);
  70009. }
  70010. }
  70011. return serializationObject;
  70012. };
  70013. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70014. var scene = this.getScene();
  70015. if (!scene) {
  70016. return;
  70017. }
  70018. var index = scene.multiMaterials.indexOf(this);
  70019. if (index >= 0) {
  70020. scene.multiMaterials.splice(index, 1);
  70021. }
  70022. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70023. };
  70024. return MultiMaterial;
  70025. }(BABYLON.Material));
  70026. BABYLON.MultiMaterial = MultiMaterial;
  70027. })(BABYLON || (BABYLON = {}));
  70028. //# sourceMappingURL=babylon.multiMaterial.js.map
  70029. var BABYLON;
  70030. (function (BABYLON) {
  70031. var FreeCameraTouchInput = /** @class */ (function () {
  70032. function FreeCameraTouchInput() {
  70033. this._offsetX = null;
  70034. this._offsetY = null;
  70035. this._pointerPressed = new Array();
  70036. this.touchAngularSensibility = 200000.0;
  70037. this.touchMoveSensibility = 250.0;
  70038. }
  70039. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70040. var _this = this;
  70041. var previousPosition = null;
  70042. if (this._pointerInput === undefined) {
  70043. this._onLostFocus = function (evt) {
  70044. _this._offsetX = null;
  70045. _this._offsetY = null;
  70046. };
  70047. this._pointerInput = function (p, s) {
  70048. var evt = p.event;
  70049. if (evt.pointerType === "mouse") {
  70050. return;
  70051. }
  70052. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70053. if (!noPreventDefault) {
  70054. evt.preventDefault();
  70055. }
  70056. _this._pointerPressed.push(evt.pointerId);
  70057. if (_this._pointerPressed.length !== 1) {
  70058. return;
  70059. }
  70060. previousPosition = {
  70061. x: evt.clientX,
  70062. y: evt.clientY
  70063. };
  70064. }
  70065. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70066. if (!noPreventDefault) {
  70067. evt.preventDefault();
  70068. }
  70069. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70070. if (index === -1) {
  70071. return;
  70072. }
  70073. _this._pointerPressed.splice(index, 1);
  70074. if (index != 0) {
  70075. return;
  70076. }
  70077. previousPosition = null;
  70078. _this._offsetX = null;
  70079. _this._offsetY = null;
  70080. }
  70081. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70082. if (!noPreventDefault) {
  70083. evt.preventDefault();
  70084. }
  70085. if (!previousPosition) {
  70086. return;
  70087. }
  70088. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70089. if (index != 0) {
  70090. return;
  70091. }
  70092. _this._offsetX = evt.clientX - previousPosition.x;
  70093. _this._offsetY = -(evt.clientY - previousPosition.y);
  70094. }
  70095. };
  70096. }
  70097. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70098. if (this._onLostFocus) {
  70099. element.addEventListener("blur", this._onLostFocus);
  70100. }
  70101. };
  70102. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70103. if (this._pointerInput && element) {
  70104. if (this._observer) {
  70105. this.camera.getScene().onPointerObservable.remove(this._observer);
  70106. this._observer = null;
  70107. }
  70108. if (this._onLostFocus) {
  70109. element.removeEventListener("blur", this._onLostFocus);
  70110. this._onLostFocus = null;
  70111. }
  70112. this._pointerPressed = [];
  70113. this._offsetX = null;
  70114. this._offsetY = null;
  70115. }
  70116. };
  70117. FreeCameraTouchInput.prototype.checkInputs = function () {
  70118. if (this._offsetX && this._offsetY) {
  70119. var camera = this.camera;
  70120. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70121. if (this._pointerPressed.length > 1) {
  70122. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70123. }
  70124. else {
  70125. var speed = camera._computeLocalCameraSpeed();
  70126. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70127. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70128. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70129. }
  70130. }
  70131. };
  70132. FreeCameraTouchInput.prototype.getClassName = function () {
  70133. return "FreeCameraTouchInput";
  70134. };
  70135. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70136. return "touch";
  70137. };
  70138. __decorate([
  70139. BABYLON.serialize()
  70140. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70141. __decorate([
  70142. BABYLON.serialize()
  70143. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70144. return FreeCameraTouchInput;
  70145. }());
  70146. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70147. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70148. })(BABYLON || (BABYLON = {}));
  70149. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70150. var BABYLON;
  70151. (function (BABYLON) {
  70152. // We're mainly based on the logic defined into the FreeCamera code
  70153. var TouchCamera = /** @class */ (function (_super) {
  70154. __extends(TouchCamera, _super);
  70155. //-- end properties for backward compatibility for inputs
  70156. function TouchCamera(name, position, scene) {
  70157. var _this = _super.call(this, name, position, scene) || this;
  70158. _this.inputs.addTouch();
  70159. _this._setupInputs();
  70160. return _this;
  70161. }
  70162. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70163. //-- Begin properties for backward compatibility for inputs
  70164. get: function () {
  70165. var touch = this.inputs.attached["touch"];
  70166. if (touch)
  70167. return touch.touchAngularSensibility;
  70168. return 0;
  70169. },
  70170. set: function (value) {
  70171. var touch = this.inputs.attached["touch"];
  70172. if (touch)
  70173. touch.touchAngularSensibility = value;
  70174. },
  70175. enumerable: true,
  70176. configurable: true
  70177. });
  70178. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70179. get: function () {
  70180. var touch = this.inputs.attached["touch"];
  70181. if (touch)
  70182. return touch.touchMoveSensibility;
  70183. return 0;
  70184. },
  70185. set: function (value) {
  70186. var touch = this.inputs.attached["touch"];
  70187. if (touch)
  70188. touch.touchMoveSensibility = value;
  70189. },
  70190. enumerable: true,
  70191. configurable: true
  70192. });
  70193. TouchCamera.prototype.getClassName = function () {
  70194. return "TouchCamera";
  70195. };
  70196. TouchCamera.prototype._setupInputs = function () {
  70197. var mouse = this.inputs.attached["mouse"];
  70198. if (mouse) {
  70199. mouse.touchEnabled = false;
  70200. }
  70201. };
  70202. return TouchCamera;
  70203. }(BABYLON.FreeCamera));
  70204. BABYLON.TouchCamera = TouchCamera;
  70205. })(BABYLON || (BABYLON = {}));
  70206. //# sourceMappingURL=babylon.touchCamera.js.map
  70207. var BABYLON;
  70208. (function (BABYLON) {
  70209. var ProceduralTexture = /** @class */ (function (_super) {
  70210. __extends(ProceduralTexture, _super);
  70211. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70212. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70213. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70214. if (isCube === void 0) { isCube = false; }
  70215. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70216. _this.isCube = isCube;
  70217. _this.isEnabled = true;
  70218. _this._currentRefreshId = -1;
  70219. _this._refreshRate = 1;
  70220. _this._vertexBuffers = {};
  70221. _this._uniforms = new Array();
  70222. _this._samplers = new Array();
  70223. _this._textures = {};
  70224. _this._floats = {};
  70225. _this._floatsArrays = {};
  70226. _this._colors3 = {};
  70227. _this._colors4 = {};
  70228. _this._vectors2 = {};
  70229. _this._vectors3 = {};
  70230. _this._matrices = {};
  70231. _this._fallbackTextureUsed = false;
  70232. scene.proceduralTextures.push(_this);
  70233. _this._engine = scene.getEngine();
  70234. _this.name = name;
  70235. _this.isRenderTarget = true;
  70236. _this._size = size;
  70237. _this._generateMipMaps = generateMipMaps;
  70238. _this.setFragment(fragment);
  70239. _this._fallbackTexture = fallbackTexture;
  70240. if (isCube) {
  70241. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70242. _this.setFloat("face", 0);
  70243. }
  70244. else {
  70245. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70246. }
  70247. // VBO
  70248. var vertices = [];
  70249. vertices.push(1, 1);
  70250. vertices.push(-1, 1);
  70251. vertices.push(-1, -1);
  70252. vertices.push(1, -1);
  70253. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70254. _this._createIndexBuffer();
  70255. return _this;
  70256. }
  70257. ProceduralTexture.prototype._createIndexBuffer = function () {
  70258. var engine = this._engine;
  70259. // Indices
  70260. var indices = [];
  70261. indices.push(0);
  70262. indices.push(1);
  70263. indices.push(2);
  70264. indices.push(0);
  70265. indices.push(2);
  70266. indices.push(3);
  70267. this._indexBuffer = engine.createIndexBuffer(indices);
  70268. };
  70269. ProceduralTexture.prototype._rebuild = function () {
  70270. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70271. if (vb) {
  70272. vb._rebuild();
  70273. }
  70274. this._createIndexBuffer();
  70275. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70276. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70277. }
  70278. };
  70279. ProceduralTexture.prototype.reset = function () {
  70280. if (this._effect === undefined) {
  70281. return;
  70282. }
  70283. var engine = this._engine;
  70284. engine._releaseEffect(this._effect);
  70285. };
  70286. ProceduralTexture.prototype.isReady = function () {
  70287. var _this = this;
  70288. var engine = this._engine;
  70289. var shaders;
  70290. if (!this._fragment) {
  70291. return false;
  70292. }
  70293. if (this._fallbackTextureUsed) {
  70294. return true;
  70295. }
  70296. if (this._fragment.fragmentElement !== undefined) {
  70297. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70298. }
  70299. else {
  70300. shaders = { vertex: "procedural", fragment: this._fragment };
  70301. }
  70302. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70303. _this.releaseInternalTexture();
  70304. if (_this._fallbackTexture) {
  70305. _this._texture = _this._fallbackTexture._texture;
  70306. if (_this._texture) {
  70307. _this._texture.incrementReferences();
  70308. }
  70309. }
  70310. _this._fallbackTextureUsed = true;
  70311. });
  70312. return this._effect.isReady();
  70313. };
  70314. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70315. this._currentRefreshId = -1;
  70316. };
  70317. ProceduralTexture.prototype.setFragment = function (fragment) {
  70318. this._fragment = fragment;
  70319. };
  70320. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70321. get: function () {
  70322. return this._refreshRate;
  70323. },
  70324. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70325. set: function (value) {
  70326. this._refreshRate = value;
  70327. this.resetRefreshCounter();
  70328. },
  70329. enumerable: true,
  70330. configurable: true
  70331. });
  70332. ProceduralTexture.prototype._shouldRender = function () {
  70333. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70334. return false;
  70335. }
  70336. if (this._fallbackTextureUsed) {
  70337. return false;
  70338. }
  70339. if (this._currentRefreshId === -1) { // At least render once
  70340. this._currentRefreshId = 1;
  70341. return true;
  70342. }
  70343. if (this.refreshRate === this._currentRefreshId) {
  70344. this._currentRefreshId = 1;
  70345. return true;
  70346. }
  70347. this._currentRefreshId++;
  70348. return false;
  70349. };
  70350. ProceduralTexture.prototype.getRenderSize = function () {
  70351. return this._size;
  70352. };
  70353. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70354. if (this._fallbackTextureUsed) {
  70355. return;
  70356. }
  70357. this.releaseInternalTexture();
  70358. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70359. };
  70360. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70361. if (this._uniforms.indexOf(uniformName) === -1) {
  70362. this._uniforms.push(uniformName);
  70363. }
  70364. };
  70365. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70366. if (this._samplers.indexOf(name) === -1) {
  70367. this._samplers.push(name);
  70368. }
  70369. this._textures[name] = texture;
  70370. return this;
  70371. };
  70372. ProceduralTexture.prototype.setFloat = function (name, value) {
  70373. this._checkUniform(name);
  70374. this._floats[name] = value;
  70375. return this;
  70376. };
  70377. ProceduralTexture.prototype.setFloats = function (name, value) {
  70378. this._checkUniform(name);
  70379. this._floatsArrays[name] = value;
  70380. return this;
  70381. };
  70382. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70383. this._checkUniform(name);
  70384. this._colors3[name] = value;
  70385. return this;
  70386. };
  70387. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70388. this._checkUniform(name);
  70389. this._colors4[name] = value;
  70390. return this;
  70391. };
  70392. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70393. this._checkUniform(name);
  70394. this._vectors2[name] = value;
  70395. return this;
  70396. };
  70397. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70398. this._checkUniform(name);
  70399. this._vectors3[name] = value;
  70400. return this;
  70401. };
  70402. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70403. this._checkUniform(name);
  70404. this._matrices[name] = value;
  70405. return this;
  70406. };
  70407. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70408. var scene = this.getScene();
  70409. if (!scene) {
  70410. return;
  70411. }
  70412. var engine = this._engine;
  70413. // Render
  70414. engine.enableEffect(this._effect);
  70415. engine.setState(false);
  70416. // Texture
  70417. for (var name in this._textures) {
  70418. this._effect.setTexture(name, this._textures[name]);
  70419. }
  70420. // Float
  70421. for (name in this._floats) {
  70422. this._effect.setFloat(name, this._floats[name]);
  70423. }
  70424. // Floats
  70425. for (name in this._floatsArrays) {
  70426. this._effect.setArray(name, this._floatsArrays[name]);
  70427. }
  70428. // Color3
  70429. for (name in this._colors3) {
  70430. this._effect.setColor3(name, this._colors3[name]);
  70431. }
  70432. // Color4
  70433. for (name in this._colors4) {
  70434. var color = this._colors4[name];
  70435. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70436. }
  70437. // Vector2
  70438. for (name in this._vectors2) {
  70439. this._effect.setVector2(name, this._vectors2[name]);
  70440. }
  70441. // Vector3
  70442. for (name in this._vectors3) {
  70443. this._effect.setVector3(name, this._vectors3[name]);
  70444. }
  70445. // Matrix
  70446. for (name in this._matrices) {
  70447. this._effect.setMatrix(name, this._matrices[name]);
  70448. }
  70449. if (!this._texture) {
  70450. return;
  70451. }
  70452. if (this.isCube) {
  70453. for (var face = 0; face < 6; face++) {
  70454. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70455. // VBOs
  70456. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70457. this._effect.setFloat("face", face);
  70458. // Clear
  70459. engine.clear(scene.clearColor, true, true, true);
  70460. // Draw order
  70461. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70462. // Mipmaps
  70463. if (face === 5) {
  70464. engine.generateMipMapsForCubemap(this._texture);
  70465. }
  70466. }
  70467. }
  70468. else {
  70469. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70470. // VBOs
  70471. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70472. // Clear
  70473. engine.clear(scene.clearColor, true, true, true);
  70474. // Draw order
  70475. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70476. }
  70477. // Unbind
  70478. engine.unBindFramebuffer(this._texture, this.isCube);
  70479. if (this.onGenerated) {
  70480. this.onGenerated();
  70481. }
  70482. };
  70483. ProceduralTexture.prototype.clone = function () {
  70484. var textureSize = this.getSize();
  70485. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70486. // Base texture
  70487. newTexture.hasAlpha = this.hasAlpha;
  70488. newTexture.level = this.level;
  70489. // RenderTarget Texture
  70490. newTexture.coordinatesMode = this.coordinatesMode;
  70491. return newTexture;
  70492. };
  70493. ProceduralTexture.prototype.dispose = function () {
  70494. var scene = this.getScene();
  70495. if (!scene) {
  70496. return;
  70497. }
  70498. var index = scene.proceduralTextures.indexOf(this);
  70499. if (index >= 0) {
  70500. scene.proceduralTextures.splice(index, 1);
  70501. }
  70502. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70503. if (vertexBuffer) {
  70504. vertexBuffer.dispose();
  70505. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70506. }
  70507. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70508. this._indexBuffer = null;
  70509. }
  70510. _super.prototype.dispose.call(this);
  70511. };
  70512. return ProceduralTexture;
  70513. }(BABYLON.Texture));
  70514. BABYLON.ProceduralTexture = ProceduralTexture;
  70515. })(BABYLON || (BABYLON = {}));
  70516. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70517. var BABYLON;
  70518. (function (BABYLON) {
  70519. var CustomProceduralTexture = /** @class */ (function (_super) {
  70520. __extends(CustomProceduralTexture, _super);
  70521. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70522. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70523. _this._animate = true;
  70524. _this._time = 0;
  70525. _this._texturePath = texturePath;
  70526. //Try to load json
  70527. _this.loadJson(texturePath);
  70528. _this.refreshRate = 1;
  70529. return _this;
  70530. }
  70531. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70532. var _this = this;
  70533. var noConfigFile = function () {
  70534. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70535. try {
  70536. _this.setFragment(_this._texturePath);
  70537. }
  70538. catch (ex) {
  70539. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70540. }
  70541. };
  70542. var configFileUrl = jsonUrl + "/config.json";
  70543. var xhr = new XMLHttpRequest();
  70544. xhr.open("GET", configFileUrl, true);
  70545. xhr.addEventListener("load", function () {
  70546. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70547. try {
  70548. _this._config = JSON.parse(xhr.response);
  70549. _this.updateShaderUniforms();
  70550. _this.updateTextures();
  70551. _this.setFragment(_this._texturePath + "/custom");
  70552. _this._animate = _this._config.animate;
  70553. _this.refreshRate = _this._config.refreshrate;
  70554. }
  70555. catch (ex) {
  70556. noConfigFile();
  70557. }
  70558. }
  70559. else {
  70560. noConfigFile();
  70561. }
  70562. }, false);
  70563. xhr.addEventListener("error", function () {
  70564. noConfigFile();
  70565. }, false);
  70566. try {
  70567. xhr.send();
  70568. }
  70569. catch (ex) {
  70570. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70571. }
  70572. };
  70573. CustomProceduralTexture.prototype.isReady = function () {
  70574. if (!_super.prototype.isReady.call(this)) {
  70575. return false;
  70576. }
  70577. for (var name in this._textures) {
  70578. var texture = this._textures[name];
  70579. if (!texture.isReady()) {
  70580. return false;
  70581. }
  70582. }
  70583. return true;
  70584. };
  70585. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70586. var scene = this.getScene();
  70587. if (this._animate && scene) {
  70588. this._time += scene.getAnimationRatio() * 0.03;
  70589. this.updateShaderUniforms();
  70590. }
  70591. _super.prototype.render.call(this, useCameraPostProcess);
  70592. };
  70593. CustomProceduralTexture.prototype.updateTextures = function () {
  70594. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70595. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70596. }
  70597. };
  70598. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70599. if (this._config) {
  70600. for (var j = 0; j < this._config.uniforms.length; j++) {
  70601. var uniform = this._config.uniforms[j];
  70602. switch (uniform.type) {
  70603. case "float":
  70604. this.setFloat(uniform.name, uniform.value);
  70605. break;
  70606. case "color3":
  70607. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70608. break;
  70609. case "color4":
  70610. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70611. break;
  70612. case "vector2":
  70613. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70614. break;
  70615. case "vector3":
  70616. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70617. break;
  70618. }
  70619. }
  70620. }
  70621. this.setFloat("time", this._time);
  70622. };
  70623. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70624. get: function () {
  70625. return this._animate;
  70626. },
  70627. set: function (value) {
  70628. this._animate = value;
  70629. },
  70630. enumerable: true,
  70631. configurable: true
  70632. });
  70633. return CustomProceduralTexture;
  70634. }(BABYLON.ProceduralTexture));
  70635. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70636. })(BABYLON || (BABYLON = {}));
  70637. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70638. var BABYLON;
  70639. (function (BABYLON) {
  70640. var FreeCameraGamepadInput = /** @class */ (function () {
  70641. function FreeCameraGamepadInput() {
  70642. this.gamepadAngularSensibility = 200;
  70643. this.gamepadMoveSensibility = 40;
  70644. // private members
  70645. this._cameraTransform = BABYLON.Matrix.Identity();
  70646. this._deltaTransform = BABYLON.Vector3.Zero();
  70647. this._vector3 = BABYLON.Vector3.Zero();
  70648. this._vector2 = BABYLON.Vector2.Zero();
  70649. }
  70650. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70651. var _this = this;
  70652. var manager = this.camera.getScene().gamepadManager;
  70653. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70654. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70655. // prioritize XBOX gamepads.
  70656. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70657. _this.gamepad = gamepad;
  70658. }
  70659. }
  70660. });
  70661. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70662. if (_this.gamepad === gamepad) {
  70663. _this.gamepad = null;
  70664. }
  70665. });
  70666. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70667. };
  70668. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70669. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70670. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70671. this.gamepad = null;
  70672. };
  70673. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70674. if (this.gamepad && this.gamepad.leftStick) {
  70675. var camera = this.camera;
  70676. var LSValues = this.gamepad.leftStick;
  70677. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70678. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70679. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70680. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70681. var RSValues = this.gamepad.rightStick;
  70682. if (RSValues) {
  70683. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70684. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70685. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70686. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70687. }
  70688. else {
  70689. RSValues = { x: 0, y: 0 };
  70690. }
  70691. if (!camera.rotationQuaternion) {
  70692. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70693. }
  70694. else {
  70695. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70696. }
  70697. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70698. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70699. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70700. camera.cameraDirection.addInPlace(this._deltaTransform);
  70701. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70702. camera.cameraRotation.addInPlace(this._vector2);
  70703. }
  70704. };
  70705. FreeCameraGamepadInput.prototype.getClassName = function () {
  70706. return "FreeCameraGamepadInput";
  70707. };
  70708. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70709. return "gamepad";
  70710. };
  70711. __decorate([
  70712. BABYLON.serialize()
  70713. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70714. __decorate([
  70715. BABYLON.serialize()
  70716. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70717. return FreeCameraGamepadInput;
  70718. }());
  70719. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70720. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70721. })(BABYLON || (BABYLON = {}));
  70722. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70723. var BABYLON;
  70724. (function (BABYLON) {
  70725. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70726. function ArcRotateCameraGamepadInput() {
  70727. this.gamepadRotationSensibility = 80;
  70728. this.gamepadMoveSensibility = 40;
  70729. }
  70730. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70731. var _this = this;
  70732. var manager = this.camera.getScene().gamepadManager;
  70733. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70734. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70735. // prioritize XBOX gamepads.
  70736. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70737. _this.gamepad = gamepad;
  70738. }
  70739. }
  70740. });
  70741. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70742. if (_this.gamepad === gamepad) {
  70743. _this.gamepad = null;
  70744. }
  70745. });
  70746. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70747. };
  70748. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70749. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70750. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70751. this.gamepad = null;
  70752. };
  70753. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70754. if (this.gamepad) {
  70755. var camera = this.camera;
  70756. var RSValues = this.gamepad.rightStick;
  70757. if (RSValues) {
  70758. if (RSValues.x != 0) {
  70759. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70760. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70761. camera.inertialAlphaOffset += normalizedRX;
  70762. }
  70763. }
  70764. if (RSValues.y != 0) {
  70765. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70766. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70767. camera.inertialBetaOffset += normalizedRY;
  70768. }
  70769. }
  70770. }
  70771. var LSValues = this.gamepad.leftStick;
  70772. if (LSValues && LSValues.y != 0) {
  70773. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70774. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70775. this.camera.inertialRadiusOffset -= normalizedLY;
  70776. }
  70777. }
  70778. }
  70779. };
  70780. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70781. return "ArcRotateCameraGamepadInput";
  70782. };
  70783. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70784. return "gamepad";
  70785. };
  70786. __decorate([
  70787. BABYLON.serialize()
  70788. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70789. __decorate([
  70790. BABYLON.serialize()
  70791. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70792. return ArcRotateCameraGamepadInput;
  70793. }());
  70794. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70795. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70796. })(BABYLON || (BABYLON = {}));
  70797. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70798. var BABYLON;
  70799. (function (BABYLON) {
  70800. var GamepadManager = /** @class */ (function () {
  70801. function GamepadManager(_scene) {
  70802. var _this = this;
  70803. this._scene = _scene;
  70804. this._babylonGamepads = [];
  70805. this._oneGamepadConnected = false;
  70806. this._isMonitoring = false;
  70807. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70808. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70809. this._gamepadEventSupported = false;
  70810. }
  70811. else {
  70812. this._gamepadEventSupported = 'GamepadEvent' in window;
  70813. this._gamepadSupport = (navigator.getGamepads ||
  70814. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70815. }
  70816. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70817. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70818. for (var i in _this._babylonGamepads) {
  70819. var gamepad = _this._babylonGamepads[i];
  70820. if (gamepad && gamepad._isConnected) {
  70821. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70822. }
  70823. }
  70824. });
  70825. this._onGamepadConnectedEvent = function (evt) {
  70826. var gamepad = evt.gamepad;
  70827. if (gamepad.index in _this._babylonGamepads) {
  70828. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70829. return;
  70830. }
  70831. }
  70832. var newGamepad;
  70833. if (_this._babylonGamepads[gamepad.index]) {
  70834. newGamepad = _this._babylonGamepads[gamepad.index];
  70835. newGamepad.browserGamepad = gamepad;
  70836. newGamepad._isConnected = true;
  70837. }
  70838. else {
  70839. newGamepad = _this._addNewGamepad(gamepad);
  70840. }
  70841. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70842. _this._startMonitoringGamepads();
  70843. };
  70844. this._onGamepadDisconnectedEvent = function (evt) {
  70845. var gamepad = evt.gamepad;
  70846. // Remove the gamepad from the list of gamepads to monitor.
  70847. for (var i in _this._babylonGamepads) {
  70848. if (_this._babylonGamepads[i].index === gamepad.index) {
  70849. var disconnectedGamepad = _this._babylonGamepads[i];
  70850. disconnectedGamepad._isConnected = false;
  70851. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70852. break;
  70853. }
  70854. }
  70855. };
  70856. if (this._gamepadSupport) {
  70857. //first add already-connected gamepads
  70858. this._updateGamepadObjects();
  70859. if (this._babylonGamepads.length) {
  70860. this._startMonitoringGamepads();
  70861. }
  70862. // Checking if the gamepad connected event is supported (like in Firefox)
  70863. if (this._gamepadEventSupported) {
  70864. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70865. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70866. }
  70867. else {
  70868. this._startMonitoringGamepads();
  70869. }
  70870. }
  70871. }
  70872. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70873. get: function () {
  70874. return this._babylonGamepads;
  70875. },
  70876. enumerable: true,
  70877. configurable: true
  70878. });
  70879. GamepadManager.prototype.getGamepadByType = function (type) {
  70880. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70881. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70882. var gamepad = _a[_i];
  70883. if (gamepad && gamepad.type === type) {
  70884. return gamepad;
  70885. }
  70886. }
  70887. return null;
  70888. };
  70889. GamepadManager.prototype.dispose = function () {
  70890. if (this._gamepadEventSupported) {
  70891. if (this._onGamepadConnectedEvent) {
  70892. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70893. }
  70894. if (this._onGamepadDisconnectedEvent) {
  70895. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70896. }
  70897. this._onGamepadConnectedEvent = null;
  70898. this._onGamepadDisconnectedEvent = null;
  70899. }
  70900. this._babylonGamepads.forEach(function (gamepad) {
  70901. gamepad.dispose();
  70902. });
  70903. this.onGamepadConnectedObservable.clear();
  70904. this.onGamepadDisconnectedObservable.clear();
  70905. this._oneGamepadConnected = false;
  70906. this._stopMonitoringGamepads();
  70907. this._babylonGamepads = [];
  70908. };
  70909. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70910. if (!this._oneGamepadConnected) {
  70911. this._oneGamepadConnected = true;
  70912. }
  70913. var newGamepad;
  70914. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70915. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70916. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70917. }
  70918. // if pose is supported, use the (WebVR) pose enabled controller
  70919. else if (gamepad.pose) {
  70920. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70921. }
  70922. else {
  70923. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70924. }
  70925. this._babylonGamepads[newGamepad.index] = newGamepad;
  70926. return newGamepad;
  70927. };
  70928. GamepadManager.prototype._startMonitoringGamepads = function () {
  70929. if (!this._isMonitoring) {
  70930. this._isMonitoring = true;
  70931. //back-comp
  70932. if (!this._scene) {
  70933. this._checkGamepadsStatus();
  70934. }
  70935. }
  70936. };
  70937. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70938. this._isMonitoring = false;
  70939. };
  70940. GamepadManager.prototype._checkGamepadsStatus = function () {
  70941. var _this = this;
  70942. // Hack to be compatible Chrome
  70943. this._updateGamepadObjects();
  70944. for (var i in this._babylonGamepads) {
  70945. var gamepad = this._babylonGamepads[i];
  70946. if (!gamepad || !gamepad.isConnected) {
  70947. continue;
  70948. }
  70949. gamepad.update();
  70950. }
  70951. if (this._isMonitoring && !this._scene) {
  70952. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70953. }
  70954. };
  70955. // This function is called only on Chrome, which does not properly support
  70956. // connection/disconnection events and forces you to recopy again the gamepad object
  70957. GamepadManager.prototype._updateGamepadObjects = function () {
  70958. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70959. for (var i = 0; i < gamepads.length; i++) {
  70960. var gamepad = gamepads[i];
  70961. if (gamepad) {
  70962. if (!this._babylonGamepads[gamepad.index]) {
  70963. var newGamepad = this._addNewGamepad(gamepad);
  70964. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70965. }
  70966. else {
  70967. // Forced to copy again this object for Chrome for unknown reason
  70968. this._babylonGamepads[i].browserGamepad = gamepad;
  70969. if (!this._babylonGamepads[i].isConnected) {
  70970. this._babylonGamepads[i]._isConnected = true;
  70971. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70972. }
  70973. }
  70974. }
  70975. }
  70976. };
  70977. return GamepadManager;
  70978. }());
  70979. BABYLON.GamepadManager = GamepadManager;
  70980. })(BABYLON || (BABYLON = {}));
  70981. //# sourceMappingURL=babylon.gamepadManager.js.map
  70982. var BABYLON;
  70983. (function (BABYLON) {
  70984. var StickValues = /** @class */ (function () {
  70985. function StickValues(x, y) {
  70986. this.x = x;
  70987. this.y = y;
  70988. }
  70989. return StickValues;
  70990. }());
  70991. BABYLON.StickValues = StickValues;
  70992. var Gamepad = /** @class */ (function () {
  70993. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70994. if (leftStickX === void 0) { leftStickX = 0; }
  70995. if (leftStickY === void 0) { leftStickY = 1; }
  70996. if (rightStickX === void 0) { rightStickX = 2; }
  70997. if (rightStickY === void 0) { rightStickY = 3; }
  70998. this.id = id;
  70999. this.index = index;
  71000. this.browserGamepad = browserGamepad;
  71001. this._isConnected = true;
  71002. this._invertLeftStickY = false;
  71003. this.type = Gamepad.GAMEPAD;
  71004. this._leftStickAxisX = leftStickX;
  71005. this._leftStickAxisY = leftStickY;
  71006. this._rightStickAxisX = rightStickX;
  71007. this._rightStickAxisY = rightStickY;
  71008. if (this.browserGamepad.axes.length >= 2) {
  71009. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71010. }
  71011. if (this.browserGamepad.axes.length >= 4) {
  71012. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71013. }
  71014. }
  71015. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71016. get: function () {
  71017. return this._isConnected;
  71018. },
  71019. enumerable: true,
  71020. configurable: true
  71021. });
  71022. Gamepad.prototype.onleftstickchanged = function (callback) {
  71023. this._onleftstickchanged = callback;
  71024. };
  71025. Gamepad.prototype.onrightstickchanged = function (callback) {
  71026. this._onrightstickchanged = callback;
  71027. };
  71028. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71029. get: function () {
  71030. return this._leftStick;
  71031. },
  71032. set: function (newValues) {
  71033. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71034. this._onleftstickchanged(newValues);
  71035. }
  71036. this._leftStick = newValues;
  71037. },
  71038. enumerable: true,
  71039. configurable: true
  71040. });
  71041. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71042. get: function () {
  71043. return this._rightStick;
  71044. },
  71045. set: function (newValues) {
  71046. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71047. this._onrightstickchanged(newValues);
  71048. }
  71049. this._rightStick = newValues;
  71050. },
  71051. enumerable: true,
  71052. configurable: true
  71053. });
  71054. Gamepad.prototype.update = function () {
  71055. if (this._leftStick) {
  71056. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71057. if (this._invertLeftStickY) {
  71058. this.leftStick.y *= -1;
  71059. }
  71060. }
  71061. if (this._rightStick) {
  71062. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71063. }
  71064. };
  71065. Gamepad.prototype.dispose = function () {
  71066. };
  71067. Gamepad.GAMEPAD = 0;
  71068. Gamepad.GENERIC = 1;
  71069. Gamepad.XBOX = 2;
  71070. Gamepad.POSE_ENABLED = 3;
  71071. return Gamepad;
  71072. }());
  71073. BABYLON.Gamepad = Gamepad;
  71074. var GenericPad = /** @class */ (function (_super) {
  71075. __extends(GenericPad, _super);
  71076. function GenericPad(id, index, browserGamepad) {
  71077. var _this = _super.call(this, id, index, browserGamepad) || this;
  71078. _this.onButtonDownObservable = new BABYLON.Observable();
  71079. _this.onButtonUpObservable = new BABYLON.Observable();
  71080. _this.type = Gamepad.GENERIC;
  71081. _this._buttons = new Array(browserGamepad.buttons.length);
  71082. return _this;
  71083. }
  71084. GenericPad.prototype.onbuttondown = function (callback) {
  71085. this._onbuttondown = callback;
  71086. };
  71087. GenericPad.prototype.onbuttonup = function (callback) {
  71088. this._onbuttonup = callback;
  71089. };
  71090. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71091. if (newValue !== currentValue) {
  71092. if (newValue === 1) {
  71093. if (this._onbuttondown) {
  71094. this._onbuttondown(buttonIndex);
  71095. }
  71096. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71097. }
  71098. if (newValue === 0) {
  71099. if (this._onbuttonup) {
  71100. this._onbuttonup(buttonIndex);
  71101. }
  71102. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71103. }
  71104. }
  71105. return newValue;
  71106. };
  71107. GenericPad.prototype.update = function () {
  71108. _super.prototype.update.call(this);
  71109. for (var index = 0; index < this._buttons.length; index++) {
  71110. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71111. }
  71112. };
  71113. GenericPad.prototype.dispose = function () {
  71114. _super.prototype.dispose.call(this);
  71115. this.onButtonDownObservable.clear();
  71116. this.onButtonUpObservable.clear();
  71117. };
  71118. return GenericPad;
  71119. }(Gamepad));
  71120. BABYLON.GenericPad = GenericPad;
  71121. })(BABYLON || (BABYLON = {}));
  71122. //# sourceMappingURL=babylon.gamepad.js.map
  71123. var BABYLON;
  71124. (function (BABYLON) {
  71125. /**
  71126. * Defines supported buttons for XBox360 compatible gamepads
  71127. */
  71128. var Xbox360Button;
  71129. (function (Xbox360Button) {
  71130. /** A */
  71131. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71132. /** B */
  71133. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71134. /** X */
  71135. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71136. /** Y */
  71137. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71138. /** Start */
  71139. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71140. /** Back */
  71141. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71142. /** Left button */
  71143. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71144. /** Right button */
  71145. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71146. /** Left stick */
  71147. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71148. /** Right stick */
  71149. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71150. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71151. /** Defines values for XBox360 DPad */
  71152. var Xbox360Dpad;
  71153. (function (Xbox360Dpad) {
  71154. /** Up */
  71155. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71156. /** Down */
  71157. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71158. /** Left */
  71159. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71160. /** Right */
  71161. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71162. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71163. /**
  71164. * Defines a XBox360 gamepad
  71165. */
  71166. var Xbox360Pad = /** @class */ (function (_super) {
  71167. __extends(Xbox360Pad, _super);
  71168. /**
  71169. * Creates a new XBox360 gamepad object
  71170. * @param id defines the id of this gamepad
  71171. * @param index defines its index
  71172. * @param gamepad defines the internal HTML gamepad object
  71173. * @param xboxOne defines if it is a XBox One gamepad
  71174. */
  71175. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71176. if (xboxOne === void 0) { xboxOne = false; }
  71177. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71178. _this._leftTrigger = 0;
  71179. _this._rightTrigger = 0;
  71180. /** Observable raised when a button is pressed */
  71181. _this.onButtonDownObservable = new BABYLON.Observable();
  71182. /** Observable raised when a button is released */
  71183. _this.onButtonUpObservable = new BABYLON.Observable();
  71184. /** Observable raised when a pad is pressed */
  71185. _this.onPadDownObservable = new BABYLON.Observable();
  71186. /** Observable raised when a pad is released */
  71187. _this.onPadUpObservable = new BABYLON.Observable();
  71188. _this._buttonA = 0;
  71189. _this._buttonB = 0;
  71190. _this._buttonX = 0;
  71191. _this._buttonY = 0;
  71192. _this._buttonBack = 0;
  71193. _this._buttonStart = 0;
  71194. _this._buttonLB = 0;
  71195. _this._buttonRB = 0;
  71196. _this._buttonLeftStick = 0;
  71197. _this._buttonRightStick = 0;
  71198. _this._dPadUp = 0;
  71199. _this._dPadDown = 0;
  71200. _this._dPadLeft = 0;
  71201. _this._dPadRight = 0;
  71202. _this._isXboxOnePad = false;
  71203. _this.type = BABYLON.Gamepad.XBOX;
  71204. _this._isXboxOnePad = xboxOne;
  71205. return _this;
  71206. }
  71207. /**
  71208. * Defines the callback to call when left trigger is pressed
  71209. * @param callback defines the callback to use
  71210. */
  71211. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71212. this._onlefttriggerchanged = callback;
  71213. };
  71214. /**
  71215. * Defines the callback to call when right trigger is pressed
  71216. * @param callback defines the callback to use
  71217. */
  71218. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71219. this._onrighttriggerchanged = callback;
  71220. };
  71221. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71222. /**
  71223. * Gets or sets left trigger value
  71224. */
  71225. get: function () {
  71226. return this._leftTrigger;
  71227. },
  71228. set: function (newValue) {
  71229. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71230. this._onlefttriggerchanged(newValue);
  71231. }
  71232. this._leftTrigger = newValue;
  71233. },
  71234. enumerable: true,
  71235. configurable: true
  71236. });
  71237. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71238. /**
  71239. * Gets or sets right trigger value
  71240. */
  71241. get: function () {
  71242. return this._rightTrigger;
  71243. },
  71244. set: function (newValue) {
  71245. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71246. this._onrighttriggerchanged(newValue);
  71247. }
  71248. this._rightTrigger = newValue;
  71249. },
  71250. enumerable: true,
  71251. configurable: true
  71252. });
  71253. /**
  71254. * Defines the callback to call when a button is pressed
  71255. * @param callback defines the callback to use
  71256. */
  71257. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71258. this._onbuttondown = callback;
  71259. };
  71260. /**
  71261. * Defines the callback to call when a button is released
  71262. * @param callback defines the callback to use
  71263. */
  71264. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71265. this._onbuttonup = callback;
  71266. };
  71267. /**
  71268. * Defines the callback to call when a pad is pressed
  71269. * @param callback defines the callback to use
  71270. */
  71271. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71272. this._ondpaddown = callback;
  71273. };
  71274. /**
  71275. * Defines the callback to call when a pad is released
  71276. * @param callback defines the callback to use
  71277. */
  71278. Xbox360Pad.prototype.ondpadup = function (callback) {
  71279. this._ondpadup = callback;
  71280. };
  71281. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71282. if (newValue !== currentValue) {
  71283. if (newValue === 1) {
  71284. if (this._onbuttondown) {
  71285. this._onbuttondown(buttonType);
  71286. }
  71287. this.onButtonDownObservable.notifyObservers(buttonType);
  71288. }
  71289. if (newValue === 0) {
  71290. if (this._onbuttonup) {
  71291. this._onbuttonup(buttonType);
  71292. }
  71293. this.onButtonUpObservable.notifyObservers(buttonType);
  71294. }
  71295. }
  71296. return newValue;
  71297. };
  71298. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71299. if (newValue !== currentValue) {
  71300. if (newValue === 1) {
  71301. if (this._ondpaddown) {
  71302. this._ondpaddown(buttonType);
  71303. }
  71304. this.onPadDownObservable.notifyObservers(buttonType);
  71305. }
  71306. if (newValue === 0) {
  71307. if (this._ondpadup) {
  71308. this._ondpadup(buttonType);
  71309. }
  71310. this.onPadUpObservable.notifyObservers(buttonType);
  71311. }
  71312. }
  71313. return newValue;
  71314. };
  71315. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71316. /** Gets or sets value of A button */
  71317. get: function () {
  71318. return this._buttonA;
  71319. },
  71320. set: function (value) {
  71321. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71322. },
  71323. enumerable: true,
  71324. configurable: true
  71325. });
  71326. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71327. /** Gets or sets value of B button */
  71328. get: function () {
  71329. return this._buttonB;
  71330. },
  71331. set: function (value) {
  71332. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71333. },
  71334. enumerable: true,
  71335. configurable: true
  71336. });
  71337. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71338. /** Gets or sets value of X button */
  71339. get: function () {
  71340. return this._buttonX;
  71341. },
  71342. set: function (value) {
  71343. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71344. },
  71345. enumerable: true,
  71346. configurable: true
  71347. });
  71348. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71349. /** Gets or sets value of Y button */
  71350. get: function () {
  71351. return this._buttonY;
  71352. },
  71353. set: function (value) {
  71354. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71355. },
  71356. enumerable: true,
  71357. configurable: true
  71358. });
  71359. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71360. /** Gets or sets value of Start button */
  71361. get: function () {
  71362. return this._buttonStart;
  71363. },
  71364. set: function (value) {
  71365. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71371. /** Gets or sets value of Back button */
  71372. get: function () {
  71373. return this._buttonBack;
  71374. },
  71375. set: function (value) {
  71376. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71377. },
  71378. enumerable: true,
  71379. configurable: true
  71380. });
  71381. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71382. /** Gets or sets value of Left button */
  71383. get: function () {
  71384. return this._buttonLB;
  71385. },
  71386. set: function (value) {
  71387. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71388. },
  71389. enumerable: true,
  71390. configurable: true
  71391. });
  71392. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71393. /** Gets or sets value of Right button */
  71394. get: function () {
  71395. return this._buttonRB;
  71396. },
  71397. set: function (value) {
  71398. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71399. },
  71400. enumerable: true,
  71401. configurable: true
  71402. });
  71403. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71404. /** Gets or sets value of left stick */
  71405. get: function () {
  71406. return this._buttonLeftStick;
  71407. },
  71408. set: function (value) {
  71409. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71410. },
  71411. enumerable: true,
  71412. configurable: true
  71413. });
  71414. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71415. /** Gets or sets value of right stick */
  71416. get: function () {
  71417. return this._buttonRightStick;
  71418. },
  71419. set: function (value) {
  71420. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71421. },
  71422. enumerable: true,
  71423. configurable: true
  71424. });
  71425. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71426. /** Gets or sets value of DPad up */
  71427. get: function () {
  71428. return this._dPadUp;
  71429. },
  71430. set: function (value) {
  71431. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71432. },
  71433. enumerable: true,
  71434. configurable: true
  71435. });
  71436. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71437. /** Gets or sets value of DPad down */
  71438. get: function () {
  71439. return this._dPadDown;
  71440. },
  71441. set: function (value) {
  71442. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71443. },
  71444. enumerable: true,
  71445. configurable: true
  71446. });
  71447. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71448. /** Gets or sets value of DPad left */
  71449. get: function () {
  71450. return this._dPadLeft;
  71451. },
  71452. set: function (value) {
  71453. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71454. },
  71455. enumerable: true,
  71456. configurable: true
  71457. });
  71458. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71459. /** Gets or sets value of DPad right */
  71460. get: function () {
  71461. return this._dPadRight;
  71462. },
  71463. set: function (value) {
  71464. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71465. },
  71466. enumerable: true,
  71467. configurable: true
  71468. });
  71469. /**
  71470. * Force the gamepad to synchronize with device values
  71471. */
  71472. Xbox360Pad.prototype.update = function () {
  71473. _super.prototype.update.call(this);
  71474. if (this._isXboxOnePad) {
  71475. this.buttonA = this.browserGamepad.buttons[0].value;
  71476. this.buttonB = this.browserGamepad.buttons[1].value;
  71477. this.buttonX = this.browserGamepad.buttons[2].value;
  71478. this.buttonY = this.browserGamepad.buttons[3].value;
  71479. this.buttonLB = this.browserGamepad.buttons[4].value;
  71480. this.buttonRB = this.browserGamepad.buttons[5].value;
  71481. this.leftTrigger = this.browserGamepad.axes[2];
  71482. this.rightTrigger = this.browserGamepad.axes[5];
  71483. this.buttonBack = this.browserGamepad.buttons[9].value;
  71484. this.buttonStart = this.browserGamepad.buttons[8].value;
  71485. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71486. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71487. this.dPadUp = this.browserGamepad.buttons[11].value;
  71488. this.dPadDown = this.browserGamepad.buttons[12].value;
  71489. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71490. this.dPadRight = this.browserGamepad.buttons[14].value;
  71491. }
  71492. else {
  71493. this.buttonA = this.browserGamepad.buttons[0].value;
  71494. this.buttonB = this.browserGamepad.buttons[1].value;
  71495. this.buttonX = this.browserGamepad.buttons[2].value;
  71496. this.buttonY = this.browserGamepad.buttons[3].value;
  71497. this.buttonLB = this.browserGamepad.buttons[4].value;
  71498. this.buttonRB = this.browserGamepad.buttons[5].value;
  71499. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71500. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71501. this.buttonBack = this.browserGamepad.buttons[8].value;
  71502. this.buttonStart = this.browserGamepad.buttons[9].value;
  71503. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71504. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71505. this.dPadUp = this.browserGamepad.buttons[12].value;
  71506. this.dPadDown = this.browserGamepad.buttons[13].value;
  71507. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71508. this.dPadRight = this.browserGamepad.buttons[15].value;
  71509. }
  71510. };
  71511. Xbox360Pad.prototype.dispose = function () {
  71512. _super.prototype.dispose.call(this);
  71513. this.onButtonDownObservable.clear();
  71514. this.onButtonUpObservable.clear();
  71515. this.onPadDownObservable.clear();
  71516. this.onPadUpObservable.clear();
  71517. };
  71518. return Xbox360Pad;
  71519. }(BABYLON.Gamepad));
  71520. BABYLON.Xbox360Pad = Xbox360Pad;
  71521. })(BABYLON || (BABYLON = {}));
  71522. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71523. var BABYLON;
  71524. (function (BABYLON) {
  71525. /**
  71526. * Defines the types of pose enabled controllers that are supported
  71527. */
  71528. var PoseEnabledControllerType;
  71529. (function (PoseEnabledControllerType) {
  71530. /**
  71531. * HTC Vive
  71532. */
  71533. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71534. /**
  71535. * Oculus Rift
  71536. */
  71537. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71538. /**
  71539. * Windows mixed reality
  71540. */
  71541. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71542. /**
  71543. * Samsung gear VR
  71544. */
  71545. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71546. /**
  71547. * Google Daydream
  71548. */
  71549. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71550. /**
  71551. * Generic
  71552. */
  71553. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71554. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71555. /**
  71556. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71557. */
  71558. var PoseEnabledControllerHelper = /** @class */ (function () {
  71559. function PoseEnabledControllerHelper() {
  71560. }
  71561. /**
  71562. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71563. * @param vrGamepad the gamepad to initialized
  71564. * @returns a vr controller of the type the gamepad identified as
  71565. */
  71566. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71567. // Oculus Touch
  71568. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71569. return new BABYLON.OculusTouchController(vrGamepad);
  71570. }
  71571. // Windows Mixed Reality controllers
  71572. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71573. return new BABYLON.WindowsMotionController(vrGamepad);
  71574. }
  71575. // HTC Vive
  71576. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71577. return new BABYLON.ViveController(vrGamepad);
  71578. }
  71579. // Samsung/Oculus Gear VR or Oculus Go
  71580. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71581. return new BABYLON.GearVRController(vrGamepad);
  71582. }
  71583. // Google Daydream
  71584. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71585. return new BABYLON.DaydreamController(vrGamepad);
  71586. }
  71587. // Generic
  71588. else {
  71589. return new BABYLON.GenericController(vrGamepad);
  71590. }
  71591. };
  71592. return PoseEnabledControllerHelper;
  71593. }());
  71594. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71595. /**
  71596. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71597. */
  71598. var PoseEnabledController = /** @class */ (function (_super) {
  71599. __extends(PoseEnabledController, _super);
  71600. /**
  71601. * Creates a new PoseEnabledController from a gamepad
  71602. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71603. */
  71604. function PoseEnabledController(browserGamepad) {
  71605. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71606. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71607. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71608. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71609. /**
  71610. * The device position in babylon space
  71611. */
  71612. _this.devicePosition = BABYLON.Vector3.Zero();
  71613. /**
  71614. * The device rotation in babylon space
  71615. */
  71616. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71617. /**
  71618. * The scale factor of the device in babylon space
  71619. */
  71620. _this.deviceScaleFactor = 1;
  71621. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71622. /**
  71623. * Internal, matrix used to convert room space to babylon space
  71624. */
  71625. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71626. /**
  71627. * Node to be used when casting a ray from the controller
  71628. */
  71629. _this._pointingPoseNode = null;
  71630. _this._workingMatrix = BABYLON.Matrix.Identity();
  71631. /**
  71632. * @hidden
  71633. */
  71634. _this._meshAttachedObservable = new BABYLON.Observable();
  71635. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71636. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71637. _this.position = BABYLON.Vector3.Zero();
  71638. _this.rotationQuaternion = new BABYLON.Quaternion();
  71639. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71640. _this._calculatedRotation = new BABYLON.Quaternion();
  71641. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71642. return _this;
  71643. }
  71644. /**
  71645. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71646. */
  71647. PoseEnabledController.prototype.update = function () {
  71648. _super.prototype.update.call(this);
  71649. var pose = this.browserGamepad.pose;
  71650. this.updateFromDevice(pose);
  71651. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71652. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71653. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71654. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71655. if (this._mesh) {
  71656. this._mesh.position.copyFrom(this.devicePosition);
  71657. if (this._mesh.rotationQuaternion) {
  71658. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71659. }
  71660. }
  71661. };
  71662. /**
  71663. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71664. * @param poseData raw pose fromthe device
  71665. */
  71666. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71667. if (poseData) {
  71668. this.rawPose = poseData;
  71669. if (poseData.position) {
  71670. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71671. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71672. this._deviceRoomPosition.z *= -1;
  71673. }
  71674. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71675. this._calculatedPosition.addInPlace(this.position);
  71676. }
  71677. var pose = this.rawPose;
  71678. if (poseData.orientation && pose.orientation) {
  71679. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71680. if (this._mesh) {
  71681. if (this._mesh.getScene().useRightHandedSystem) {
  71682. this._deviceRoomRotationQuaternion.z *= -1;
  71683. this._deviceRoomRotationQuaternion.w *= -1;
  71684. }
  71685. else {
  71686. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71687. }
  71688. }
  71689. // if the camera is set, rotate to the camera's rotation
  71690. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71691. }
  71692. }
  71693. };
  71694. /**
  71695. * Attaches a mesh to the controller
  71696. * @param mesh the mesh to be attached
  71697. */
  71698. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71699. if (this._mesh) {
  71700. this._mesh.parent = null;
  71701. }
  71702. this._mesh = mesh;
  71703. if (this._poseControlledCamera) {
  71704. this._mesh.parent = this._poseControlledCamera;
  71705. }
  71706. if (!this._mesh.rotationQuaternion) {
  71707. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71708. }
  71709. this._meshAttachedObservable.notifyObservers(mesh);
  71710. };
  71711. /**
  71712. * Attaches the controllers mesh to a camera
  71713. * @param camera the camera the mesh should be attached to
  71714. */
  71715. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71716. this._poseControlledCamera = camera;
  71717. if (this._mesh) {
  71718. this._mesh.parent = this._poseControlledCamera;
  71719. }
  71720. };
  71721. /**
  71722. * Disposes of the controller
  71723. */
  71724. PoseEnabledController.prototype.dispose = function () {
  71725. if (this._mesh) {
  71726. this._mesh.dispose();
  71727. }
  71728. this._mesh = null;
  71729. _super.prototype.dispose.call(this);
  71730. };
  71731. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71732. /**
  71733. * The mesh that is attached to the controller
  71734. */
  71735. get: function () {
  71736. return this._mesh;
  71737. },
  71738. enumerable: true,
  71739. configurable: true
  71740. });
  71741. /**
  71742. * Gets the ray of the controller in the direction the controller is pointing
  71743. * @param length the length the resulting ray should be
  71744. * @returns a ray in the direction the controller is pointing
  71745. */
  71746. PoseEnabledController.prototype.getForwardRay = function (length) {
  71747. if (length === void 0) { length = 100; }
  71748. if (!this.mesh) {
  71749. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71750. }
  71751. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71752. var origin = m.getTranslation();
  71753. var forward = new BABYLON.Vector3(0, 0, -1);
  71754. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71755. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71756. return new BABYLON.Ray(origin, direction, length);
  71757. };
  71758. /**
  71759. * Name of the child mesh that can be used to cast a ray from the controller
  71760. */
  71761. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71762. return PoseEnabledController;
  71763. }(BABYLON.Gamepad));
  71764. BABYLON.PoseEnabledController = PoseEnabledController;
  71765. })(BABYLON || (BABYLON = {}));
  71766. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71767. var BABYLON;
  71768. (function (BABYLON) {
  71769. /**
  71770. * Defines the WebVRController object that represents controllers tracked in 3D space
  71771. */
  71772. var WebVRController = /** @class */ (function (_super) {
  71773. __extends(WebVRController, _super);
  71774. /**
  71775. * Creates a new WebVRController from a gamepad
  71776. * @param vrGamepad the gamepad that the WebVRController should be created from
  71777. */
  71778. function WebVRController(vrGamepad) {
  71779. var _this = _super.call(this, vrGamepad) || this;
  71780. // Observables
  71781. /**
  71782. * Fired when the trigger state has changed
  71783. */
  71784. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71785. /**
  71786. * Fired when the main button state has changed
  71787. */
  71788. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71789. /**
  71790. * Fired when the secondary button state has changed
  71791. */
  71792. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71793. /**
  71794. * Fired when the pad state has changed
  71795. */
  71796. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71797. /**
  71798. * Fired when controllers stick values have changed
  71799. */
  71800. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71801. /**
  71802. * X and Y axis corrisponding to the controllers joystick
  71803. */
  71804. _this.pad = { x: 0, y: 0 };
  71805. // avoid GC, store state in a tmp object
  71806. _this._changes = {
  71807. pressChanged: false,
  71808. touchChanged: false,
  71809. valueChanged: false,
  71810. changed: false
  71811. };
  71812. _this._buttons = new Array(vrGamepad.buttons.length);
  71813. _this.hand = vrGamepad.hand;
  71814. return _this;
  71815. }
  71816. /**
  71817. * Fired when a controller button's state has changed
  71818. * @param callback the callback containing the button that was modified
  71819. */
  71820. WebVRController.prototype.onButtonStateChange = function (callback) {
  71821. this._onButtonStateChange = callback;
  71822. };
  71823. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71824. /**
  71825. * The default controller model for the controller
  71826. */
  71827. get: function () {
  71828. return this._defaultModel;
  71829. },
  71830. enumerable: true,
  71831. configurable: true
  71832. });
  71833. /**
  71834. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71835. */
  71836. WebVRController.prototype.update = function () {
  71837. _super.prototype.update.call(this);
  71838. for (var index = 0; index < this._buttons.length; index++) {
  71839. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71840. }
  71841. ;
  71842. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71843. this.pad.x = this.leftStick.x;
  71844. this.pad.y = this.leftStick.y;
  71845. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71846. }
  71847. };
  71848. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71849. if (!newState) {
  71850. newState = {
  71851. pressed: false,
  71852. touched: false,
  71853. value: 0
  71854. };
  71855. }
  71856. if (!currentState) {
  71857. this._buttons[buttonIndex] = {
  71858. pressed: newState.pressed,
  71859. touched: newState.touched,
  71860. value: newState.value
  71861. };
  71862. return;
  71863. }
  71864. this._checkChanges(newState, currentState);
  71865. if (this._changes.changed) {
  71866. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71867. this._handleButtonChange(buttonIndex, newState, this._changes);
  71868. }
  71869. this._buttons[buttonIndex].pressed = newState.pressed;
  71870. this._buttons[buttonIndex].touched = newState.touched;
  71871. // oculus triggers are never 0, thou not touched.
  71872. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71873. };
  71874. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71875. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71876. this._changes.touchChanged = newState.touched !== currentState.touched;
  71877. this._changes.valueChanged = newState.value !== currentState.value;
  71878. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71879. return this._changes;
  71880. };
  71881. /**
  71882. * Disposes of th webVRCOntroller
  71883. */
  71884. WebVRController.prototype.dispose = function () {
  71885. _super.prototype.dispose.call(this);
  71886. this.onTriggerStateChangedObservable.clear();
  71887. this.onMainButtonStateChangedObservable.clear();
  71888. this.onSecondaryButtonStateChangedObservable.clear();
  71889. this.onPadStateChangedObservable.clear();
  71890. this.onPadValuesChangedObservable.clear();
  71891. };
  71892. return WebVRController;
  71893. }(BABYLON.PoseEnabledController));
  71894. BABYLON.WebVRController = WebVRController;
  71895. })(BABYLON || (BABYLON = {}));
  71896. //# sourceMappingURL=babylon.webVRController.js.map
  71897. var BABYLON;
  71898. (function (BABYLON) {
  71899. /**
  71900. * Oculus Touch Controller
  71901. */
  71902. var OculusTouchController = /** @class */ (function (_super) {
  71903. __extends(OculusTouchController, _super);
  71904. /**
  71905. * Creates a new OculusTouchController from a gamepad
  71906. * @param vrGamepad the gamepad that the controller should be created from
  71907. */
  71908. function OculusTouchController(vrGamepad) {
  71909. var _this = _super.call(this, vrGamepad) || this;
  71910. /**
  71911. * Fired when the secondary trigger on this controller is modified
  71912. */
  71913. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71914. /**
  71915. * Fired when the thumb rest on this controller is modified
  71916. */
  71917. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71918. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71919. return _this;
  71920. }
  71921. /**
  71922. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71923. * @param scene scene in which to add meshes
  71924. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71925. */
  71926. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71927. var _this = this;
  71928. var meshName;
  71929. // Hand
  71930. if (this.hand === 'left') {
  71931. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71932. }
  71933. else { // Right is the default if no hand is specified
  71934. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71935. }
  71936. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71937. /*
  71938. Parent Mesh name: oculus_touch_left
  71939. - body
  71940. - trigger
  71941. - thumbstick
  71942. - grip
  71943. - button_y
  71944. - button_x
  71945. - button_enter
  71946. */
  71947. _this._defaultModel = newMeshes[1];
  71948. _this.attachToMesh(_this._defaultModel);
  71949. if (meshLoaded) {
  71950. meshLoaded(_this._defaultModel);
  71951. }
  71952. });
  71953. };
  71954. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71955. /**
  71956. * Fired when the A button on this controller is modified
  71957. */
  71958. get: function () {
  71959. if (this.hand === 'right') {
  71960. return this.onMainButtonStateChangedObservable;
  71961. }
  71962. else {
  71963. throw new Error('No A button on left hand');
  71964. }
  71965. },
  71966. enumerable: true,
  71967. configurable: true
  71968. });
  71969. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71970. /**
  71971. * Fired when the B button on this controller is modified
  71972. */
  71973. get: function () {
  71974. if (this.hand === 'right') {
  71975. return this.onSecondaryButtonStateChangedObservable;
  71976. }
  71977. else {
  71978. throw new Error('No B button on left hand');
  71979. }
  71980. },
  71981. enumerable: true,
  71982. configurable: true
  71983. });
  71984. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71985. /**
  71986. * Fired when the X button on this controller is modified
  71987. */
  71988. get: function () {
  71989. if (this.hand === 'left') {
  71990. return this.onMainButtonStateChangedObservable;
  71991. }
  71992. else {
  71993. throw new Error('No X button on right hand');
  71994. }
  71995. },
  71996. enumerable: true,
  71997. configurable: true
  71998. });
  71999. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72000. /**
  72001. * Fired when the Y button on this controller is modified
  72002. */
  72003. get: function () {
  72004. if (this.hand === 'left') {
  72005. return this.onSecondaryButtonStateChangedObservable;
  72006. }
  72007. else {
  72008. throw new Error('No Y button on right hand');
  72009. }
  72010. },
  72011. enumerable: true,
  72012. configurable: true
  72013. });
  72014. /**
  72015. * Called once for each button that changed state since the last frame
  72016. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72017. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72018. * 2) secondary trigger (same)
  72019. * 3) A (right) X (left), touch, pressed = value
  72020. * 4) B / Y
  72021. * 5) thumb rest
  72022. * @param buttonIdx Which button index changed
  72023. * @param state New state of the button
  72024. * @param changes Which properties on the state changed since last frame
  72025. */
  72026. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72027. var notifyObject = state; //{ state: state, changes: changes };
  72028. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72029. switch (buttonIdx) {
  72030. case 0:
  72031. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72032. return;
  72033. case 1: // index trigger
  72034. if (this._defaultModel) {
  72035. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72036. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72037. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72038. }
  72039. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72040. return;
  72041. case 2: // secondary trigger
  72042. if (this._defaultModel) {
  72043. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72044. }
  72045. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72046. return;
  72047. case 3:
  72048. if (this._defaultModel) {
  72049. if (notifyObject.pressed) {
  72050. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72051. }
  72052. else {
  72053. (this._defaultModel.getChildren()[1]).position.y = 0;
  72054. }
  72055. }
  72056. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72057. return;
  72058. case 4:
  72059. if (this._defaultModel) {
  72060. if (notifyObject.pressed) {
  72061. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72062. }
  72063. else {
  72064. (this._defaultModel.getChildren()[2]).position.y = 0;
  72065. }
  72066. }
  72067. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72068. return;
  72069. case 5:
  72070. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72071. return;
  72072. }
  72073. };
  72074. /**
  72075. * Base Url for the controller model.
  72076. */
  72077. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72078. /**
  72079. * File name for the left controller model.
  72080. */
  72081. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72082. /**
  72083. * File name for the right controller model.
  72084. */
  72085. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72086. return OculusTouchController;
  72087. }(BABYLON.WebVRController));
  72088. BABYLON.OculusTouchController = OculusTouchController;
  72089. })(BABYLON || (BABYLON = {}));
  72090. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72091. var BABYLON;
  72092. (function (BABYLON) {
  72093. /**
  72094. * Vive Controller
  72095. */
  72096. var ViveController = /** @class */ (function (_super) {
  72097. __extends(ViveController, _super);
  72098. /**
  72099. * Creates a new ViveController from a gamepad
  72100. * @param vrGamepad the gamepad that the controller should be created from
  72101. */
  72102. function ViveController(vrGamepad) {
  72103. var _this = _super.call(this, vrGamepad) || this;
  72104. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72105. _this._invertLeftStickY = true;
  72106. return _this;
  72107. }
  72108. /**
  72109. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72110. * @param scene scene in which to add meshes
  72111. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72112. */
  72113. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72114. var _this = this;
  72115. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72116. /*
  72117. Parent Mesh name: ViveWand
  72118. - body
  72119. - r_gripper
  72120. - l_gripper
  72121. - menu_button
  72122. - system_button
  72123. - trackpad
  72124. - trigger
  72125. - LED
  72126. */
  72127. _this._defaultModel = newMeshes[1];
  72128. _this.attachToMesh(_this._defaultModel);
  72129. if (meshLoaded) {
  72130. meshLoaded(_this._defaultModel);
  72131. }
  72132. });
  72133. };
  72134. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72135. /**
  72136. * Fired when the left button on this controller is modified
  72137. */
  72138. get: function () {
  72139. return this.onMainButtonStateChangedObservable;
  72140. },
  72141. enumerable: true,
  72142. configurable: true
  72143. });
  72144. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72145. /**
  72146. * Fired when the right button on this controller is modified
  72147. */
  72148. get: function () {
  72149. return this.onMainButtonStateChangedObservable;
  72150. },
  72151. enumerable: true,
  72152. configurable: true
  72153. });
  72154. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72155. /**
  72156. * Fired when the menu button on this controller is modified
  72157. */
  72158. get: function () {
  72159. return this.onSecondaryButtonStateChangedObservable;
  72160. },
  72161. enumerable: true,
  72162. configurable: true
  72163. });
  72164. /**
  72165. * Called once for each button that changed state since the last frame
  72166. * Vive mapping:
  72167. * 0: touchpad
  72168. * 1: trigger
  72169. * 2: left AND right buttons
  72170. * 3: menu button
  72171. * @param buttonIdx Which button index changed
  72172. * @param state New state of the button
  72173. * @param changes Which properties on the state changed since last frame
  72174. */
  72175. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72176. var notifyObject = state; //{ state: state, changes: changes };
  72177. switch (buttonIdx) {
  72178. case 0:
  72179. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72180. return;
  72181. case 1: // index trigger
  72182. if (this._defaultModel) {
  72183. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72184. }
  72185. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72186. return;
  72187. case 2: // left AND right button
  72188. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72189. return;
  72190. case 3:
  72191. if (this._defaultModel) {
  72192. if (notifyObject.pressed) {
  72193. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72194. }
  72195. else {
  72196. (this._defaultModel.getChildren()[2]).position.y = 0;
  72197. }
  72198. }
  72199. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72200. return;
  72201. }
  72202. };
  72203. /**
  72204. * Base Url for the controller model.
  72205. */
  72206. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72207. /**
  72208. * File name for the controller model.
  72209. */
  72210. ViveController.MODEL_FILENAME = 'wand.babylon';
  72211. return ViveController;
  72212. }(BABYLON.WebVRController));
  72213. BABYLON.ViveController = ViveController;
  72214. })(BABYLON || (BABYLON = {}));
  72215. //# sourceMappingURL=babylon.viveController.js.map
  72216. var BABYLON;
  72217. (function (BABYLON) {
  72218. /**
  72219. * Generic Controller
  72220. */
  72221. var GenericController = /** @class */ (function (_super) {
  72222. __extends(GenericController, _super);
  72223. /**
  72224. * Creates a new GenericController from a gamepad
  72225. * @param vrGamepad the gamepad that the controller should be created from
  72226. */
  72227. function GenericController(vrGamepad) {
  72228. return _super.call(this, vrGamepad) || this;
  72229. }
  72230. /**
  72231. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72232. * @param scene scene in which to add meshes
  72233. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72234. */
  72235. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72236. var _this = this;
  72237. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72238. _this._defaultModel = newMeshes[1];
  72239. _this.attachToMesh(_this._defaultModel);
  72240. if (meshLoaded) {
  72241. meshLoaded(_this._defaultModel);
  72242. }
  72243. });
  72244. };
  72245. /**
  72246. * Called once for each button that changed state since the last frame
  72247. * @param buttonIdx Which button index changed
  72248. * @param state New state of the button
  72249. * @param changes Which properties on the state changed since last frame
  72250. */
  72251. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72252. console.log("Button id: " + buttonIdx + "state: ");
  72253. console.dir(state);
  72254. };
  72255. /**
  72256. * Base Url for the controller model.
  72257. */
  72258. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72259. /**
  72260. * File name for the controller model.
  72261. */
  72262. GenericController.MODEL_FILENAME = 'generic.babylon';
  72263. return GenericController;
  72264. }(BABYLON.WebVRController));
  72265. BABYLON.GenericController = GenericController;
  72266. })(BABYLON || (BABYLON = {}));
  72267. //# sourceMappingURL=babylon.genericController.js.map
  72268. var BABYLON;
  72269. (function (BABYLON) {
  72270. /**
  72271. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72272. */
  72273. var LoadedMeshInfo = /** @class */ (function () {
  72274. function LoadedMeshInfo() {
  72275. /**
  72276. * Map of the button meshes contained in the controller
  72277. */
  72278. this.buttonMeshes = {};
  72279. /**
  72280. * Map of the axis meshes contained in the controller
  72281. */
  72282. this.axisMeshes = {};
  72283. }
  72284. return LoadedMeshInfo;
  72285. }());
  72286. /**
  72287. * Defines the WindowsMotionController object that the state of the windows motion controller
  72288. */
  72289. var WindowsMotionController = /** @class */ (function (_super) {
  72290. __extends(WindowsMotionController, _super);
  72291. /**
  72292. * Creates a new WindowsMotionController from a gamepad
  72293. * @param vrGamepad the gamepad that the controller should be created from
  72294. */
  72295. function WindowsMotionController(vrGamepad) {
  72296. var _this = _super.call(this, vrGamepad) || this;
  72297. _this._mapping = {
  72298. // Semantic button names
  72299. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72300. // A mapping of the button name to glTF model node name
  72301. // that should be transformed by button value.
  72302. buttonMeshNames: {
  72303. 'trigger': 'SELECT',
  72304. 'menu': 'MENU',
  72305. 'grip': 'GRASP',
  72306. 'thumbstick': 'THUMBSTICK_PRESS',
  72307. 'trackpad': 'TOUCHPAD_PRESS'
  72308. },
  72309. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72310. buttonObservableNames: {
  72311. 'trigger': 'onTriggerStateChangedObservable',
  72312. 'menu': 'onSecondaryButtonStateChangedObservable',
  72313. 'grip': 'onMainButtonStateChangedObservable',
  72314. 'thumbstick': 'onPadStateChangedObservable',
  72315. 'trackpad': 'onTrackpadChangedObservable'
  72316. },
  72317. // A mapping of the axis name to glTF model node name
  72318. // that should be transformed by axis value.
  72319. // This array mirrors the browserGamepad.axes array, such that
  72320. // the mesh corresponding to axis 0 is in this array index 0.
  72321. axisMeshNames: [
  72322. 'THUMBSTICK_X',
  72323. 'THUMBSTICK_Y',
  72324. 'TOUCHPAD_TOUCH_X',
  72325. 'TOUCHPAD_TOUCH_Y'
  72326. ],
  72327. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72328. };
  72329. /**
  72330. * Fired when the trackpad on this controller is clicked
  72331. */
  72332. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72333. /**
  72334. * Fired when the trackpad on this controller is modified
  72335. */
  72336. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72337. /**
  72338. * The current x and y values of this controller's trackpad
  72339. */
  72340. _this.trackpad = { x: 0, y: 0 };
  72341. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72342. _this._loadedMeshInfo = null;
  72343. return _this;
  72344. }
  72345. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72346. /**
  72347. * Fired when the trigger on this controller is modified
  72348. */
  72349. get: function () {
  72350. return this.onTriggerStateChangedObservable;
  72351. },
  72352. enumerable: true,
  72353. configurable: true
  72354. });
  72355. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72356. /**
  72357. * Fired when the menu button on this controller is modified
  72358. */
  72359. get: function () {
  72360. return this.onSecondaryButtonStateChangedObservable;
  72361. },
  72362. enumerable: true,
  72363. configurable: true
  72364. });
  72365. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72366. /**
  72367. * Fired when the grip button on this controller is modified
  72368. */
  72369. get: function () {
  72370. return this.onMainButtonStateChangedObservable;
  72371. },
  72372. enumerable: true,
  72373. configurable: true
  72374. });
  72375. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72376. /**
  72377. * Fired when the thumbstick button on this controller is modified
  72378. */
  72379. get: function () {
  72380. return this.onPadStateChangedObservable;
  72381. },
  72382. enumerable: true,
  72383. configurable: true
  72384. });
  72385. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72386. /**
  72387. * Fired when the touchpad button on this controller is modified
  72388. */
  72389. get: function () {
  72390. return this.onTrackpadChangedObservable;
  72391. },
  72392. enumerable: true,
  72393. configurable: true
  72394. });
  72395. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72396. /**
  72397. * Fired when the touchpad values on this controller are modified
  72398. */
  72399. get: function () {
  72400. return this.onTrackpadValuesChangedObservable;
  72401. },
  72402. enumerable: true,
  72403. configurable: true
  72404. });
  72405. /**
  72406. * Called once per frame by the engine.
  72407. */
  72408. WindowsMotionController.prototype.update = function () {
  72409. _super.prototype.update.call(this);
  72410. if (this.browserGamepad.axes) {
  72411. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72412. this.trackpad.x = this.browserGamepad["axes"][2];
  72413. this.trackpad.y = this.browserGamepad["axes"][3];
  72414. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72415. }
  72416. // Only need to animate axes if there is a loaded mesh
  72417. if (this._loadedMeshInfo) {
  72418. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72419. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72420. }
  72421. }
  72422. }
  72423. };
  72424. /**
  72425. * Called once for each button that changed state since the last frame
  72426. * @param buttonIdx Which button index changed
  72427. * @param state New state of the button
  72428. * @param changes Which properties on the state changed since last frame
  72429. */
  72430. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72431. var buttonName = this._mapping.buttons[buttonIdx];
  72432. if (!buttonName) {
  72433. return;
  72434. }
  72435. // Only emit events for buttons that we know how to map from index to name
  72436. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72437. if (observable) {
  72438. observable.notifyObservers(state);
  72439. }
  72440. this._lerpButtonTransform(buttonName, state.value);
  72441. };
  72442. /**
  72443. * Moves the buttons on the controller mesh based on their current state
  72444. * @param buttonName the name of the button to move
  72445. * @param buttonValue the value of the button which determines the buttons new position
  72446. */
  72447. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72448. // If there is no loaded mesh, there is nothing to transform.
  72449. if (!this._loadedMeshInfo) {
  72450. return;
  72451. }
  72452. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72453. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72454. return;
  72455. }
  72456. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72457. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72458. };
  72459. /**
  72460. * Moves the axis on the controller mesh based on its current state
  72461. * @param axis the index of the axis
  72462. * @param axisValue the value of the axis which determines the meshes new position
  72463. * @hidden
  72464. */
  72465. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72466. if (!this._loadedMeshInfo) {
  72467. return;
  72468. }
  72469. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72470. if (!meshInfo) {
  72471. return;
  72472. }
  72473. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72474. return;
  72475. }
  72476. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72477. var lerpValue = axisValue * 0.5 + 0.5;
  72478. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72479. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72480. };
  72481. /**
  72482. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72483. * @param scene scene in which to add meshes
  72484. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72485. */
  72486. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72487. var _this = this;
  72488. if (forceDefault === void 0) { forceDefault = false; }
  72489. var path;
  72490. var filename;
  72491. // Checking if GLB loader is present
  72492. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72493. // Determine the device specific folder based on the ID suffix
  72494. var device = 'default';
  72495. if (this.id && !forceDefault) {
  72496. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72497. device = ((match && match[0]) || device);
  72498. }
  72499. // Hand
  72500. if (this.hand === 'left') {
  72501. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72502. }
  72503. else { // Right is the default if no hand is specified
  72504. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72505. }
  72506. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72507. }
  72508. else {
  72509. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72510. path = BABYLON.GenericController.MODEL_BASE_URL;
  72511. filename = BABYLON.GenericController.MODEL_FILENAME;
  72512. }
  72513. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72514. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72515. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72516. if (!_this._loadedMeshInfo) {
  72517. return;
  72518. }
  72519. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72520. _this.attachToMesh(_this._defaultModel);
  72521. if (meshLoaded) {
  72522. meshLoaded(_this._defaultModel);
  72523. }
  72524. }, null, function (scene, message) {
  72525. BABYLON.Tools.Log(message);
  72526. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72527. if (!forceDefault) {
  72528. _this.initControllerMesh(scene, meshLoaded, true);
  72529. }
  72530. });
  72531. };
  72532. /**
  72533. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72534. * can be transformed by button presses and axes values, based on this._mapping.
  72535. *
  72536. * @param scene scene in which the meshes exist
  72537. * @param meshes list of meshes that make up the controller model to process
  72538. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72539. */
  72540. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72541. var loadedMeshInfo = null;
  72542. // Create a new mesh to contain the glTF hierarchy
  72543. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72544. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72545. var childMesh = null;
  72546. for (var i = 0; i < meshes.length; i++) {
  72547. var mesh = meshes[i];
  72548. if (!mesh.parent) {
  72549. // Exclude controller meshes from picking results
  72550. mesh.isPickable = false;
  72551. // Handle root node, attach to the new parentMesh
  72552. childMesh = mesh;
  72553. break;
  72554. }
  72555. }
  72556. if (childMesh) {
  72557. childMesh.setParent(parentMesh);
  72558. // Create our mesh info. Note that this method will always return non-null.
  72559. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72560. }
  72561. else {
  72562. BABYLON.Tools.Warn('Could not find root node in model file.');
  72563. }
  72564. return loadedMeshInfo;
  72565. };
  72566. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72567. var loadedMeshInfo = new LoadedMeshInfo();
  72568. var i;
  72569. loadedMeshInfo.rootNode = rootNode;
  72570. // Reset the caches
  72571. loadedMeshInfo.buttonMeshes = {};
  72572. loadedMeshInfo.axisMeshes = {};
  72573. // Button Meshes
  72574. for (i = 0; i < this._mapping.buttons.length; i++) {
  72575. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72576. if (!buttonMeshName) {
  72577. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72578. continue;
  72579. }
  72580. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72581. if (!buttonMesh) {
  72582. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72583. continue;
  72584. }
  72585. var buttonMeshInfo = {
  72586. index: i,
  72587. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72588. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72589. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72590. };
  72591. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72592. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72593. }
  72594. else {
  72595. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72596. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72597. '(VALUE: ' + !!buttonMeshInfo.value +
  72598. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72599. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72600. ')');
  72601. }
  72602. }
  72603. // Axis Meshes
  72604. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72605. var axisMeshName = this._mapping.axisMeshNames[i];
  72606. if (!axisMeshName) {
  72607. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72608. continue;
  72609. }
  72610. var axisMesh = getChildByName(rootNode, axisMeshName);
  72611. if (!axisMesh) {
  72612. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72613. continue;
  72614. }
  72615. var axisMeshInfo = {
  72616. index: i,
  72617. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72618. min: getImmediateChildByName(axisMesh, 'MIN'),
  72619. max: getImmediateChildByName(axisMesh, 'MAX')
  72620. };
  72621. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72622. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72623. }
  72624. else {
  72625. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72626. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72627. '(VALUE: ' + !!axisMeshInfo.value +
  72628. ', MIN: ' + !!axisMeshInfo.min +
  72629. ', MAX:' + !!axisMeshInfo.max +
  72630. ')');
  72631. }
  72632. }
  72633. // Pointing Ray
  72634. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72635. if (!loadedMeshInfo.pointingPoseNode) {
  72636. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72637. }
  72638. return loadedMeshInfo;
  72639. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72640. function getChildByName(node, name) {
  72641. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72642. }
  72643. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72644. function getImmediateChildByName(node, name) {
  72645. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72646. }
  72647. };
  72648. /**
  72649. * Gets the ray of the controller in the direction the controller is pointing
  72650. * @param length the length the resulting ray should be
  72651. * @returns a ray in the direction the controller is pointing
  72652. */
  72653. WindowsMotionController.prototype.getForwardRay = function (length) {
  72654. if (length === void 0) { length = 100; }
  72655. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72656. return _super.prototype.getForwardRay.call(this, length);
  72657. }
  72658. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72659. var origin = m.getTranslation();
  72660. var forward = new BABYLON.Vector3(0, 0, -1);
  72661. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72662. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72663. return new BABYLON.Ray(origin, direction, length);
  72664. };
  72665. /**
  72666. * Disposes of the controller
  72667. */
  72668. WindowsMotionController.prototype.dispose = function () {
  72669. _super.prototype.dispose.call(this);
  72670. this.onTrackpadChangedObservable.clear();
  72671. };
  72672. /**
  72673. * The base url used to load the left and right controller models
  72674. */
  72675. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72676. /**
  72677. * The name of the left controller model file
  72678. */
  72679. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72680. /**
  72681. * The name of the right controller model file
  72682. */
  72683. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72684. /**
  72685. * The controller name prefix for this controller type
  72686. */
  72687. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72688. /**
  72689. * The controller id pattern for this controller type
  72690. */
  72691. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72692. return WindowsMotionController;
  72693. }(BABYLON.WebVRController));
  72694. BABYLON.WindowsMotionController = WindowsMotionController;
  72695. })(BABYLON || (BABYLON = {}));
  72696. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72697. var BABYLON;
  72698. (function (BABYLON) {
  72699. /**
  72700. * Gear VR Controller
  72701. */
  72702. var GearVRController = /** @class */ (function (_super) {
  72703. __extends(GearVRController, _super);
  72704. /**
  72705. * Creates a new GearVRController from a gamepad
  72706. * @param vrGamepad the gamepad that the controller should be created from
  72707. */
  72708. function GearVRController(vrGamepad) {
  72709. var _this = _super.call(this, vrGamepad) || this;
  72710. _this._buttonIndexToObservableNameMap = [
  72711. 'onTrackpadChangedObservable',
  72712. 'onTriggerStateChangedObservable' // Trigger
  72713. ];
  72714. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72715. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72716. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72717. return _this;
  72718. }
  72719. /**
  72720. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72721. * @param scene scene in which to add meshes
  72722. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72723. */
  72724. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72725. var _this = this;
  72726. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72727. _this._defaultModel = newMeshes[1];
  72728. _this.attachToMesh(_this._defaultModel);
  72729. if (meshLoaded) {
  72730. meshLoaded(_this._defaultModel);
  72731. }
  72732. });
  72733. };
  72734. /**
  72735. * Called once for each button that changed state since the last frame
  72736. * @param buttonIdx Which button index changed
  72737. * @param state New state of the button
  72738. * @param changes Which properties on the state changed since last frame
  72739. */
  72740. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72741. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72742. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72743. // Only emit events for buttons that we know how to map from index to observable
  72744. var observable = this[observableName];
  72745. if (observable) {
  72746. observable.notifyObservers(state);
  72747. }
  72748. }
  72749. };
  72750. /**
  72751. * Base Url for the controller model.
  72752. */
  72753. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72754. /**
  72755. * File name for the controller model.
  72756. */
  72757. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72758. /**
  72759. * Gamepad Id prefix used to identify this controller.
  72760. */
  72761. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72762. return GearVRController;
  72763. }(BABYLON.WebVRController));
  72764. BABYLON.GearVRController = GearVRController;
  72765. })(BABYLON || (BABYLON = {}));
  72766. //# sourceMappingURL=babylon.gearVRController.js.map
  72767. var BABYLON;
  72768. (function (BABYLON) {
  72769. /**
  72770. * Google Daydream controller
  72771. */
  72772. var DaydreamController = /** @class */ (function (_super) {
  72773. __extends(DaydreamController, _super);
  72774. /**
  72775. * Creates a new DaydreamController from a gamepad
  72776. * @param vrGamepad the gamepad that the controller should be created from
  72777. */
  72778. function DaydreamController(vrGamepad) {
  72779. var _this = _super.call(this, vrGamepad) || this;
  72780. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72781. return _this;
  72782. }
  72783. /**
  72784. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72785. * @param scene scene in which to add meshes
  72786. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72787. */
  72788. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72789. var _this = this;
  72790. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72791. _this._defaultModel = newMeshes[1];
  72792. _this.attachToMesh(_this._defaultModel);
  72793. if (meshLoaded) {
  72794. meshLoaded(_this._defaultModel);
  72795. }
  72796. });
  72797. };
  72798. /**
  72799. * Called once for each button that changed state since the last frame
  72800. * @param buttonIdx Which button index changed
  72801. * @param state New state of the button
  72802. * @param changes Which properties on the state changed since last frame
  72803. */
  72804. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72805. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72806. if (buttonIdx === 0) {
  72807. var observable = this.onTriggerStateChangedObservable;
  72808. if (observable) {
  72809. observable.notifyObservers(state);
  72810. }
  72811. }
  72812. else {
  72813. // If the app or home buttons are ever made available
  72814. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72815. }
  72816. };
  72817. /**
  72818. * Base Url for the controller model.
  72819. */
  72820. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72821. /**
  72822. * File name for the controller model.
  72823. */
  72824. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72825. /**
  72826. * Gamepad Id prefix used to identify Daydream Controller.
  72827. */
  72828. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72829. return DaydreamController;
  72830. }(BABYLON.WebVRController));
  72831. BABYLON.DaydreamController = DaydreamController;
  72832. })(BABYLON || (BABYLON = {}));
  72833. //# sourceMappingURL=babylon.daydreamController.js.map
  72834. var BABYLON;
  72835. (function (BABYLON) {
  72836. var FollowCamera = /** @class */ (function (_super) {
  72837. __extends(FollowCamera, _super);
  72838. function FollowCamera(name, position, scene, lockedTarget) {
  72839. if (lockedTarget === void 0) { lockedTarget = null; }
  72840. var _this = _super.call(this, name, position, scene) || this;
  72841. _this.radius = 12;
  72842. _this.rotationOffset = 0;
  72843. _this.heightOffset = 4;
  72844. _this.cameraAcceleration = 0.05;
  72845. _this.maxCameraSpeed = 20;
  72846. _this.lockedTarget = lockedTarget;
  72847. return _this;
  72848. }
  72849. FollowCamera.prototype.getRadians = function (degrees) {
  72850. return degrees * Math.PI / 180;
  72851. };
  72852. FollowCamera.prototype.follow = function (cameraTarget) {
  72853. if (!cameraTarget)
  72854. return;
  72855. var yRotation;
  72856. if (cameraTarget.rotationQuaternion) {
  72857. var rotMatrix = new BABYLON.Matrix();
  72858. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72859. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72860. }
  72861. else {
  72862. yRotation = cameraTarget.rotation.y;
  72863. }
  72864. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72865. var targetPosition = cameraTarget.getAbsolutePosition();
  72866. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72867. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72868. var dx = targetX - this.position.x;
  72869. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72870. var dz = (targetZ) - this.position.z;
  72871. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72872. var vy = dy * this.cameraAcceleration;
  72873. var vz = dz * this.cameraAcceleration * 2;
  72874. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72875. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72876. }
  72877. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72878. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72879. }
  72880. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72881. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72882. }
  72883. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72884. this.setTarget(targetPosition);
  72885. };
  72886. FollowCamera.prototype._checkInputs = function () {
  72887. _super.prototype._checkInputs.call(this);
  72888. if (this.lockedTarget) {
  72889. this.follow(this.lockedTarget);
  72890. }
  72891. };
  72892. FollowCamera.prototype.getClassName = function () {
  72893. return "FollowCamera";
  72894. };
  72895. __decorate([
  72896. BABYLON.serialize()
  72897. ], FollowCamera.prototype, "radius", void 0);
  72898. __decorate([
  72899. BABYLON.serialize()
  72900. ], FollowCamera.prototype, "rotationOffset", void 0);
  72901. __decorate([
  72902. BABYLON.serialize()
  72903. ], FollowCamera.prototype, "heightOffset", void 0);
  72904. __decorate([
  72905. BABYLON.serialize()
  72906. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72907. __decorate([
  72908. BABYLON.serialize()
  72909. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72910. __decorate([
  72911. BABYLON.serializeAsMeshReference("lockedTargetId")
  72912. ], FollowCamera.prototype, "lockedTarget", void 0);
  72913. return FollowCamera;
  72914. }(BABYLON.TargetCamera));
  72915. BABYLON.FollowCamera = FollowCamera;
  72916. var ArcFollowCamera = /** @class */ (function (_super) {
  72917. __extends(ArcFollowCamera, _super);
  72918. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72919. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72920. _this.alpha = alpha;
  72921. _this.beta = beta;
  72922. _this.radius = radius;
  72923. _this.target = target;
  72924. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72925. _this.follow();
  72926. return _this;
  72927. }
  72928. ArcFollowCamera.prototype.follow = function () {
  72929. if (!this.target) {
  72930. return;
  72931. }
  72932. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72933. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72934. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72935. var targetPosition = this.target.getAbsolutePosition();
  72936. this.position = targetPosition.add(this._cartesianCoordinates);
  72937. this.setTarget(targetPosition);
  72938. };
  72939. ArcFollowCamera.prototype._checkInputs = function () {
  72940. _super.prototype._checkInputs.call(this);
  72941. this.follow();
  72942. };
  72943. ArcFollowCamera.prototype.getClassName = function () {
  72944. return "ArcFollowCamera";
  72945. };
  72946. return ArcFollowCamera;
  72947. }(BABYLON.TargetCamera));
  72948. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72949. })(BABYLON || (BABYLON = {}));
  72950. //# sourceMappingURL=babylon.followCamera.js.map
  72951. var BABYLON;
  72952. (function (BABYLON) {
  72953. // We're mainly based on the logic defined into the FreeCamera code
  72954. var UniversalCamera = /** @class */ (function (_super) {
  72955. __extends(UniversalCamera, _super);
  72956. //-- end properties for backward compatibility for inputs
  72957. function UniversalCamera(name, position, scene) {
  72958. var _this = _super.call(this, name, position, scene) || this;
  72959. _this.inputs.addGamepad();
  72960. return _this;
  72961. }
  72962. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72963. //-- Begin properties for backward compatibility for inputs
  72964. get: function () {
  72965. var gamepad = this.inputs.attached["gamepad"];
  72966. if (gamepad)
  72967. return gamepad.gamepadAngularSensibility;
  72968. return 0;
  72969. },
  72970. set: function (value) {
  72971. var gamepad = this.inputs.attached["gamepad"];
  72972. if (gamepad)
  72973. gamepad.gamepadAngularSensibility = value;
  72974. },
  72975. enumerable: true,
  72976. configurable: true
  72977. });
  72978. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72979. get: function () {
  72980. var gamepad = this.inputs.attached["gamepad"];
  72981. if (gamepad)
  72982. return gamepad.gamepadMoveSensibility;
  72983. return 0;
  72984. },
  72985. set: function (value) {
  72986. var gamepad = this.inputs.attached["gamepad"];
  72987. if (gamepad)
  72988. gamepad.gamepadMoveSensibility = value;
  72989. },
  72990. enumerable: true,
  72991. configurable: true
  72992. });
  72993. UniversalCamera.prototype.getClassName = function () {
  72994. return "UniversalCamera";
  72995. };
  72996. return UniversalCamera;
  72997. }(BABYLON.TouchCamera));
  72998. BABYLON.UniversalCamera = UniversalCamera;
  72999. })(BABYLON || (BABYLON = {}));
  73000. //# sourceMappingURL=babylon.universalCamera.js.map
  73001. var BABYLON;
  73002. (function (BABYLON) {
  73003. // We're mainly based on the logic defined into the FreeCamera code
  73004. var GamepadCamera = /** @class */ (function (_super) {
  73005. __extends(GamepadCamera, _super);
  73006. //-- end properties for backward compatibility for inputs
  73007. function GamepadCamera(name, position, scene) {
  73008. return _super.call(this, name, position, scene) || this;
  73009. }
  73010. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73011. //-- Begin properties for backward compatibility for inputs
  73012. get: function () {
  73013. var gamepad = this.inputs.attached["gamepad"];
  73014. if (gamepad)
  73015. return gamepad.gamepadAngularSensibility;
  73016. return 0;
  73017. },
  73018. set: function (value) {
  73019. var gamepad = this.inputs.attached["gamepad"];
  73020. if (gamepad)
  73021. gamepad.gamepadAngularSensibility = value;
  73022. },
  73023. enumerable: true,
  73024. configurable: true
  73025. });
  73026. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73027. get: function () {
  73028. var gamepad = this.inputs.attached["gamepad"];
  73029. if (gamepad)
  73030. return gamepad.gamepadMoveSensibility;
  73031. return 0;
  73032. },
  73033. set: function (value) {
  73034. var gamepad = this.inputs.attached["gamepad"];
  73035. if (gamepad)
  73036. gamepad.gamepadMoveSensibility = value;
  73037. },
  73038. enumerable: true,
  73039. configurable: true
  73040. });
  73041. GamepadCamera.prototype.getClassName = function () {
  73042. return "GamepadCamera";
  73043. };
  73044. return GamepadCamera;
  73045. }(BABYLON.UniversalCamera));
  73046. BABYLON.GamepadCamera = GamepadCamera;
  73047. })(BABYLON || (BABYLON = {}));
  73048. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73049. var BABYLON;
  73050. (function (BABYLON) {
  73051. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73052. function PostProcessRenderPipelineManager() {
  73053. this._renderPipelines = {};
  73054. }
  73055. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73056. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73057. };
  73058. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73059. if (unique === void 0) { unique = false; }
  73060. var renderPipeline = this._renderPipelines[renderPipelineName];
  73061. if (!renderPipeline) {
  73062. return;
  73063. }
  73064. renderPipeline._attachCameras(cameras, unique);
  73065. };
  73066. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73067. var renderPipeline = this._renderPipelines[renderPipelineName];
  73068. if (!renderPipeline) {
  73069. return;
  73070. }
  73071. renderPipeline._detachCameras(cameras);
  73072. };
  73073. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73074. var renderPipeline = this._renderPipelines[renderPipelineName];
  73075. if (!renderPipeline) {
  73076. return;
  73077. }
  73078. renderPipeline._enableEffect(renderEffectName, cameras);
  73079. };
  73080. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73081. var renderPipeline = this._renderPipelines[renderPipelineName];
  73082. if (!renderPipeline) {
  73083. return;
  73084. }
  73085. renderPipeline._disableEffect(renderEffectName, cameras);
  73086. };
  73087. PostProcessRenderPipelineManager.prototype.update = function () {
  73088. for (var renderPipelineName in this._renderPipelines) {
  73089. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73090. var pipeline = this._renderPipelines[renderPipelineName];
  73091. if (!pipeline.isSupported) {
  73092. pipeline.dispose();
  73093. delete this._renderPipelines[renderPipelineName];
  73094. }
  73095. else {
  73096. pipeline._update();
  73097. }
  73098. }
  73099. }
  73100. };
  73101. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73102. for (var renderPipelineName in this._renderPipelines) {
  73103. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73104. var pipeline = this._renderPipelines[renderPipelineName];
  73105. pipeline._rebuild();
  73106. }
  73107. }
  73108. };
  73109. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73110. for (var renderPipelineName in this._renderPipelines) {
  73111. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73112. var pipeline = this._renderPipelines[renderPipelineName];
  73113. pipeline.dispose();
  73114. }
  73115. }
  73116. };
  73117. return PostProcessRenderPipelineManager;
  73118. }());
  73119. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73120. })(BABYLON || (BABYLON = {}));
  73121. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73122. var BABYLON;
  73123. (function (BABYLON) {
  73124. /**
  73125. * This represents a set of one or more post processes in Babylon.
  73126. * A post process can be used to apply a shader to a texture after it is rendered.
  73127. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73128. */
  73129. var PostProcessRenderEffect = /** @class */ (function () {
  73130. /**
  73131. * Instantiates a post process render effect.
  73132. * A post process can be used to apply a shader to a texture after it is rendered.
  73133. * @param engine The engine the effect is tied to
  73134. * @param name The name of the effect
  73135. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73136. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73137. */
  73138. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73139. this._name = name;
  73140. this._singleInstance = singleInstance || true;
  73141. this._getPostProcesses = getPostProcesses;
  73142. this._cameras = {};
  73143. this._indicesForCamera = {};
  73144. this._postProcesses = {};
  73145. }
  73146. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73147. /**
  73148. * Checks if all the post processes in the effect are supported.
  73149. */
  73150. get: function () {
  73151. for (var index in this._postProcesses) {
  73152. if (this._postProcesses.hasOwnProperty(index)) {
  73153. var pps = this._postProcesses[index];
  73154. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73155. if (!pps[ppIndex].isSupported) {
  73156. return false;
  73157. }
  73158. }
  73159. }
  73160. }
  73161. return true;
  73162. },
  73163. enumerable: true,
  73164. configurable: true
  73165. });
  73166. /**
  73167. * Updates the current state of the effect
  73168. */
  73169. PostProcessRenderEffect.prototype._update = function () {
  73170. };
  73171. /**
  73172. * Attaches the effect on cameras
  73173. * @param cameras The camera to attach to.
  73174. */
  73175. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73176. var _this = this;
  73177. var cameraKey;
  73178. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73179. if (!cams) {
  73180. return;
  73181. }
  73182. for (var i = 0; i < cams.length; i++) {
  73183. var camera = cams[i];
  73184. var cameraName = camera.name;
  73185. if (this._singleInstance) {
  73186. cameraKey = 0;
  73187. }
  73188. else {
  73189. cameraKey = cameraName;
  73190. }
  73191. if (!this._postProcesses[cameraKey]) {
  73192. var postProcess = this._getPostProcesses();
  73193. if (postProcess) {
  73194. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73195. }
  73196. }
  73197. if (!this._indicesForCamera[cameraName]) {
  73198. this._indicesForCamera[cameraName] = [];
  73199. }
  73200. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73201. var index = camera.attachPostProcess(postProcess);
  73202. _this._indicesForCamera[cameraName].push(index);
  73203. });
  73204. if (!this._cameras[cameraName]) {
  73205. this._cameras[cameraName] = camera;
  73206. }
  73207. }
  73208. };
  73209. /**
  73210. * Detatches the effect on cameras
  73211. * @param cameras The camera to detatch from.
  73212. */
  73213. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73214. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73215. if (!cams) {
  73216. return;
  73217. }
  73218. for (var i = 0; i < cams.length; i++) {
  73219. var camera = cams[i];
  73220. var cameraName = camera.name;
  73221. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73222. camera.detachPostProcess(postProcess);
  73223. });
  73224. if (this._cameras[cameraName]) {
  73225. //this._indicesForCamera.splice(index, 1);
  73226. this._cameras[cameraName] = null;
  73227. }
  73228. }
  73229. };
  73230. /**
  73231. * Enables the effect on given cameras
  73232. * @param cameras The camera to enable.
  73233. */
  73234. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73235. var _this = this;
  73236. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73237. if (!cams) {
  73238. return;
  73239. }
  73240. for (var i = 0; i < cams.length; i++) {
  73241. var camera = cams[i];
  73242. var cameraName = camera.name;
  73243. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73244. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73245. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73246. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73247. });
  73248. }
  73249. }
  73250. }
  73251. };
  73252. /**
  73253. * Disables the effect on the given cameras
  73254. * @param cameras The camera to disable.
  73255. */
  73256. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73257. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73258. if (!cams) {
  73259. return;
  73260. }
  73261. for (var i = 0; i < cams.length; i++) {
  73262. var camera = cams[i];
  73263. var cameraName = camera.name;
  73264. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73265. camera.detachPostProcess(postProcess);
  73266. });
  73267. }
  73268. };
  73269. /**
  73270. * Gets a list of the post processes contained in the effect.
  73271. * @param camera The camera to get the post processes on.
  73272. * @returns The list of the post processes in the effect.
  73273. */
  73274. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73275. if (this._singleInstance) {
  73276. return this._postProcesses[0];
  73277. }
  73278. else {
  73279. if (!camera) {
  73280. return null;
  73281. }
  73282. return this._postProcesses[camera.name];
  73283. }
  73284. };
  73285. return PostProcessRenderEffect;
  73286. }());
  73287. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73288. })(BABYLON || (BABYLON = {}));
  73289. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73290. var BABYLON;
  73291. (function (BABYLON) {
  73292. var PostProcessRenderPipeline = /** @class */ (function () {
  73293. function PostProcessRenderPipeline(engine, name) {
  73294. this.engine = engine;
  73295. this._name = name;
  73296. this._renderEffects = {};
  73297. this._renderEffectsForIsolatedPass = new Array();
  73298. this._cameras = [];
  73299. }
  73300. PostProcessRenderPipeline.prototype.getClassName = function () {
  73301. return "PostProcessRenderPipeline";
  73302. };
  73303. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73304. get: function () {
  73305. for (var renderEffectName in this._renderEffects) {
  73306. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73307. if (!this._renderEffects[renderEffectName].isSupported) {
  73308. return false;
  73309. }
  73310. }
  73311. }
  73312. return true;
  73313. },
  73314. enumerable: true,
  73315. configurable: true
  73316. });
  73317. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73318. this._renderEffects[renderEffect._name] = renderEffect;
  73319. };
  73320. // private
  73321. PostProcessRenderPipeline.prototype._rebuild = function () {
  73322. };
  73323. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73324. var renderEffects = this._renderEffects[renderEffectName];
  73325. if (!renderEffects) {
  73326. return;
  73327. }
  73328. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73329. };
  73330. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73331. var renderEffects = this._renderEffects[renderEffectName];
  73332. if (!renderEffects) {
  73333. return;
  73334. }
  73335. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73336. };
  73337. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73338. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73339. if (!cams) {
  73340. return;
  73341. }
  73342. var indicesToDelete = [];
  73343. var i;
  73344. for (i = 0; i < cams.length; i++) {
  73345. var camera = cams[i];
  73346. var cameraName = camera.name;
  73347. if (this._cameras.indexOf(camera) === -1) {
  73348. this._cameras[cameraName] = camera;
  73349. }
  73350. else if (unique) {
  73351. indicesToDelete.push(i);
  73352. }
  73353. }
  73354. for (i = 0; i < indicesToDelete.length; i++) {
  73355. cameras.splice(indicesToDelete[i], 1);
  73356. }
  73357. for (var renderEffectName in this._renderEffects) {
  73358. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73359. this._renderEffects[renderEffectName]._attachCameras(cams);
  73360. }
  73361. }
  73362. };
  73363. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73364. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73365. if (!cams) {
  73366. return;
  73367. }
  73368. for (var renderEffectName in this._renderEffects) {
  73369. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73370. this._renderEffects[renderEffectName]._detachCameras(cams);
  73371. }
  73372. }
  73373. for (var i = 0; i < cams.length; i++) {
  73374. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73375. }
  73376. };
  73377. PostProcessRenderPipeline.prototype._update = function () {
  73378. for (var renderEffectName in this._renderEffects) {
  73379. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73380. this._renderEffects[renderEffectName]._update();
  73381. }
  73382. }
  73383. for (var i = 0; i < this._cameras.length; i++) {
  73384. var cameraName = this._cameras[i].name;
  73385. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73386. this._renderEffectsForIsolatedPass[cameraName]._update();
  73387. }
  73388. }
  73389. };
  73390. PostProcessRenderPipeline.prototype._reset = function () {
  73391. this._renderEffects = {};
  73392. this._renderEffectsForIsolatedPass = new Array();
  73393. };
  73394. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73395. // 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)
  73396. var effectKeys = Object.keys(this._renderEffects);
  73397. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73398. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73399. if (postProcesses) {
  73400. postProcesses[0].samples = sampleCount;
  73401. return true;
  73402. }
  73403. }
  73404. return false;
  73405. };
  73406. PostProcessRenderPipeline.prototype.dispose = function () {
  73407. // Must be implemented by children
  73408. };
  73409. __decorate([
  73410. BABYLON.serialize()
  73411. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73412. return PostProcessRenderPipeline;
  73413. }());
  73414. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73415. })(BABYLON || (BABYLON = {}));
  73416. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73417. var BABYLON;
  73418. (function (BABYLON) {
  73419. /**
  73420. * This represents a depth renderer in Babylon.
  73421. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73422. */
  73423. var DepthRenderer = /** @class */ (function () {
  73424. /**
  73425. * Instantiates a depth renderer
  73426. * @param scene The scene the renderer belongs to
  73427. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73428. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73429. */
  73430. function DepthRenderer(scene, type, camera) {
  73431. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73432. if (camera === void 0) { camera = null; }
  73433. var _this = this;
  73434. this._scene = scene;
  73435. this._camera = camera;
  73436. var engine = scene.getEngine();
  73437. // Render target
  73438. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73439. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73440. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73441. this._depthMap.refreshRate = 1;
  73442. this._depthMap.renderParticles = false;
  73443. this._depthMap.renderList = null;
  73444. // Camera to get depth map from to support multiple concurrent cameras
  73445. this._depthMap.activeCamera = this._camera;
  73446. this._depthMap.ignoreCameraViewport = true;
  73447. this._depthMap.useCameraPostProcesses = false;
  73448. // set default depth value to 1.0 (far away)
  73449. this._depthMap.onClearObservable.add(function (engine) {
  73450. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73451. });
  73452. // Custom render function
  73453. var renderSubMesh = function (subMesh) {
  73454. var mesh = subMesh.getRenderingMesh();
  73455. var scene = _this._scene;
  73456. var engine = scene.getEngine();
  73457. var material = subMesh.getMaterial();
  73458. if (!material) {
  73459. return;
  73460. }
  73461. // Culling and reverse (right handed system)
  73462. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73463. // Managing instances
  73464. var batch = mesh._getInstancesRenderList(subMesh._id);
  73465. if (batch.mustReturn) {
  73466. return;
  73467. }
  73468. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73469. var camera = _this._camera || scene.activeCamera;
  73470. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73471. engine.enableEffect(_this._effect);
  73472. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73473. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73474. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73475. // Alpha test
  73476. if (material && material.needAlphaTesting()) {
  73477. var alphaTexture = material.getAlphaTestTexture();
  73478. if (alphaTexture) {
  73479. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73480. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73481. }
  73482. }
  73483. // Bones
  73484. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73485. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73486. }
  73487. // Draw
  73488. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73489. }
  73490. };
  73491. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73492. var index;
  73493. if (depthOnlySubMeshes.length) {
  73494. engine.setColorWrite(false);
  73495. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73496. renderSubMesh(depthOnlySubMeshes.data[index]);
  73497. }
  73498. engine.setColorWrite(true);
  73499. }
  73500. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73501. renderSubMesh(opaqueSubMeshes.data[index]);
  73502. }
  73503. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73504. renderSubMesh(alphaTestSubMeshes.data[index]);
  73505. }
  73506. };
  73507. }
  73508. /**
  73509. * Creates the depth rendering effect and checks if the effect is ready.
  73510. * @param subMesh The submesh to be used to render the depth map of
  73511. * @param useInstances If multiple world instances should be used
  73512. * @returns if the depth renderer is ready to render the depth map
  73513. */
  73514. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73515. var material = subMesh.getMaterial();
  73516. if (material.disableDepthWrite) {
  73517. return false;
  73518. }
  73519. var defines = [];
  73520. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73521. var mesh = subMesh.getMesh();
  73522. // Alpha test
  73523. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73524. defines.push("#define ALPHATEST");
  73525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73526. attribs.push(BABYLON.VertexBuffer.UVKind);
  73527. defines.push("#define UV1");
  73528. }
  73529. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73530. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73531. defines.push("#define UV2");
  73532. }
  73533. }
  73534. // Bones
  73535. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73538. if (mesh.numBoneInfluencers > 4) {
  73539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73541. }
  73542. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73543. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73544. }
  73545. else {
  73546. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73547. }
  73548. // Instances
  73549. if (useInstances) {
  73550. defines.push("#define INSTANCES");
  73551. attribs.push("world0");
  73552. attribs.push("world1");
  73553. attribs.push("world2");
  73554. attribs.push("world3");
  73555. }
  73556. // Get correct effect
  73557. var join = defines.join("\n");
  73558. if (this._cachedDefines !== join) {
  73559. this._cachedDefines = join;
  73560. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73561. }
  73562. return this._effect.isReady();
  73563. };
  73564. /**
  73565. * Gets the texture which the depth map will be written to.
  73566. * @returns The depth map texture
  73567. */
  73568. DepthRenderer.prototype.getDepthMap = function () {
  73569. return this._depthMap;
  73570. };
  73571. /**
  73572. * Disposes of the depth renderer.
  73573. */
  73574. DepthRenderer.prototype.dispose = function () {
  73575. this._depthMap.dispose();
  73576. };
  73577. return DepthRenderer;
  73578. }());
  73579. BABYLON.DepthRenderer = DepthRenderer;
  73580. })(BABYLON || (BABYLON = {}));
  73581. //# sourceMappingURL=babylon.depthRenderer.js.map
  73582. var BABYLON;
  73583. (function (BABYLON) {
  73584. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73585. __extends(SSAORenderingPipeline, _super);
  73586. /**
  73587. * @constructor
  73588. * @param {string} name - The rendering pipeline name
  73589. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73590. * @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 }
  73591. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73592. */
  73593. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73594. var _this = _super.call(this, scene.getEngine(), name) || this;
  73595. // Members
  73596. /**
  73597. * The PassPostProcess id in the pipeline that contains the original scene color
  73598. */
  73599. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73600. /**
  73601. * The SSAO PostProcess id in the pipeline
  73602. */
  73603. _this.SSAORenderEffect = "SSAORenderEffect";
  73604. /**
  73605. * The horizontal blur PostProcess id in the pipeline
  73606. */
  73607. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73608. /**
  73609. * The vertical blur PostProcess id in the pipeline
  73610. */
  73611. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73612. /**
  73613. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73614. */
  73615. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73616. /**
  73617. * The output strength of the SSAO post-process. Default value is 1.0.
  73618. */
  73619. _this.totalStrength = 1.0;
  73620. /**
  73621. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73622. */
  73623. _this.radius = 0.0001;
  73624. /**
  73625. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73626. * Must not be equal to fallOff and superior to fallOff.
  73627. * Default value is 0.975
  73628. */
  73629. _this.area = 0.0075;
  73630. /**
  73631. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73632. * Must not be equal to area and inferior to area.
  73633. * Default value is 0.0
  73634. */
  73635. _this.fallOff = 0.000001;
  73636. /**
  73637. * The base color of the SSAO post-process
  73638. * The final result is "base + ssao" between [0, 1]
  73639. */
  73640. _this.base = 0.5;
  73641. _this._firstUpdate = true;
  73642. _this._scene = scene;
  73643. // Set up assets
  73644. _this._createRandomTexture();
  73645. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73646. var ssaoRatio = ratio.ssaoRatio || ratio;
  73647. var combineRatio = ratio.combineRatio || ratio;
  73648. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73649. _this._createSSAOPostProcess(ssaoRatio);
  73650. _this._createBlurPostProcess(ssaoRatio);
  73651. _this._createSSAOCombinePostProcess(combineRatio);
  73652. // Set up pipeline
  73653. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73654. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73655. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73656. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73657. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73658. // Finish
  73659. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73660. if (cameras)
  73661. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73662. return _this;
  73663. }
  73664. // Public Methods
  73665. /**
  73666. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73667. */
  73668. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73669. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73670. for (var i = 0; i < this._scene.cameras.length; i++) {
  73671. var camera = this._scene.cameras[i];
  73672. this._originalColorPostProcess.dispose(camera);
  73673. this._ssaoPostProcess.dispose(camera);
  73674. this._blurHPostProcess.dispose(camera);
  73675. this._blurVPostProcess.dispose(camera);
  73676. this._ssaoCombinePostProcess.dispose(camera);
  73677. }
  73678. this._randomTexture.dispose();
  73679. if (disableDepthRender)
  73680. this._scene.disableDepthRenderer();
  73681. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73682. _super.prototype.dispose.call(this);
  73683. };
  73684. // Private Methods
  73685. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73686. var _this = this;
  73687. var size = 16;
  73688. 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);
  73689. 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);
  73690. this._blurHPostProcess.onActivateObservable.add(function () {
  73691. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73692. _this._blurHPostProcess.kernel = size * dw;
  73693. });
  73694. this._blurVPostProcess.onActivateObservable.add(function () {
  73695. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73696. _this._blurVPostProcess.kernel = size * dw;
  73697. });
  73698. };
  73699. SSAORenderingPipeline.prototype._rebuild = function () {
  73700. this._firstUpdate = true;
  73701. _super.prototype._rebuild.call(this);
  73702. };
  73703. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73704. var _this = this;
  73705. var numSamples = 16;
  73706. var sampleSphere = [
  73707. 0.5381, 0.1856, -0.4319,
  73708. 0.1379, 0.2486, 0.4430,
  73709. 0.3371, 0.5679, -0.0057,
  73710. -0.6999, -0.0451, -0.0019,
  73711. 0.0689, -0.1598, -0.8547,
  73712. 0.0560, 0.0069, -0.1843,
  73713. -0.0146, 0.1402, 0.0762,
  73714. 0.0100, -0.1924, -0.0344,
  73715. -0.3577, -0.5301, -0.4358,
  73716. -0.3169, 0.1063, 0.0158,
  73717. 0.0103, -0.5869, 0.0046,
  73718. -0.0897, -0.4940, 0.3287,
  73719. 0.7119, -0.0154, -0.0918,
  73720. -0.0533, 0.0596, -0.5411,
  73721. 0.0352, -0.0631, 0.5460,
  73722. -0.4776, 0.2847, -0.0271
  73723. ];
  73724. var samplesFactor = 1.0 / numSamples;
  73725. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73726. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73727. "area", "fallOff", "base", "range", "viewport"
  73728. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73729. this._ssaoPostProcess.onApply = function (effect) {
  73730. if (_this._firstUpdate) {
  73731. effect.setArray3("sampleSphere", sampleSphere);
  73732. effect.setFloat("samplesFactor", samplesFactor);
  73733. effect.setFloat("randTextureTiles", 4.0);
  73734. }
  73735. effect.setFloat("totalStrength", _this.totalStrength);
  73736. effect.setFloat("radius", _this.radius);
  73737. effect.setFloat("area", _this.area);
  73738. effect.setFloat("fallOff", _this.fallOff);
  73739. effect.setFloat("base", _this.base);
  73740. effect.setTexture("textureSampler", _this._depthTexture);
  73741. effect.setTexture("randomSampler", _this._randomTexture);
  73742. };
  73743. };
  73744. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73745. var _this = this;
  73746. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73747. this._ssaoCombinePostProcess.onApply = function (effect) {
  73748. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73749. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73750. };
  73751. };
  73752. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73753. var size = 512;
  73754. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73755. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73756. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73757. var context = this._randomTexture.getContext();
  73758. var rand = function (min, max) {
  73759. return Math.random() * (max - min) + min;
  73760. };
  73761. var randVector = BABYLON.Vector3.Zero();
  73762. for (var x = 0; x < size; x++) {
  73763. for (var y = 0; y < size; y++) {
  73764. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73765. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73766. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73767. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73768. context.fillRect(x, y, 1, 1);
  73769. }
  73770. }
  73771. this._randomTexture.update(false);
  73772. };
  73773. __decorate([
  73774. BABYLON.serialize()
  73775. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73776. __decorate([
  73777. BABYLON.serialize()
  73778. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73779. __decorate([
  73780. BABYLON.serialize()
  73781. ], SSAORenderingPipeline.prototype, "area", void 0);
  73782. __decorate([
  73783. BABYLON.serialize()
  73784. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73785. __decorate([
  73786. BABYLON.serialize()
  73787. ], SSAORenderingPipeline.prototype, "base", void 0);
  73788. return SSAORenderingPipeline;
  73789. }(BABYLON.PostProcessRenderPipeline));
  73790. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73791. })(BABYLON || (BABYLON = {}));
  73792. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73793. var BABYLON;
  73794. (function (BABYLON) {
  73795. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73796. __extends(SSAO2RenderingPipeline, _super);
  73797. /**
  73798. * @constructor
  73799. * @param {string} name - The rendering pipeline name
  73800. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73801. * @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 }
  73802. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73803. */
  73804. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73805. var _this = _super.call(this, scene.getEngine(), name) || this;
  73806. // Members
  73807. /**
  73808. * The PassPostProcess id in the pipeline that contains the original scene color
  73809. */
  73810. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73811. /**
  73812. * The SSAO PostProcess id in the pipeline
  73813. */
  73814. _this.SSAORenderEffect = "SSAORenderEffect";
  73815. /**
  73816. * The horizontal blur PostProcess id in the pipeline
  73817. */
  73818. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73819. /**
  73820. * The vertical blur PostProcess id in the pipeline
  73821. */
  73822. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73823. /**
  73824. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73825. */
  73826. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73827. /**
  73828. * The output strength of the SSAO post-process. Default value is 1.0.
  73829. */
  73830. _this.totalStrength = 1.0;
  73831. /**
  73832. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73833. */
  73834. _this.maxZ = 100.0;
  73835. /**
  73836. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73837. */
  73838. _this.minZAspect = 0.2;
  73839. /**
  73840. * Number of samples used for the SSAO calculations. Default value is 8
  73841. */
  73842. _this._samples = 8;
  73843. /**
  73844. * Are we using bilateral blur ?
  73845. */
  73846. _this._expensiveBlur = true;
  73847. /**
  73848. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73849. */
  73850. _this.radius = 2.0;
  73851. /**
  73852. * The base color of the SSAO post-process
  73853. * The final result is "base + ssao" between [0, 1]
  73854. */
  73855. _this.base = 0.1;
  73856. _this._firstUpdate = true;
  73857. _this._scene = scene;
  73858. _this._ratio = ratio;
  73859. if (!_this.isSupported) {
  73860. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73861. return _this;
  73862. }
  73863. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73864. var blurRatio = _this._ratio.blurRatio || ratio;
  73865. // Set up assets
  73866. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73867. _this._createRandomTexture();
  73868. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73869. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73870. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73871. _this._createSSAOPostProcess(1.0);
  73872. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73873. _this._createSSAOCombinePostProcess(blurRatio);
  73874. // Set up pipeline
  73875. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73876. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73877. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73878. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73879. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73880. // Finish
  73881. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73882. if (cameras)
  73883. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73884. return _this;
  73885. }
  73886. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73887. get: function () {
  73888. return this._samples;
  73889. },
  73890. set: function (n) {
  73891. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73892. this._samples = n;
  73893. this._sampleSphere = this._generateHemisphere();
  73894. this._firstUpdate = true;
  73895. },
  73896. enumerable: true,
  73897. configurable: true
  73898. });
  73899. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73900. get: function () {
  73901. return this._expensiveBlur;
  73902. },
  73903. set: function (b) {
  73904. 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"]);
  73905. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73906. this._expensiveBlur = b;
  73907. this._firstUpdate = true;
  73908. },
  73909. enumerable: true,
  73910. configurable: true
  73911. });
  73912. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73913. /**
  73914. * Support test.
  73915. */
  73916. get: function () {
  73917. var engine = BABYLON.Engine.LastCreatedEngine;
  73918. if (!engine) {
  73919. return false;
  73920. }
  73921. return engine.getCaps().drawBuffersExtension;
  73922. },
  73923. enumerable: true,
  73924. configurable: true
  73925. });
  73926. // Public Methods
  73927. /**
  73928. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73929. */
  73930. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73931. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73932. for (var i = 0; i < this._scene.cameras.length; i++) {
  73933. var camera = this._scene.cameras[i];
  73934. this._originalColorPostProcess.dispose(camera);
  73935. this._ssaoPostProcess.dispose(camera);
  73936. this._blurHPostProcess.dispose(camera);
  73937. this._blurVPostProcess.dispose(camera);
  73938. this._ssaoCombinePostProcess.dispose(camera);
  73939. }
  73940. this._randomTexture.dispose();
  73941. if (disableGeometryBufferRenderer)
  73942. this._scene.disableGeometryBufferRenderer();
  73943. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73944. _super.prototype.dispose.call(this);
  73945. };
  73946. // Private Methods
  73947. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73948. var _this = this;
  73949. this._samplerOffsets = [];
  73950. var expensive = this.expensiveBlur;
  73951. for (var i = -8; i < 8; i++) {
  73952. this._samplerOffsets.push(i * 2 + 0.5);
  73953. }
  73954. 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");
  73955. this._blurHPostProcess.onApply = function (effect) {
  73956. if (!_this._scene.activeCamera) {
  73957. return;
  73958. }
  73959. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73960. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73961. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73962. effect.setFloat("radius", _this.radius);
  73963. effect.setTexture("depthSampler", _this._depthTexture);
  73964. if (_this._firstUpdate) {
  73965. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73966. }
  73967. };
  73968. 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");
  73969. this._blurVPostProcess.onApply = function (effect) {
  73970. if (!_this._scene.activeCamera) {
  73971. return;
  73972. }
  73973. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73974. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73975. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73976. effect.setFloat("radius", _this.radius);
  73977. effect.setTexture("depthSampler", _this._depthTexture);
  73978. if (_this._firstUpdate) {
  73979. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73980. _this._firstUpdate = false;
  73981. }
  73982. };
  73983. };
  73984. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73985. this._firstUpdate = true;
  73986. _super.prototype._rebuild.call(this);
  73987. };
  73988. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73989. var numSamples = this.samples;
  73990. var result = [];
  73991. var vector, scale;
  73992. var rand = function (min, max) {
  73993. return Math.random() * (max - min) + min;
  73994. };
  73995. var i = 0;
  73996. while (i < numSamples) {
  73997. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73998. vector.normalize();
  73999. scale = i / numSamples;
  74000. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74001. vector.scaleInPlace(scale);
  74002. result.push(vector.x, vector.y, vector.z);
  74003. i++;
  74004. }
  74005. return result;
  74006. };
  74007. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74008. var _this = this;
  74009. var numSamples = this.samples;
  74010. this._sampleSphere = this._generateHemisphere();
  74011. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74012. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74013. "base", "range", "projection", "near", "far", "texelSize",
  74014. "xViewport", "yViewport", "maxZ", "minZAspect"
  74015. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74016. this._ssaoPostProcess.onApply = function (effect) {
  74017. if (_this._firstUpdate) {
  74018. effect.setArray3("sampleSphere", _this._sampleSphere);
  74019. effect.setFloat("randTextureTiles", 4.0);
  74020. }
  74021. if (!_this._scene.activeCamera) {
  74022. return;
  74023. }
  74024. effect.setFloat("samplesFactor", 1 / _this.samples);
  74025. effect.setFloat("totalStrength", _this.totalStrength);
  74026. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74027. effect.setFloat("radius", _this.radius);
  74028. effect.setFloat("maxZ", _this.maxZ);
  74029. effect.setFloat("minZAspect", _this.minZAspect);
  74030. effect.setFloat("base", _this.base);
  74031. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74032. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74033. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74034. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74035. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74036. effect.setTexture("textureSampler", _this._depthTexture);
  74037. effect.setTexture("normalSampler", _this._normalTexture);
  74038. effect.setTexture("randomSampler", _this._randomTexture);
  74039. };
  74040. };
  74041. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74042. var _this = this;
  74043. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74044. this._ssaoCombinePostProcess.onApply = function (effect) {
  74045. var viewport = _this._scene.activeCamera.viewport;
  74046. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74047. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74048. };
  74049. };
  74050. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74051. var size = 512;
  74052. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74053. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74054. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74055. var context = this._randomTexture.getContext();
  74056. var rand = function (min, max) {
  74057. return Math.random() * (max - min) + min;
  74058. };
  74059. var randVector = BABYLON.Vector3.Zero();
  74060. for (var x = 0; x < size; x++) {
  74061. for (var y = 0; y < size; y++) {
  74062. randVector.x = rand(0.0, 1.0);
  74063. randVector.y = rand(0.0, 1.0);
  74064. randVector.z = 0.0;
  74065. randVector.normalize();
  74066. randVector.scaleInPlace(255);
  74067. randVector.x = Math.floor(randVector.x);
  74068. randVector.y = Math.floor(randVector.y);
  74069. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74070. context.fillRect(x, y, 1, 1);
  74071. }
  74072. }
  74073. this._randomTexture.update(false);
  74074. };
  74075. /**
  74076. * Serialize the rendering pipeline (Used when exporting)
  74077. * @returns the serialized object
  74078. */
  74079. SSAO2RenderingPipeline.prototype.serialize = function () {
  74080. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74081. serializationObject.customType = "SSAO2RenderingPipeline";
  74082. return serializationObject;
  74083. };
  74084. /**
  74085. * Parse the serialized pipeline
  74086. * @param source Source pipeline.
  74087. * @param scene The scene to load the pipeline to.
  74088. * @param rootUrl The URL of the serialized pipeline.
  74089. * @returns An instantiated pipeline from the serialized object.
  74090. */
  74091. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74092. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74093. };
  74094. __decorate([
  74095. BABYLON.serialize()
  74096. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74097. __decorate([
  74098. BABYLON.serialize()
  74099. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74100. __decorate([
  74101. BABYLON.serialize()
  74102. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74103. __decorate([
  74104. BABYLON.serialize("samples")
  74105. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74106. __decorate([
  74107. BABYLON.serialize()
  74108. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74109. __decorate([
  74110. BABYLON.serialize("expensiveBlur")
  74111. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74112. __decorate([
  74113. BABYLON.serialize()
  74114. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74115. __decorate([
  74116. BABYLON.serialize()
  74117. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74118. return SSAO2RenderingPipeline;
  74119. }(BABYLON.PostProcessRenderPipeline));
  74120. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74121. })(BABYLON || (BABYLON = {}));
  74122. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74123. // BABYLON.JS Chromatic Aberration GLSL Shader
  74124. // Author: Olivier Guyot
  74125. // Separates very slightly R, G and B colors on the edges of the screen
  74126. // Inspired by Francois Tarlier & Martins Upitis
  74127. var BABYLON;
  74128. (function (BABYLON) {
  74129. var LensRenderingPipeline = /** @class */ (function (_super) {
  74130. __extends(LensRenderingPipeline, _super);
  74131. /**
  74132. * @constructor
  74133. *
  74134. * Effect parameters are as follow:
  74135. * {
  74136. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74137. * edge_blur: number; // from 0 to x (1 for realism)
  74138. * distortion: number; // from 0 to x (1 for realism)
  74139. * grain_amount: number; // from 0 to 1
  74140. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74141. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74142. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74143. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74144. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74145. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74146. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74147. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74148. * }
  74149. * Note: if an effect parameter is unset, effect is disabled
  74150. *
  74151. * @param {string} name - The rendering pipeline name
  74152. * @param {object} parameters - An object containing all parameters (see above)
  74153. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74154. * @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)
  74155. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74156. */
  74157. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74158. if (ratio === void 0) { ratio = 1.0; }
  74159. var _this = _super.call(this, scene.getEngine(), name) || this;
  74160. // Lens effects can be of the following:
  74161. // - chromatic aberration (slight shift of RGB colors)
  74162. // - blur on the edge of the lens
  74163. // - lens distortion
  74164. // - depth-of-field blur & highlights enhancing
  74165. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74166. // - grain effect (noise or custom texture)
  74167. // Two additional texture samplers are needed:
  74168. // - depth map (for depth-of-field)
  74169. // - grain texture
  74170. /**
  74171. * The chromatic aberration PostProcess id in the pipeline
  74172. */
  74173. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74174. /**
  74175. * The highlights enhancing PostProcess id in the pipeline
  74176. */
  74177. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74178. /**
  74179. * The depth-of-field PostProcess id in the pipeline
  74180. */
  74181. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74182. _this._scene = scene;
  74183. // Fetch texture samplers
  74184. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74185. if (parameters.grain_texture) {
  74186. _this._grainTexture = parameters.grain_texture;
  74187. }
  74188. else {
  74189. _this._createGrainTexture();
  74190. }
  74191. // save parameters
  74192. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74193. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74194. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74195. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74196. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74197. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74198. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74199. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74200. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74201. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74202. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74203. // Create effects
  74204. _this._createChromaticAberrationPostProcess(ratio);
  74205. _this._createHighlightsPostProcess(ratio);
  74206. _this._createDepthOfFieldPostProcess(ratio / 4);
  74207. // Set up pipeline
  74208. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74209. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74210. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74211. if (_this._highlightsGain === -1) {
  74212. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74213. }
  74214. // Finish
  74215. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74216. if (cameras) {
  74217. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74218. }
  74219. return _this;
  74220. }
  74221. // public methods (self explanatory)
  74222. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74223. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74224. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74225. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74226. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74227. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74228. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74229. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74230. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74231. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74232. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74233. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74234. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74235. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74236. };
  74237. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74238. this._highlightsPostProcess.updateEffect();
  74239. };
  74240. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74241. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74242. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74243. this._highlightsGain = amount;
  74244. };
  74245. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74246. if (this._highlightsGain === -1) {
  74247. this._highlightsGain = 1.0;
  74248. }
  74249. this._highlightsThreshold = amount;
  74250. };
  74251. LensRenderingPipeline.prototype.disableHighlights = function () {
  74252. this._highlightsGain = -1;
  74253. };
  74254. /**
  74255. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74256. */
  74257. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74258. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74259. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74260. this._chromaticAberrationPostProcess = null;
  74261. this._highlightsPostProcess = null;
  74262. this._depthOfFieldPostProcess = null;
  74263. this._grainTexture.dispose();
  74264. if (disableDepthRender)
  74265. this._scene.disableDepthRenderer();
  74266. };
  74267. // colors shifting and distortion
  74268. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74269. var _this = this;
  74270. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74271. [], // samplers
  74272. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74273. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74274. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74275. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74276. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74277. effect.setFloat('radialIntensity', 1);
  74278. effect.setFloat2('direction', 17, 17);
  74279. effect.setFloat2('centerPosition', 0.5, 0.5);
  74280. };
  74281. };
  74282. // highlights enhancing
  74283. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74284. var _this = this;
  74285. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74286. [], // samplers
  74287. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74288. this._highlightsPostProcess.onApply = function (effect) {
  74289. effect.setFloat('gain', _this._highlightsGain);
  74290. effect.setFloat('threshold', _this._highlightsThreshold);
  74291. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74292. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74293. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74294. };
  74295. };
  74296. // colors shifting and distortion
  74297. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74298. var _this = this;
  74299. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74300. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74301. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74302. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74303. this._depthOfFieldPostProcess.onApply = function (effect) {
  74304. effect.setTexture("depthSampler", _this._depthTexture);
  74305. effect.setTexture("grainSampler", _this._grainTexture);
  74306. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74307. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74308. effect.setFloat('grain_amount', _this._grainAmount);
  74309. effect.setBool('blur_noise', _this._blurNoise);
  74310. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74311. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74312. effect.setFloat('distortion', _this._distortion);
  74313. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74314. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74315. effect.setFloat('aperture', _this._dofAperture);
  74316. effect.setFloat('darken', _this._dofDarken);
  74317. effect.setFloat('edge_blur', _this._edgeBlur);
  74318. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74319. if (_this._scene.activeCamera) {
  74320. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74321. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74322. }
  74323. };
  74324. };
  74325. // creates a black and white random noise texture, 512x512
  74326. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74327. var size = 512;
  74328. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74329. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74330. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74331. var context = this._grainTexture.getContext();
  74332. var rand = function (min, max) {
  74333. return Math.random() * (max - min) + min;
  74334. };
  74335. var value;
  74336. for (var x = 0; x < size; x++) {
  74337. for (var y = 0; y < size; y++) {
  74338. value = Math.floor(rand(0.42, 0.58) * 255);
  74339. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74340. context.fillRect(x, y, 1, 1);
  74341. }
  74342. }
  74343. this._grainTexture.update(false);
  74344. };
  74345. return LensRenderingPipeline;
  74346. }(BABYLON.PostProcessRenderPipeline));
  74347. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74348. })(BABYLON || (BABYLON = {}));
  74349. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74350. var BABYLON;
  74351. (function (BABYLON) {
  74352. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74353. __extends(StandardRenderingPipeline, _super);
  74354. /**
  74355. * @constructor
  74356. * @param {string} name - The rendering pipeline name
  74357. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74358. * @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)
  74359. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74360. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74361. */
  74362. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74363. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74364. var _this = _super.call(this, scene.getEngine(), name) || this;
  74365. _this.downSampleX4PostProcess = null;
  74366. _this.brightPassPostProcess = null;
  74367. _this.blurHPostProcesses = [];
  74368. _this.blurVPostProcesses = [];
  74369. _this.textureAdderPostProcess = null;
  74370. _this.volumetricLightPostProcess = null;
  74371. _this.volumetricLightSmoothXPostProcess = null;
  74372. _this.volumetricLightSmoothYPostProcess = null;
  74373. _this.volumetricLightMergePostProces = null;
  74374. _this.volumetricLightFinalPostProcess = null;
  74375. _this.luminancePostProcess = null;
  74376. _this.luminanceDownSamplePostProcesses = [];
  74377. _this.hdrPostProcess = null;
  74378. _this.textureAdderFinalPostProcess = null;
  74379. _this.lensFlareFinalPostProcess = null;
  74380. _this.hdrFinalPostProcess = null;
  74381. _this.lensFlarePostProcess = null;
  74382. _this.lensFlareComposePostProcess = null;
  74383. _this.motionBlurPostProcess = null;
  74384. _this.depthOfFieldPostProcess = null;
  74385. // Values
  74386. _this.brightThreshold = 1.0;
  74387. _this.blurWidth = 512.0;
  74388. _this.horizontalBlur = false;
  74389. _this.exposure = 1.0;
  74390. _this.lensTexture = null;
  74391. _this.volumetricLightCoefficient = 0.2;
  74392. _this.volumetricLightPower = 4.0;
  74393. _this.volumetricLightBlurScale = 64.0;
  74394. _this.sourceLight = null;
  74395. _this.hdrMinimumLuminance = 1.0;
  74396. _this.hdrDecreaseRate = 0.5;
  74397. _this.hdrIncreaseRate = 0.5;
  74398. _this.lensColorTexture = null;
  74399. _this.lensFlareStrength = 20.0;
  74400. _this.lensFlareGhostDispersal = 1.4;
  74401. _this.lensFlareHaloWidth = 0.7;
  74402. _this.lensFlareDistortionStrength = 16.0;
  74403. _this.lensStarTexture = null;
  74404. _this.lensFlareDirtTexture = null;
  74405. _this.depthOfFieldDistance = 10.0;
  74406. _this.depthOfFieldBlurWidth = 64.0;
  74407. _this.motionStrength = 1.0;
  74408. // IAnimatable
  74409. _this.animations = [];
  74410. _this._currentDepthOfFieldSource = null;
  74411. _this._hdrCurrentLuminance = 1.0;
  74412. // Getters and setters
  74413. _this._bloomEnabled = true;
  74414. _this._depthOfFieldEnabled = false;
  74415. _this._vlsEnabled = false;
  74416. _this._lensFlareEnabled = false;
  74417. _this._hdrEnabled = false;
  74418. _this._motionBlurEnabled = false;
  74419. _this._motionBlurSamples = 64.0;
  74420. _this._volumetricLightStepsCount = 50.0;
  74421. _this._cameras = cameras || [];
  74422. // Initialize
  74423. _this._scene = scene;
  74424. _this._basePostProcess = originalPostProcess;
  74425. _this._ratio = ratio;
  74426. // Misc
  74427. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74428. // Finish
  74429. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74430. _this._buildPipeline();
  74431. return _this;
  74432. }
  74433. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74434. get: function () {
  74435. return this._bloomEnabled;
  74436. },
  74437. set: function (enabled) {
  74438. if (this._bloomEnabled === enabled) {
  74439. return;
  74440. }
  74441. this._bloomEnabled = enabled;
  74442. this._buildPipeline();
  74443. },
  74444. enumerable: true,
  74445. configurable: true
  74446. });
  74447. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74448. get: function () {
  74449. return this._depthOfFieldEnabled;
  74450. },
  74451. set: function (enabled) {
  74452. if (this._depthOfFieldEnabled === enabled) {
  74453. return;
  74454. }
  74455. this._depthOfFieldEnabled = enabled;
  74456. this._buildPipeline();
  74457. },
  74458. enumerable: true,
  74459. configurable: true
  74460. });
  74461. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74462. get: function () {
  74463. return this._lensFlareEnabled;
  74464. },
  74465. set: function (enabled) {
  74466. if (this._lensFlareEnabled === enabled) {
  74467. return;
  74468. }
  74469. this._lensFlareEnabled = enabled;
  74470. this._buildPipeline();
  74471. },
  74472. enumerable: true,
  74473. configurable: true
  74474. });
  74475. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74476. get: function () {
  74477. return this._hdrEnabled;
  74478. },
  74479. set: function (enabled) {
  74480. if (this._hdrEnabled === enabled) {
  74481. return;
  74482. }
  74483. this._hdrEnabled = enabled;
  74484. this._buildPipeline();
  74485. },
  74486. enumerable: true,
  74487. configurable: true
  74488. });
  74489. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74490. get: function () {
  74491. return this._vlsEnabled;
  74492. },
  74493. set: function (enabled) {
  74494. if (this._vlsEnabled === enabled) {
  74495. return;
  74496. }
  74497. if (enabled) {
  74498. var geometry = this._scene.enableGeometryBufferRenderer();
  74499. if (!geometry) {
  74500. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74501. return;
  74502. }
  74503. }
  74504. this._vlsEnabled = enabled;
  74505. this._buildPipeline();
  74506. },
  74507. enumerable: true,
  74508. configurable: true
  74509. });
  74510. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74511. get: function () {
  74512. return this._motionBlurEnabled;
  74513. },
  74514. set: function (enabled) {
  74515. if (this._motionBlurEnabled === enabled) {
  74516. return;
  74517. }
  74518. this._motionBlurEnabled = enabled;
  74519. this._buildPipeline();
  74520. },
  74521. enumerable: true,
  74522. configurable: true
  74523. });
  74524. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74525. get: function () {
  74526. return this._volumetricLightStepsCount;
  74527. },
  74528. set: function (count) {
  74529. if (this.volumetricLightPostProcess) {
  74530. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74531. }
  74532. this._volumetricLightStepsCount = count;
  74533. },
  74534. enumerable: true,
  74535. configurable: true
  74536. });
  74537. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74538. get: function () {
  74539. return this._motionBlurSamples;
  74540. },
  74541. set: function (samples) {
  74542. if (this.motionBlurPostProcess) {
  74543. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74544. }
  74545. this._motionBlurSamples = samples;
  74546. },
  74547. enumerable: true,
  74548. configurable: true
  74549. });
  74550. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74551. var _this = this;
  74552. var ratio = this._ratio;
  74553. var scene = this._scene;
  74554. this._disposePostProcesses();
  74555. this._reset();
  74556. // Create pass post-process
  74557. if (!this._basePostProcess) {
  74558. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74559. this.originalPostProcess.onApply = function (effect) {
  74560. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74561. };
  74562. }
  74563. else {
  74564. this.originalPostProcess = this._basePostProcess;
  74565. }
  74566. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74567. this._currentDepthOfFieldSource = this.originalPostProcess;
  74568. if (this._bloomEnabled) {
  74569. // Create down sample X4 post-process
  74570. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74571. // Create bright pass post-process
  74572. this._createBrightPassPostProcess(scene, ratio / 2);
  74573. // Create gaussian blur post-processes (down sampling blurs)
  74574. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74575. // Create texture adder post-process
  74576. this._createTextureAdderPostProcess(scene, ratio);
  74577. // Create depth-of-field source post-process
  74578. 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);
  74579. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74580. }
  74581. if (this._vlsEnabled) {
  74582. // Create volumetric light
  74583. this._createVolumetricLightPostProcess(scene, ratio);
  74584. // Create volumetric light final post-process
  74585. 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);
  74586. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74587. }
  74588. if (this._lensFlareEnabled) {
  74589. // Create lens flare post-process
  74590. this._createLensFlarePostProcess(scene, ratio);
  74591. // Create depth-of-field source post-process post lens-flare and disable it now
  74592. 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);
  74593. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74594. }
  74595. if (this._hdrEnabled) {
  74596. // Create luminance
  74597. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74598. // Create HDR
  74599. this._createHdrPostProcess(scene, ratio);
  74600. // Create depth-of-field source post-process post hdr and disable it now
  74601. 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);
  74602. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74603. }
  74604. if (this._depthOfFieldEnabled) {
  74605. // Create gaussian blur used by depth-of-field
  74606. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74607. // Create depth-of-field post-process
  74608. this._createDepthOfFieldPostProcess(scene, ratio);
  74609. }
  74610. if (this._motionBlurEnabled) {
  74611. // Create motion blur post-process
  74612. this._createMotionBlurPostProcess(scene, ratio);
  74613. }
  74614. if (this._cameras !== null) {
  74615. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74616. }
  74617. };
  74618. // Down Sample X4 Post-Processs
  74619. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74620. var _this = this;
  74621. var downSampleX4Offsets = new Array(32);
  74622. 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);
  74623. this.downSampleX4PostProcess.onApply = function (effect) {
  74624. var id = 0;
  74625. var width = _this.downSampleX4PostProcess.width;
  74626. var height = _this.downSampleX4PostProcess.height;
  74627. for (var i = -2; i < 2; i++) {
  74628. for (var j = -2; j < 2; j++) {
  74629. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74630. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74631. id += 2;
  74632. }
  74633. }
  74634. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74635. };
  74636. // Add to pipeline
  74637. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74638. };
  74639. // Brightpass Post-Process
  74640. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74641. var _this = this;
  74642. var brightOffsets = new Array(8);
  74643. 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);
  74644. this.brightPassPostProcess.onApply = function (effect) {
  74645. var sU = (1.0 / _this.brightPassPostProcess.width);
  74646. var sV = (1.0 / _this.brightPassPostProcess.height);
  74647. brightOffsets[0] = -0.5 * sU;
  74648. brightOffsets[1] = 0.5 * sV;
  74649. brightOffsets[2] = 0.5 * sU;
  74650. brightOffsets[3] = 0.5 * sV;
  74651. brightOffsets[4] = -0.5 * sU;
  74652. brightOffsets[5] = -0.5 * sV;
  74653. brightOffsets[6] = 0.5 * sU;
  74654. brightOffsets[7] = -0.5 * sV;
  74655. effect.setArray2("dsOffsets", brightOffsets);
  74656. effect.setFloat("brightThreshold", _this.brightThreshold);
  74657. };
  74658. // Add to pipeline
  74659. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74660. };
  74661. // Create blur H&V post-processes
  74662. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74663. var _this = this;
  74664. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74665. var engine = scene.getEngine();
  74666. 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);
  74667. 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);
  74668. blurX.onActivateObservable.add(function () {
  74669. var dw = blurX.width / engine.getRenderWidth();
  74670. blurX.kernel = _this[blurWidthKey] * dw;
  74671. });
  74672. blurY.onActivateObservable.add(function () {
  74673. var dw = blurY.height / engine.getRenderHeight();
  74674. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74675. });
  74676. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74677. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74678. this.blurHPostProcesses.push(blurX);
  74679. this.blurVPostProcesses.push(blurY);
  74680. };
  74681. // Create texture adder post-process
  74682. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74683. var _this = this;
  74684. 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);
  74685. this.textureAdderPostProcess.onApply = function (effect) {
  74686. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74687. effect.setTexture("lensSampler", _this.lensTexture);
  74688. effect.setFloat("exposure", _this.exposure);
  74689. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74690. };
  74691. // Add to pipeline
  74692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74693. };
  74694. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74695. var _this = this;
  74696. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74697. geometryRenderer.enablePosition = true;
  74698. var geometry = geometryRenderer.getGBuffer();
  74699. // Base post-process
  74700. 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));
  74701. var depthValues = BABYLON.Vector2.Zero();
  74702. this.volumetricLightPostProcess.onApply = function (effect) {
  74703. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74704. var generator = _this.sourceLight.getShadowGenerator();
  74705. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74706. effect.setTexture("positionSampler", geometry.textures[2]);
  74707. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74708. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74709. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74710. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74711. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74712. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74713. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74714. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74715. effect.setVector2("depthValues", depthValues);
  74716. }
  74717. };
  74718. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74719. // Smooth
  74720. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74721. // Merge
  74722. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74723. this.volumetricLightMergePostProces.onApply = function (effect) {
  74724. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74725. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74726. };
  74727. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74728. };
  74729. // Create luminance
  74730. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74731. var _this = this;
  74732. // Create luminance
  74733. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74734. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74735. var offsets = [];
  74736. this.luminancePostProcess.onApply = function (effect) {
  74737. var sU = (1.0 / _this.luminancePostProcess.width);
  74738. var sV = (1.0 / _this.luminancePostProcess.height);
  74739. offsets[0] = -0.5 * sU;
  74740. offsets[1] = 0.5 * sV;
  74741. offsets[2] = 0.5 * sU;
  74742. offsets[3] = 0.5 * sV;
  74743. offsets[4] = -0.5 * sU;
  74744. offsets[5] = -0.5 * sV;
  74745. offsets[6] = 0.5 * sU;
  74746. offsets[7] = -0.5 * sV;
  74747. effect.setArray2("lumOffsets", offsets);
  74748. };
  74749. // Add to pipeline
  74750. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74751. // Create down sample luminance
  74752. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74753. var size = Math.pow(3, i);
  74754. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74755. if (i === 0) {
  74756. defines += "#define FINAL_DOWN_SAMPLER";
  74757. }
  74758. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74759. this.luminanceDownSamplePostProcesses.push(postProcess);
  74760. }
  74761. // Create callbacks and add effects
  74762. var lastLuminance = this.luminancePostProcess;
  74763. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74764. var downSampleOffsets = new Array(18);
  74765. pp.onApply = function (effect) {
  74766. if (!lastLuminance) {
  74767. return;
  74768. }
  74769. var id = 0;
  74770. for (var x = -1; x < 2; x++) {
  74771. for (var y = -1; y < 2; y++) {
  74772. downSampleOffsets[id] = x / lastLuminance.width;
  74773. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74774. id += 2;
  74775. }
  74776. }
  74777. effect.setArray2("dsOffsets", downSampleOffsets);
  74778. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74779. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74780. lastLuminance = _this.luminancePostProcess;
  74781. }
  74782. else {
  74783. lastLuminance = pp;
  74784. }
  74785. };
  74786. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74787. pp.onAfterRender = function (effect) {
  74788. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74789. 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);
  74790. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74791. };
  74792. }
  74793. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74794. });
  74795. };
  74796. // Create HDR post-process
  74797. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74798. var _this = this;
  74799. 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);
  74800. var outputLiminance = 1;
  74801. var time = 0;
  74802. var lastTime = 0;
  74803. this.hdrPostProcess.onApply = function (effect) {
  74804. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74805. time += scene.getEngine().getDeltaTime();
  74806. if (outputLiminance < 0) {
  74807. outputLiminance = _this._hdrCurrentLuminance;
  74808. }
  74809. else {
  74810. var dt = (lastTime - time) / 1000.0;
  74811. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74812. outputLiminance += _this.hdrDecreaseRate * dt;
  74813. }
  74814. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74815. outputLiminance -= _this.hdrIncreaseRate * dt;
  74816. }
  74817. else {
  74818. outputLiminance = _this._hdrCurrentLuminance;
  74819. }
  74820. }
  74821. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74822. effect.setFloat("averageLuminance", outputLiminance);
  74823. lastTime = time;
  74824. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74825. };
  74826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74827. };
  74828. // Create lens flare post-process
  74829. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74830. var _this = this;
  74831. 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);
  74832. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74833. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74834. 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);
  74835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74836. var resolution = new BABYLON.Vector2(0, 0);
  74837. // Lens flare
  74838. this.lensFlarePostProcess.onApply = function (effect) {
  74839. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74840. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74841. effect.setFloat("strength", _this.lensFlareStrength);
  74842. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74843. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74844. // Shift
  74845. resolution.x = _this.lensFlarePostProcess.width;
  74846. resolution.y = _this.lensFlarePostProcess.height;
  74847. effect.setVector2("resolution", resolution);
  74848. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74849. };
  74850. // Compose
  74851. 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);
  74852. 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);
  74853. this.lensFlareComposePostProcess.onApply = function (effect) {
  74854. if (!_this._scene.activeCamera) {
  74855. return;
  74856. }
  74857. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74858. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74859. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74860. // Lens start rotation matrix
  74861. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74862. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74863. 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));
  74864. camRot *= 4.0;
  74865. 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);
  74866. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74867. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74868. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74869. };
  74870. };
  74871. // Create depth-of-field post-process
  74872. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74873. var _this = this;
  74874. 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);
  74875. this.depthOfFieldPostProcess.onApply = function (effect) {
  74876. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74877. effect.setTexture("depthSampler", _this._getDepthTexture());
  74878. effect.setFloat("distance", _this.depthOfFieldDistance);
  74879. };
  74880. // Add to pipeline
  74881. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74882. };
  74883. // Create motion blur post-process
  74884. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74885. var _this = this;
  74886. 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);
  74887. var motionScale = 0;
  74888. var prevViewProjection = BABYLON.Matrix.Identity();
  74889. var invViewProjection = BABYLON.Matrix.Identity();
  74890. var viewProjection = BABYLON.Matrix.Identity();
  74891. var screenSize = BABYLON.Vector2.Zero();
  74892. this.motionBlurPostProcess.onApply = function (effect) {
  74893. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74894. viewProjection.invertToRef(invViewProjection);
  74895. effect.setMatrix("inverseViewProjection", invViewProjection);
  74896. effect.setMatrix("prevViewProjection", prevViewProjection);
  74897. prevViewProjection = viewProjection;
  74898. screenSize.x = _this.motionBlurPostProcess.width;
  74899. screenSize.y = _this.motionBlurPostProcess.height;
  74900. effect.setVector2("screenSize", screenSize);
  74901. motionScale = scene.getEngine().getFps() / 60.0;
  74902. effect.setFloat("motionScale", motionScale);
  74903. effect.setFloat("motionStrength", _this.motionStrength);
  74904. effect.setTexture("depthSampler", _this._getDepthTexture());
  74905. };
  74906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74907. };
  74908. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74909. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74910. var renderer = this._scene.enableGeometryBufferRenderer();
  74911. return renderer.getGBuffer().textures[0];
  74912. }
  74913. return this._scene.enableDepthRenderer().getDepthMap();
  74914. };
  74915. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74916. for (var i = 0; i < this._cameras.length; i++) {
  74917. var camera = this._cameras[i];
  74918. if (this.originalPostProcess) {
  74919. this.originalPostProcess.dispose(camera);
  74920. }
  74921. if (this.downSampleX4PostProcess) {
  74922. this.downSampleX4PostProcess.dispose(camera);
  74923. }
  74924. if (this.brightPassPostProcess) {
  74925. this.brightPassPostProcess.dispose(camera);
  74926. }
  74927. if (this.textureAdderPostProcess) {
  74928. this.textureAdderPostProcess.dispose(camera);
  74929. }
  74930. if (this.textureAdderFinalPostProcess) {
  74931. this.textureAdderFinalPostProcess.dispose(camera);
  74932. }
  74933. if (this.volumetricLightPostProcess) {
  74934. this.volumetricLightPostProcess.dispose(camera);
  74935. }
  74936. if (this.volumetricLightSmoothXPostProcess) {
  74937. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74938. }
  74939. if (this.volumetricLightSmoothYPostProcess) {
  74940. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74941. }
  74942. if (this.volumetricLightMergePostProces) {
  74943. this.volumetricLightMergePostProces.dispose(camera);
  74944. }
  74945. if (this.volumetricLightFinalPostProcess) {
  74946. this.volumetricLightFinalPostProcess.dispose(camera);
  74947. }
  74948. if (this.lensFlarePostProcess) {
  74949. this.lensFlarePostProcess.dispose(camera);
  74950. }
  74951. if (this.lensFlareComposePostProcess) {
  74952. this.lensFlareComposePostProcess.dispose(camera);
  74953. }
  74954. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74955. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74956. }
  74957. if (this.luminancePostProcess) {
  74958. this.luminancePostProcess.dispose(camera);
  74959. }
  74960. if (this.hdrPostProcess) {
  74961. this.hdrPostProcess.dispose(camera);
  74962. }
  74963. if (this.hdrFinalPostProcess) {
  74964. this.hdrFinalPostProcess.dispose(camera);
  74965. }
  74966. if (this.depthOfFieldPostProcess) {
  74967. this.depthOfFieldPostProcess.dispose(camera);
  74968. }
  74969. if (this.motionBlurPostProcess) {
  74970. this.motionBlurPostProcess.dispose(camera);
  74971. }
  74972. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74973. this.blurHPostProcesses[j].dispose(camera);
  74974. }
  74975. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74976. this.blurVPostProcesses[j].dispose(camera);
  74977. }
  74978. }
  74979. this.originalPostProcess = null;
  74980. this.downSampleX4PostProcess = null;
  74981. this.brightPassPostProcess = null;
  74982. this.textureAdderPostProcess = null;
  74983. this.textureAdderFinalPostProcess = null;
  74984. this.volumetricLightPostProcess = null;
  74985. this.volumetricLightSmoothXPostProcess = null;
  74986. this.volumetricLightSmoothYPostProcess = null;
  74987. this.volumetricLightMergePostProces = null;
  74988. this.volumetricLightFinalPostProcess = null;
  74989. this.lensFlarePostProcess = null;
  74990. this.lensFlareComposePostProcess = null;
  74991. this.luminancePostProcess = null;
  74992. this.hdrPostProcess = null;
  74993. this.hdrFinalPostProcess = null;
  74994. this.depthOfFieldPostProcess = null;
  74995. this.motionBlurPostProcess = null;
  74996. this.luminanceDownSamplePostProcesses = [];
  74997. this.blurHPostProcesses = [];
  74998. this.blurVPostProcesses = [];
  74999. };
  75000. /**
  75001. * Dispose of the pipeline and stop all post processes
  75002. */
  75003. StandardRenderingPipeline.prototype.dispose = function () {
  75004. this._disposePostProcesses();
  75005. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75006. _super.prototype.dispose.call(this);
  75007. };
  75008. /**
  75009. * Serialize the rendering pipeline (Used when exporting)
  75010. * @returns the serialized object
  75011. */
  75012. StandardRenderingPipeline.prototype.serialize = function () {
  75013. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75014. if (this.sourceLight) {
  75015. serializationObject.sourceLightId = this.sourceLight.id;
  75016. }
  75017. serializationObject.customType = "StandardRenderingPipeline";
  75018. return serializationObject;
  75019. };
  75020. /**
  75021. * Parse the serialized pipeline
  75022. * @param source Source pipeline.
  75023. * @param scene The scene to load the pipeline to.
  75024. * @param rootUrl The URL of the serialized pipeline.
  75025. * @returns An instantiated pipeline from the serialized object.
  75026. */
  75027. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75028. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75029. if (source.sourceLightId) {
  75030. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75031. }
  75032. return p;
  75033. };
  75034. // Luminance steps
  75035. StandardRenderingPipeline.LuminanceSteps = 6;
  75036. __decorate([
  75037. BABYLON.serialize()
  75038. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75039. __decorate([
  75040. BABYLON.serialize()
  75041. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75042. __decorate([
  75043. BABYLON.serialize()
  75044. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75045. __decorate([
  75046. BABYLON.serialize()
  75047. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75048. __decorate([
  75049. BABYLON.serializeAsTexture("lensTexture")
  75050. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75051. __decorate([
  75052. BABYLON.serialize()
  75053. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75054. __decorate([
  75055. BABYLON.serialize()
  75056. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75057. __decorate([
  75058. BABYLON.serialize()
  75059. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75060. __decorate([
  75061. BABYLON.serialize()
  75062. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75063. __decorate([
  75064. BABYLON.serialize()
  75065. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75066. __decorate([
  75067. BABYLON.serialize()
  75068. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75069. __decorate([
  75070. BABYLON.serializeAsTexture("lensColorTexture")
  75071. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75072. __decorate([
  75073. BABYLON.serialize()
  75074. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75075. __decorate([
  75076. BABYLON.serialize()
  75077. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75078. __decorate([
  75079. BABYLON.serialize()
  75080. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75081. __decorate([
  75082. BABYLON.serialize()
  75083. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75084. __decorate([
  75085. BABYLON.serializeAsTexture("lensStarTexture")
  75086. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75087. __decorate([
  75088. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75089. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75090. __decorate([
  75091. BABYLON.serialize()
  75092. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75093. __decorate([
  75094. BABYLON.serialize()
  75095. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75096. __decorate([
  75097. BABYLON.serialize()
  75098. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75099. __decorate([
  75100. BABYLON.serialize()
  75101. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75102. __decorate([
  75103. BABYLON.serialize()
  75104. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75105. __decorate([
  75106. BABYLON.serialize()
  75107. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75108. __decorate([
  75109. BABYLON.serialize()
  75110. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75111. __decorate([
  75112. BABYLON.serialize()
  75113. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75114. __decorate([
  75115. BABYLON.serialize()
  75116. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75117. __decorate([
  75118. BABYLON.serialize()
  75119. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75120. __decorate([
  75121. BABYLON.serialize()
  75122. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75123. __decorate([
  75124. BABYLON.serialize()
  75125. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75126. return StandardRenderingPipeline;
  75127. }(BABYLON.PostProcessRenderPipeline));
  75128. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75129. })(BABYLON || (BABYLON = {}));
  75130. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75131. var BABYLON;
  75132. (function (BABYLON) {
  75133. var FxaaPostProcess = /** @class */ (function (_super) {
  75134. __extends(FxaaPostProcess, _super);
  75135. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75136. if (camera === void 0) { camera = null; }
  75137. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75138. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75139. var defines = _this._getDefines();
  75140. _this.updateEffect(defines);
  75141. _this.onApplyObservable.add(function (effect) {
  75142. var texelSize = _this.texelSize;
  75143. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75144. });
  75145. return _this;
  75146. }
  75147. FxaaPostProcess.prototype._getDefines = function () {
  75148. var engine = this.getEngine();
  75149. if (!engine) {
  75150. return null;
  75151. }
  75152. var glInfo = engine.getGlInfo();
  75153. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75154. return "#define MALI 1\n";
  75155. }
  75156. return null;
  75157. };
  75158. return FxaaPostProcess;
  75159. }(BABYLON.PostProcess));
  75160. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75161. })(BABYLON || (BABYLON = {}));
  75162. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75163. var BABYLON;
  75164. (function (BABYLON) {
  75165. /**
  75166. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75167. */
  75168. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75169. __extends(ChromaticAberrationPostProcess, _super);
  75170. /**
  75171. * Creates a new instance ChromaticAberrationPostProcess
  75172. * @param name The name of the effect.
  75173. * @param screenWidth The width of the screen to apply the effect on.
  75174. * @param screenHeight The height of the screen to apply the effect on.
  75175. * @param options The required width/height ratio to downsize to before computing the render pass.
  75176. * @param camera The camera to apply the render pass to.
  75177. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75178. * @param engine The engine which the post process will be applied. (default: current engine)
  75179. * @param reusable If the post process can be reused on the same frame. (default: false)
  75180. * @param textureType Type of textures used when performing the post process. (default: 0)
  75181. * @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)
  75182. */
  75183. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75184. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75185. if (blockCompilation === void 0) { blockCompilation = false; }
  75186. 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;
  75187. /**
  75188. * The amount of seperation of rgb channels (default: 30)
  75189. */
  75190. _this.aberrationAmount = 30;
  75191. /**
  75192. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75193. */
  75194. _this.radialIntensity = 0;
  75195. /**
  75196. * 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))
  75197. */
  75198. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75199. /**
  75200. * 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))
  75201. */
  75202. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75203. _this.onApplyObservable.add(function (effect) {
  75204. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75205. effect.setFloat('screen_width', screenWidth);
  75206. effect.setFloat('screen_height', screenHeight);
  75207. effect.setFloat('radialIntensity', _this.radialIntensity);
  75208. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75209. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75210. });
  75211. return _this;
  75212. }
  75213. return ChromaticAberrationPostProcess;
  75214. }(BABYLON.PostProcess));
  75215. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75216. })(BABYLON || (BABYLON = {}));
  75217. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75218. var BABYLON;
  75219. (function (BABYLON) {
  75220. /**
  75221. * The GrainPostProcess adds noise to the image at mid luminance levels
  75222. */
  75223. var GrainPostProcess = /** @class */ (function (_super) {
  75224. __extends(GrainPostProcess, _super);
  75225. /**
  75226. * Creates a new instance of @see GrainPostProcess
  75227. * @param name The name of the effect.
  75228. * @param options The required width/height ratio to downsize to before computing the render pass.
  75229. * @param camera The camera to apply the render pass to.
  75230. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75231. * @param engine The engine which the post process will be applied. (default: current engine)
  75232. * @param reusable If the post process can be reused on the same frame. (default: false)
  75233. * @param textureType Type of textures used when performing the post process. (default: 0)
  75234. * @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)
  75235. */
  75236. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75237. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75238. if (blockCompilation === void 0) { blockCompilation = false; }
  75239. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75240. /**
  75241. * The intensity of the grain added (default: 30)
  75242. */
  75243. _this.intensity = 30;
  75244. /**
  75245. * If the grain should be randomized on every frame
  75246. */
  75247. _this.animated = false;
  75248. _this.onApplyObservable.add(function (effect) {
  75249. effect.setFloat('intensity', _this.intensity);
  75250. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75251. });
  75252. return _this;
  75253. }
  75254. return GrainPostProcess;
  75255. }(BABYLON.PostProcess));
  75256. BABYLON.GrainPostProcess = GrainPostProcess;
  75257. })(BABYLON || (BABYLON = {}));
  75258. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75259. var BABYLON;
  75260. (function (BABYLON) {
  75261. /**
  75262. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75263. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75264. */
  75265. var SharpenPostProcess = /** @class */ (function (_super) {
  75266. __extends(SharpenPostProcess, _super);
  75267. /**
  75268. * Creates a new instance ConvolutionPostProcess
  75269. * @param name The name of the effect.
  75270. * @param options The required width/height ratio to downsize to before computing the render pass.
  75271. * @param camera The camera to apply the render pass to.
  75272. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75273. * @param engine The engine which the post process will be applied. (default: current engine)
  75274. * @param reusable If the post process can be reused on the same frame. (default: false)
  75275. * @param textureType Type of textures used when performing the post process. (default: 0)
  75276. * @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)
  75277. */
  75278. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75279. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75280. if (blockCompilation === void 0) { blockCompilation = false; }
  75281. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75282. /**
  75283. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75284. */
  75285. _this.colorAmount = 1.0;
  75286. /**
  75287. * How much sharpness should be applied (default: 0.3)
  75288. */
  75289. _this.edgeAmount = 0.3;
  75290. _this.onApply = function (effect) {
  75291. effect.setFloat2("screenSize", _this.width, _this.height);
  75292. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75293. };
  75294. return _this;
  75295. }
  75296. return SharpenPostProcess;
  75297. }(BABYLON.PostProcess));
  75298. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75299. })(BABYLON || (BABYLON = {}));
  75300. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75301. var BABYLON;
  75302. (function (BABYLON) {
  75303. /**
  75304. * The Blur Post Process which blurs an image based on a kernel and direction.
  75305. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75306. */
  75307. var BlurPostProcess = /** @class */ (function (_super) {
  75308. __extends(BlurPostProcess, _super);
  75309. /**
  75310. * Creates a new instance BlurPostProcess
  75311. * @param name The name of the effect.
  75312. * @param direction The direction in which to blur the image.
  75313. * @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.
  75314. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75315. * @param camera The camera to apply the render pass to.
  75316. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75317. * @param engine The engine which the post process will be applied. (default: current engine)
  75318. * @param reusable If the post process can be reused on the same frame. (default: false)
  75319. * @param textureType Type of textures used when performing the post process. (default: 0)
  75320. * @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)
  75321. */
  75322. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75323. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75324. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75325. if (defines === void 0) { defines = ""; }
  75326. if (blockCompilation === void 0) { blockCompilation = false; }
  75327. 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;
  75328. _this.direction = direction;
  75329. _this.blockCompilation = blockCompilation;
  75330. _this._packedFloat = false;
  75331. _this._staticDefines = "";
  75332. _this._staticDefines = defines;
  75333. _this.onApplyObservable.add(function (effect) {
  75334. if (_this._outputTexture) {
  75335. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75336. }
  75337. else {
  75338. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75339. }
  75340. });
  75341. _this.kernel = kernel;
  75342. return _this;
  75343. }
  75344. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75345. /**
  75346. * Gets the length in pixels of the blur sample region
  75347. */
  75348. get: function () {
  75349. return this._idealKernel;
  75350. },
  75351. /**
  75352. * Sets the length in pixels of the blur sample region
  75353. */
  75354. set: function (v) {
  75355. if (this._idealKernel === v) {
  75356. return;
  75357. }
  75358. v = Math.max(v, 1);
  75359. this._idealKernel = v;
  75360. this._kernel = this._nearestBestKernel(v);
  75361. if (!this.blockCompilation) {
  75362. this._updateParameters();
  75363. }
  75364. },
  75365. enumerable: true,
  75366. configurable: true
  75367. });
  75368. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75369. /**
  75370. * Gets wether or not the blur is unpacking/repacking floats
  75371. */
  75372. get: function () {
  75373. return this._packedFloat;
  75374. },
  75375. /**
  75376. * Sets wether or not the blur needs to unpack/repack floats
  75377. */
  75378. set: function (v) {
  75379. if (this._packedFloat === v) {
  75380. return;
  75381. }
  75382. this._packedFloat = v;
  75383. if (!this.blockCompilation) {
  75384. this._updateParameters();
  75385. }
  75386. },
  75387. enumerable: true,
  75388. configurable: true
  75389. });
  75390. /**
  75391. * Updates the effect with the current post process compile time values and recompiles the shader.
  75392. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75393. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75394. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75395. * @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
  75396. * @param onCompiled Called when the shader has been compiled.
  75397. * @param onError Called if there is an error when compiling a shader.
  75398. */
  75399. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75400. if (defines === void 0) { defines = null; }
  75401. if (uniforms === void 0) { uniforms = null; }
  75402. if (samplers === void 0) { samplers = null; }
  75403. this._updateParameters(onCompiled, onError);
  75404. };
  75405. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75406. // Generate sampling offsets and weights
  75407. var N = this._kernel;
  75408. var centerIndex = (N - 1) / 2;
  75409. // Generate Gaussian sampling weights over kernel
  75410. var offsets = [];
  75411. var weights = [];
  75412. var totalWeight = 0;
  75413. for (var i = 0; i < N; i++) {
  75414. var u = i / (N - 1);
  75415. var w = this._gaussianWeight(u * 2.0 - 1);
  75416. offsets[i] = (i - centerIndex);
  75417. weights[i] = w;
  75418. totalWeight += w;
  75419. }
  75420. // Normalize weights
  75421. for (var i = 0; i < weights.length; i++) {
  75422. weights[i] /= totalWeight;
  75423. }
  75424. // Optimize: combine samples to take advantage of hardware linear sampling
  75425. // Walk from left to center, combining pairs (symmetrically)
  75426. var linearSamplingWeights = [];
  75427. var linearSamplingOffsets = [];
  75428. var linearSamplingMap = [];
  75429. for (var i = 0; i <= centerIndex; i += 2) {
  75430. var j = Math.min(i + 1, Math.floor(centerIndex));
  75431. var singleCenterSample = i === j;
  75432. if (singleCenterSample) {
  75433. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75434. }
  75435. else {
  75436. var sharedCell = j === centerIndex;
  75437. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75438. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75439. if (offsetLinear === 0) {
  75440. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75441. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75442. }
  75443. else {
  75444. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75445. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75446. }
  75447. }
  75448. }
  75449. for (var i = 0; i < linearSamplingMap.length; i++) {
  75450. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75451. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75452. }
  75453. // Replace with optimized
  75454. offsets = linearSamplingOffsets;
  75455. weights = linearSamplingWeights;
  75456. // Generate shaders
  75457. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75458. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75459. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75460. var defines = "";
  75461. defines += this._staticDefines;
  75462. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75463. if (this._staticDefines.indexOf("DOF") != -1) {
  75464. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75465. varyingCount--;
  75466. }
  75467. for (var i = 0; i < varyingCount; i++) {
  75468. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75469. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75470. }
  75471. var depCount = 0;
  75472. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75473. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75474. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75475. depCount++;
  75476. }
  75477. if (this.packedFloat) {
  75478. defines += "#define PACKEDFLOAT 1";
  75479. }
  75480. this.blockCompilation = false;
  75481. _super.prototype.updateEffect.call(this, defines, null, null, {
  75482. varyingCount: varyingCount,
  75483. depCount: depCount
  75484. }, onCompiled, onError);
  75485. };
  75486. /**
  75487. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75488. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75489. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75490. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75491. * The gaps between physical kernels are compensated for in the weighting of the samples
  75492. * @param idealKernel Ideal blur kernel.
  75493. * @return Nearest best kernel.
  75494. */
  75495. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75496. var v = Math.round(idealKernel);
  75497. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75498. var k = _a[_i];
  75499. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75500. return Math.max(k, 3);
  75501. }
  75502. }
  75503. return Math.max(v, 3);
  75504. };
  75505. /**
  75506. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75507. * @param x The point on the Gaussian distribution to sample.
  75508. * @return the value of the Gaussian function at x.
  75509. */
  75510. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75511. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75512. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75513. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75514. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75515. // truncated at around 1.3% of peak strength.
  75516. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75517. var sigma = (1 / 3);
  75518. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75519. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75520. var weight = (1.0 / denominator) * Math.exp(exponent);
  75521. return weight;
  75522. };
  75523. /**
  75524. * Generates a string that can be used as a floating point number in GLSL.
  75525. * @param x Value to print.
  75526. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75527. * @return GLSL float string.
  75528. */
  75529. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75530. if (decimalFigures === void 0) { decimalFigures = 8; }
  75531. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75532. };
  75533. return BlurPostProcess;
  75534. }(BABYLON.PostProcess));
  75535. BABYLON.BlurPostProcess = BlurPostProcess;
  75536. })(BABYLON || (BABYLON = {}));
  75537. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75538. var BABYLON;
  75539. (function (BABYLON) {
  75540. /**
  75541. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75542. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75543. * based on samples that have a large difference in distance than the center pixel.
  75544. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75545. */
  75546. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75547. __extends(DepthOfFieldBlurPostProcess, _super);
  75548. /**
  75549. * Creates a new instance CircleOfConfusionPostProcess
  75550. * @param name The name of the effect.
  75551. * @param scene The scene the effect belongs to.
  75552. * @param direction The direction the blur should be applied.
  75553. * @param kernel The size of the kernel used to blur.
  75554. * @param options The required width/height ratio to downsize to before computing the render pass.
  75555. * @param camera The camera to apply the render pass to.
  75556. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75557. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75558. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75559. * @param engine The engine which the post process will be applied. (default: current engine)
  75560. * @param reusable If the post process can be reused on the same frame. (default: false)
  75561. * @param textureType Type of textures used when performing the post process. (default: 0)
  75562. * @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)
  75563. */
  75564. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75565. if (imageToBlur === void 0) { imageToBlur = null; }
  75566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75567. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75568. if (blockCompilation === void 0) { blockCompilation = false; }
  75569. 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;
  75570. _this.direction = direction;
  75571. _this.onApplyObservable.add(function (effect) {
  75572. if (imageToBlur != null) {
  75573. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75574. }
  75575. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75576. if (scene.activeCamera) {
  75577. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75578. }
  75579. });
  75580. return _this;
  75581. }
  75582. return DepthOfFieldBlurPostProcess;
  75583. }(BABYLON.BlurPostProcess));
  75584. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75585. })(BABYLON || (BABYLON = {}));
  75586. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75587. var BABYLON;
  75588. (function (BABYLON) {
  75589. /**
  75590. * Options to be set when merging outputs from the default pipeline.
  75591. */
  75592. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75593. function DepthOfFieldMergePostProcessOptions() {
  75594. }
  75595. return DepthOfFieldMergePostProcessOptions;
  75596. }());
  75597. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75598. /**
  75599. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75600. */
  75601. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75602. __extends(DepthOfFieldMergePostProcess, _super);
  75603. /**
  75604. * Creates a new instance of DepthOfFieldMergePostProcess
  75605. * @param name The name of the effect.
  75606. * @param originalFromInput Post process which's input will be used for the merge.
  75607. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75608. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75609. * @param options The required width/height ratio to downsize to before computing the render pass.
  75610. * @param camera The camera to apply the render pass to.
  75611. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75612. * @param engine The engine which the post process will be applied. (default: current engine)
  75613. * @param reusable If the post process can be reused on the same frame. (default: false)
  75614. * @param textureType Type of textures used when performing the post process. (default: 0)
  75615. * @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)
  75616. */
  75617. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75618. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75619. if (blockCompilation === void 0) { blockCompilation = false; }
  75620. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75621. _this.blurSteps = blurSteps;
  75622. _this.onApplyObservable.add(function (effect) {
  75623. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75624. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75625. blurSteps.forEach(function (step, index) {
  75626. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75627. });
  75628. });
  75629. if (!blockCompilation) {
  75630. _this.updateEffect();
  75631. }
  75632. return _this;
  75633. }
  75634. /**
  75635. * Updates the effect with the current post process compile time values and recompiles the shader.
  75636. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75637. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75638. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75639. * @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
  75640. * @param onCompiled Called when the shader has been compiled.
  75641. * @param onError Called if there is an error when compiling a shader.
  75642. */
  75643. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75644. if (defines === void 0) { defines = null; }
  75645. if (uniforms === void 0) { uniforms = null; }
  75646. if (samplers === void 0) { samplers = null; }
  75647. if (!defines) {
  75648. defines = "";
  75649. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75650. }
  75651. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75652. };
  75653. return DepthOfFieldMergePostProcess;
  75654. }(BABYLON.PostProcess));
  75655. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75656. })(BABYLON || (BABYLON = {}));
  75657. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75658. var BABYLON;
  75659. (function (BABYLON) {
  75660. /**
  75661. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75662. */
  75663. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75664. __extends(CircleOfConfusionPostProcess, _super);
  75665. /**
  75666. * Creates a new instance CircleOfConfusionPostProcess
  75667. * @param name The name of the effect.
  75668. * @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.
  75669. * @param options The required width/height ratio to downsize to before computing the render pass.
  75670. * @param camera The camera to apply the render pass to.
  75671. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75672. * @param engine The engine which the post process will be applied. (default: current engine)
  75673. * @param reusable If the post process can be reused on the same frame. (default: false)
  75674. * @param textureType Type of textures used when performing the post process. (default: 0)
  75675. * @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)
  75676. */
  75677. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75678. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75679. if (blockCompilation === void 0) { blockCompilation = false; }
  75680. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75681. /**
  75682. * 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.
  75683. */
  75684. _this.lensSize = 50;
  75685. /**
  75686. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75687. */
  75688. _this.fStop = 1.4;
  75689. /**
  75690. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75691. */
  75692. _this.focusDistance = 2000;
  75693. /**
  75694. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75695. */
  75696. _this.focalLength = 50;
  75697. _this._depthTexture = null;
  75698. _this._depthTexture = depthTexture;
  75699. _this.onApplyObservable.add(function (effect) {
  75700. if (!_this._depthTexture) {
  75701. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75702. return;
  75703. }
  75704. effect.setTexture("depthSampler", _this._depthTexture);
  75705. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75706. var aperture = _this.lensSize / _this.fStop;
  75707. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75708. effect.setFloat('focusDistance', _this.focusDistance);
  75709. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75710. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75711. });
  75712. return _this;
  75713. }
  75714. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75715. /**
  75716. * 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.
  75717. */
  75718. set: function (value) {
  75719. this._depthTexture = value;
  75720. },
  75721. enumerable: true,
  75722. configurable: true
  75723. });
  75724. return CircleOfConfusionPostProcess;
  75725. }(BABYLON.PostProcess));
  75726. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75727. })(BABYLON || (BABYLON = {}));
  75728. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75729. var BABYLON;
  75730. (function (BABYLON) {
  75731. /**
  75732. * Specifies the level of max blur that should be applied when using the depth of field effect
  75733. */
  75734. var DepthOfFieldEffectBlurLevel;
  75735. (function (DepthOfFieldEffectBlurLevel) {
  75736. /**
  75737. * Subtle blur
  75738. */
  75739. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75740. /**
  75741. * Medium blur
  75742. */
  75743. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75744. /**
  75745. * Large blur
  75746. */
  75747. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75748. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75749. ;
  75750. /**
  75751. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75752. */
  75753. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75754. __extends(DepthOfFieldEffect, _super);
  75755. /**
  75756. * Creates a new instance DepthOfFieldEffect
  75757. * @param scene The scene the effect belongs to.
  75758. * @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.
  75759. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75760. * @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)
  75761. */
  75762. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75763. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75764. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75765. if (blockCompilation === void 0) { blockCompilation = false; }
  75766. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75767. return _this._effects;
  75768. }, true) || this;
  75769. /**
  75770. * Internal post processes in depth of field effect
  75771. */
  75772. _this._effects = [];
  75773. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75774. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75775. // 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)
  75776. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75777. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75778. _this._depthOfFieldBlurY = [];
  75779. _this._depthOfFieldBlurX = [];
  75780. var blurCount = 1;
  75781. var kernelSize = 15;
  75782. switch (blurLevel) {
  75783. case DepthOfFieldEffectBlurLevel.High: {
  75784. blurCount = 3;
  75785. kernelSize = 51;
  75786. break;
  75787. }
  75788. case DepthOfFieldEffectBlurLevel.Medium: {
  75789. blurCount = 2;
  75790. kernelSize = 31;
  75791. break;
  75792. }
  75793. default: {
  75794. kernelSize = 15;
  75795. blurCount = 1;
  75796. break;
  75797. }
  75798. }
  75799. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75800. var ratio = 1.0;
  75801. for (var i = 0; i < blurCount; i++) {
  75802. 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);
  75803. blurY.autoClear = false;
  75804. ratio = 0.75 / Math.pow(2, i);
  75805. 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);
  75806. blurX.autoClear = false;
  75807. _this._depthOfFieldBlurY.push(blurY);
  75808. _this._depthOfFieldBlurX.push(blurX);
  75809. }
  75810. // Set all post processes on the effect.
  75811. _this._effects = [_this._circleOfConfusion];
  75812. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75813. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75814. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75815. }
  75816. // Merge blurred images with original image based on circleOfConfusion
  75817. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75818. _this._dofMerge.autoClear = false;
  75819. _this._effects.push(_this._dofMerge);
  75820. return _this;
  75821. }
  75822. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75823. get: function () {
  75824. return this._circleOfConfusion.focalLength;
  75825. },
  75826. /**
  75827. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75828. */
  75829. set: function (value) {
  75830. this._circleOfConfusion.focalLength = value;
  75831. },
  75832. enumerable: true,
  75833. configurable: true
  75834. });
  75835. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75836. get: function () {
  75837. return this._circleOfConfusion.fStop;
  75838. },
  75839. /**
  75840. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75841. */
  75842. set: function (value) {
  75843. this._circleOfConfusion.fStop = value;
  75844. },
  75845. enumerable: true,
  75846. configurable: true
  75847. });
  75848. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75849. get: function () {
  75850. return this._circleOfConfusion.focusDistance;
  75851. },
  75852. /**
  75853. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75854. */
  75855. set: function (value) {
  75856. this._circleOfConfusion.focusDistance = value;
  75857. },
  75858. enumerable: true,
  75859. configurable: true
  75860. });
  75861. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75862. get: function () {
  75863. return this._circleOfConfusion.lensSize;
  75864. },
  75865. /**
  75866. * 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.
  75867. */
  75868. set: function (value) {
  75869. this._circleOfConfusion.lensSize = value;
  75870. },
  75871. enumerable: true,
  75872. configurable: true
  75873. });
  75874. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75875. /**
  75876. * 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.
  75877. */
  75878. set: function (value) {
  75879. this._circleOfConfusion.depthTexture = value;
  75880. },
  75881. enumerable: true,
  75882. configurable: true
  75883. });
  75884. /**
  75885. * Disposes each of the internal effects for a given camera.
  75886. * @param camera The camera to dispose the effect on.
  75887. */
  75888. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75889. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75890. this._effects[effectIndex].dispose(camera);
  75891. }
  75892. };
  75893. /**
  75894. * Internal
  75895. */
  75896. DepthOfFieldEffect.prototype._updateEffects = function () {
  75897. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75898. this._effects[effectIndex].updateEffect();
  75899. }
  75900. };
  75901. /**
  75902. * Internal
  75903. * @returns if all the contained post processes are ready.
  75904. */
  75905. DepthOfFieldEffect.prototype._isReady = function () {
  75906. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75907. if (!this._effects[effectIndex].isReady()) {
  75908. return false;
  75909. }
  75910. }
  75911. return true;
  75912. };
  75913. return DepthOfFieldEffect;
  75914. }(BABYLON.PostProcessRenderEffect));
  75915. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75916. })(BABYLON || (BABYLON = {}));
  75917. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75918. var BABYLON;
  75919. (function (BABYLON) {
  75920. /**
  75921. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75922. */
  75923. var BloomMergePostProcess = /** @class */ (function (_super) {
  75924. __extends(BloomMergePostProcess, _super);
  75925. /**
  75926. * Creates a new instance of @see BloomMergePostProcess
  75927. * @param name The name of the effect.
  75928. * @param originalFromInput Post process which's input will be used for the merge.
  75929. * @param blurred Blurred highlights post process which's output will be used.
  75930. * @param weight Weight of the bloom to be added to the original input.
  75931. * @param options The required width/height ratio to downsize to before computing the render pass.
  75932. * @param camera The camera to apply the render pass to.
  75933. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75934. * @param engine The engine which the post process will be applied. (default: current engine)
  75935. * @param reusable If the post process can be reused on the same frame. (default: false)
  75936. * @param textureType Type of textures used when performing the post process. (default: 0)
  75937. * @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)
  75938. */
  75939. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75940. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75941. if (blockCompilation === void 0) { blockCompilation = false; }
  75942. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75943. _this.weight = weight;
  75944. _this.onApplyObservable.add(function (effect) {
  75945. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75946. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75947. effect.setFloat("bloomWeight", _this.weight);
  75948. });
  75949. if (!blockCompilation) {
  75950. _this.updateEffect();
  75951. }
  75952. return _this;
  75953. }
  75954. return BloomMergePostProcess;
  75955. }(BABYLON.PostProcess));
  75956. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75957. })(BABYLON || (BABYLON = {}));
  75958. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75959. var BABYLON;
  75960. (function (BABYLON) {
  75961. /**
  75962. * 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.
  75963. */
  75964. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75965. __extends(ExtractHighlightsPostProcess, _super);
  75966. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75967. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75968. if (blockCompilation === void 0) { blockCompilation = false; }
  75969. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75970. /**
  75971. * The luminance threshold, pixels below this value will be set to black.
  75972. */
  75973. _this.threshold = 0.9;
  75974. /**
  75975. * Internal
  75976. */
  75977. _this._exposure = 1;
  75978. /**
  75979. * Post process which has the input texture to be used when performing highlight extraction
  75980. */
  75981. _this._inputPostProcess = null;
  75982. _this.onApplyObservable.add(function (effect) {
  75983. if (_this._inputPostProcess) {
  75984. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75985. }
  75986. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75987. effect.setFloat('exposure', _this._exposure);
  75988. });
  75989. return _this;
  75990. }
  75991. return ExtractHighlightsPostProcess;
  75992. }(BABYLON.PostProcess));
  75993. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75994. })(BABYLON || (BABYLON = {}));
  75995. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75996. var BABYLON;
  75997. (function (BABYLON) {
  75998. /**
  75999. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76000. */
  76001. var BloomEffect = /** @class */ (function (_super) {
  76002. __extends(BloomEffect, _super);
  76003. /**
  76004. * Creates a new instance of @see BloomEffect
  76005. * @param scene The scene the effect belongs to.
  76006. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76007. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76008. * @param bloomWeight The the strength of bloom.
  76009. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76010. * @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)
  76011. */
  76012. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76013. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76014. if (blockCompilation === void 0) { blockCompilation = false; }
  76015. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76016. return _this._effects;
  76017. }, true) || this;
  76018. _this.bloomScale = bloomScale;
  76019. /**
  76020. * Internal
  76021. */
  76022. _this._effects = [];
  76023. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76024. _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);
  76025. _this._blurX.alwaysForcePOT = true;
  76026. _this._blurX.autoClear = false;
  76027. _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);
  76028. _this._blurY.alwaysForcePOT = true;
  76029. _this._blurY.autoClear = false;
  76030. _this.kernel = bloomKernel;
  76031. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76032. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76033. _this._merge.autoClear = false;
  76034. _this._effects.push(_this._merge);
  76035. return _this;
  76036. }
  76037. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76038. /**
  76039. * The luminance threshold to find bright areas of the image to bloom.
  76040. */
  76041. get: function () {
  76042. return this._downscale.threshold;
  76043. },
  76044. set: function (value) {
  76045. this._downscale.threshold = value;
  76046. },
  76047. enumerable: true,
  76048. configurable: true
  76049. });
  76050. Object.defineProperty(BloomEffect.prototype, "weight", {
  76051. /**
  76052. * The strength of the bloom.
  76053. */
  76054. get: function () {
  76055. return this._merge.weight;
  76056. },
  76057. set: function (value) {
  76058. this._merge.weight = value;
  76059. },
  76060. enumerable: true,
  76061. configurable: true
  76062. });
  76063. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76064. /**
  76065. * Specifies the size of the bloom blur kernel, relative to the final output size
  76066. */
  76067. get: function () {
  76068. return this._blurX.kernel / this.bloomScale;
  76069. },
  76070. set: function (value) {
  76071. this._blurX.kernel = value * this.bloomScale;
  76072. this._blurY.kernel = value * this.bloomScale;
  76073. },
  76074. enumerable: true,
  76075. configurable: true
  76076. });
  76077. /**
  76078. * Disposes each of the internal effects for a given camera.
  76079. * @param camera The camera to dispose the effect on.
  76080. */
  76081. BloomEffect.prototype.disposeEffects = function (camera) {
  76082. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76083. this._effects[effectIndex].dispose(camera);
  76084. }
  76085. };
  76086. /**
  76087. * Internal
  76088. */
  76089. BloomEffect.prototype._updateEffects = function () {
  76090. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76091. this._effects[effectIndex].updateEffect();
  76092. }
  76093. };
  76094. /**
  76095. * Internal
  76096. * @returns if all the contained post processes are ready.
  76097. */
  76098. BloomEffect.prototype._isReady = function () {
  76099. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76100. if (!this._effects[effectIndex].isReady()) {
  76101. return false;
  76102. }
  76103. }
  76104. return true;
  76105. };
  76106. return BloomEffect;
  76107. }(BABYLON.PostProcessRenderEffect));
  76108. BABYLON.BloomEffect = BloomEffect;
  76109. })(BABYLON || (BABYLON = {}));
  76110. //# sourceMappingURL=babylon.bloomEffect.js.map
  76111. var BABYLON;
  76112. (function (BABYLON) {
  76113. /**
  76114. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76115. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76116. */
  76117. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76118. __extends(DefaultRenderingPipeline, _super);
  76119. /**
  76120. * @constructor
  76121. * @param {string} name - The rendering pipeline name (default: "")
  76122. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76123. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76124. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76125. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76126. */
  76127. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76128. if (name === void 0) { name = ""; }
  76129. if (hdr === void 0) { hdr = true; }
  76130. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76131. if (automaticBuild === void 0) { automaticBuild = true; }
  76132. var _this = _super.call(this, scene.getEngine(), name) || this;
  76133. _this._originalCameras = [];
  76134. /**
  76135. * ID of the sharpen post process,
  76136. */
  76137. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76138. /**
  76139. * ID of the image processing post process;
  76140. */
  76141. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76142. /**
  76143. * ID of the Fast Approximate Anti-Aliasing post process;
  76144. */
  76145. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76146. /**
  76147. * ID of the chromatic aberration post process,
  76148. */
  76149. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76150. /**
  76151. * ID of the grain post process
  76152. */
  76153. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76154. /**
  76155. * Glow post process which adds a glow to emmisive areas of the image
  76156. */
  76157. _this._glowLayer = null;
  76158. /**
  76159. * Animations which can be used to tweak settings over a period of time
  76160. */
  76161. _this.animations = [];
  76162. _this._imageProcessingConfigurationObserver = null;
  76163. // Values
  76164. _this._sharpenEnabled = false;
  76165. _this._bloomEnabled = false;
  76166. _this._depthOfFieldEnabled = false;
  76167. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76168. _this._fxaaEnabled = false;
  76169. _this._imageProcessingEnabled = true;
  76170. _this._bloomScale = 0.5;
  76171. _this._chromaticAberrationEnabled = false;
  76172. _this._grainEnabled = false;
  76173. _this._buildAllowed = true;
  76174. _this._resizeObserver = null;
  76175. _this._hardwareScaleLevel = 1.0;
  76176. _this._bloomKernel = 64;
  76177. /**
  76178. * Specifies the weight of the bloom in the final rendering
  76179. */
  76180. _this._bloomWeight = 0.15;
  76181. /**
  76182. * Specifies the luma threshold for the area that will be blurred by the bloom
  76183. */
  76184. _this._bloomThreshold = 0.9;
  76185. _this._samples = 1;
  76186. _this._hasCleared = false;
  76187. _this._prevPostProcess = null;
  76188. _this._prevPrevPostProcess = null;
  76189. _this._cameras = cameras || scene.cameras;
  76190. _this._originalCameras = _this._cameras.slice();
  76191. _this._buildAllowed = automaticBuild;
  76192. // Initialize
  76193. _this._scene = scene;
  76194. var caps = _this._scene.getEngine().getCaps();
  76195. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76196. // Misc
  76197. if (_this._hdr) {
  76198. if (caps.textureHalfFloatRender) {
  76199. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76200. }
  76201. else if (caps.textureFloatRender) {
  76202. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76203. }
  76204. }
  76205. else {
  76206. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76207. }
  76208. // Attach
  76209. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76210. var engine = _this._scene.getEngine();
  76211. // Create post processes before hand so they can be modified before enabled.
  76212. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76213. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76214. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76215. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76216. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76217. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76218. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76219. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76220. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76221. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76222. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76223. _this.bloomKernel = _this.bloomKernel;
  76224. });
  76225. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76226. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76227. });
  76228. _this._buildPipeline();
  76229. return _this;
  76230. }
  76231. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76232. get: function () {
  76233. return this._sharpenEnabled;
  76234. },
  76235. /**
  76236. * Enable or disable the sharpen process from the pipeline
  76237. */
  76238. set: function (enabled) {
  76239. if (this._sharpenEnabled === enabled) {
  76240. return;
  76241. }
  76242. this._sharpenEnabled = enabled;
  76243. this._buildPipeline();
  76244. },
  76245. enumerable: true,
  76246. configurable: true
  76247. });
  76248. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76249. /**
  76250. * Specifies the size of the bloom blur kernel, relative to the final output size
  76251. */
  76252. get: function () {
  76253. return this._bloomKernel;
  76254. },
  76255. set: function (value) {
  76256. this._bloomKernel = value;
  76257. this.bloom.kernel = value / this._hardwareScaleLevel;
  76258. },
  76259. enumerable: true,
  76260. configurable: true
  76261. });
  76262. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76263. get: function () {
  76264. return this._bloomWeight;
  76265. },
  76266. /**
  76267. * The strength of the bloom.
  76268. */
  76269. set: function (value) {
  76270. if (this._bloomWeight === value) {
  76271. return;
  76272. }
  76273. this.bloom.weight = value;
  76274. this._bloomWeight = value;
  76275. },
  76276. enumerable: true,
  76277. configurable: true
  76278. });
  76279. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76280. get: function () {
  76281. return this._bloomThreshold;
  76282. },
  76283. /**
  76284. * The strength of the bloom.
  76285. */
  76286. set: function (value) {
  76287. if (this._bloomThreshold === value) {
  76288. return;
  76289. }
  76290. this.bloom.threshold = value;
  76291. this._bloomThreshold = value;
  76292. },
  76293. enumerable: true,
  76294. configurable: true
  76295. });
  76296. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76297. get: function () {
  76298. return this._bloomScale;
  76299. },
  76300. /**
  76301. * The scale of the bloom, lower value will provide better performance.
  76302. */
  76303. set: function (value) {
  76304. if (this._bloomScale === value) {
  76305. return;
  76306. }
  76307. this._bloomScale = value;
  76308. // recreate bloom and dispose old as this setting is not dynamic
  76309. this._rebuildBloom();
  76310. this._buildPipeline();
  76311. },
  76312. enumerable: true,
  76313. configurable: true
  76314. });
  76315. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76316. get: function () {
  76317. return this._bloomEnabled;
  76318. },
  76319. /**
  76320. * Enable or disable the bloom from the pipeline
  76321. */
  76322. set: function (enabled) {
  76323. if (this._bloomEnabled === enabled) {
  76324. return;
  76325. }
  76326. this._bloomEnabled = enabled;
  76327. this._buildPipeline();
  76328. },
  76329. enumerable: true,
  76330. configurable: true
  76331. });
  76332. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76333. // recreate bloom and dispose old as this setting is not dynamic
  76334. var oldBloom = this.bloom;
  76335. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76336. this.bloom.threshold = oldBloom.threshold;
  76337. for (var i = 0; i < this._cameras.length; i++) {
  76338. oldBloom.disposeEffects(this._cameras[i]);
  76339. }
  76340. };
  76341. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76342. /**
  76343. * If the depth of field is enabled.
  76344. */
  76345. get: function () {
  76346. return this._depthOfFieldEnabled;
  76347. },
  76348. set: function (enabled) {
  76349. if (this._depthOfFieldEnabled === enabled) {
  76350. return;
  76351. }
  76352. this._depthOfFieldEnabled = enabled;
  76353. this._buildPipeline();
  76354. },
  76355. enumerable: true,
  76356. configurable: true
  76357. });
  76358. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76359. /**
  76360. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76361. */
  76362. get: function () {
  76363. return this._depthOfFieldBlurLevel;
  76364. },
  76365. set: function (value) {
  76366. if (this._depthOfFieldBlurLevel === value) {
  76367. return;
  76368. }
  76369. this._depthOfFieldBlurLevel = value;
  76370. // recreate dof and dispose old as this setting is not dynamic
  76371. var oldDof = this.depthOfField;
  76372. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76373. this.depthOfField.focalLength = oldDof.focalLength;
  76374. this.depthOfField.focusDistance = oldDof.focusDistance;
  76375. this.depthOfField.fStop = oldDof.fStop;
  76376. this.depthOfField.lensSize = oldDof.lensSize;
  76377. for (var i = 0; i < this._cameras.length; i++) {
  76378. oldDof.disposeEffects(this._cameras[i]);
  76379. }
  76380. this._buildPipeline();
  76381. },
  76382. enumerable: true,
  76383. configurable: true
  76384. });
  76385. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76386. get: function () {
  76387. return this._fxaaEnabled;
  76388. },
  76389. /**
  76390. * If the anti aliasing is enabled.
  76391. */
  76392. set: function (enabled) {
  76393. if (this._fxaaEnabled === enabled) {
  76394. return;
  76395. }
  76396. this._fxaaEnabled = enabled;
  76397. this._buildPipeline();
  76398. },
  76399. enumerable: true,
  76400. configurable: true
  76401. });
  76402. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76403. get: function () {
  76404. return this._samples;
  76405. },
  76406. /**
  76407. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76408. */
  76409. set: function (sampleCount) {
  76410. if (this._samples === sampleCount) {
  76411. return;
  76412. }
  76413. this._samples = sampleCount;
  76414. this._buildPipeline();
  76415. },
  76416. enumerable: true,
  76417. configurable: true
  76418. });
  76419. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76420. get: function () {
  76421. return this._imageProcessingEnabled;
  76422. },
  76423. /**
  76424. * If image processing is enabled.
  76425. */
  76426. set: function (enabled) {
  76427. if (this._imageProcessingEnabled === enabled) {
  76428. return;
  76429. }
  76430. this._imageProcessingEnabled = enabled;
  76431. this._buildPipeline();
  76432. },
  76433. enumerable: true,
  76434. configurable: true
  76435. });
  76436. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76437. get: function () {
  76438. return this._glowLayer == null;
  76439. },
  76440. /**
  76441. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76442. */
  76443. set: function (enabled) {
  76444. if (enabled && !this._glowLayer) {
  76445. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76446. }
  76447. else if (!enabled && this._glowLayer) {
  76448. this._glowLayer.dispose();
  76449. this._glowLayer = null;
  76450. }
  76451. },
  76452. enumerable: true,
  76453. configurable: true
  76454. });
  76455. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76456. get: function () {
  76457. return this._chromaticAberrationEnabled;
  76458. },
  76459. /**
  76460. * Enable or disable the chromaticAberration process from the pipeline
  76461. */
  76462. set: function (enabled) {
  76463. if (this._chromaticAberrationEnabled === enabled) {
  76464. return;
  76465. }
  76466. this._chromaticAberrationEnabled = enabled;
  76467. this._buildPipeline();
  76468. },
  76469. enumerable: true,
  76470. configurable: true
  76471. });
  76472. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76473. get: function () {
  76474. return this._grainEnabled;
  76475. },
  76476. /**
  76477. * Enable or disable the grain process from the pipeline
  76478. */
  76479. set: function (enabled) {
  76480. if (this._grainEnabled === enabled) {
  76481. return;
  76482. }
  76483. this._grainEnabled = enabled;
  76484. this._buildPipeline();
  76485. },
  76486. enumerable: true,
  76487. configurable: true
  76488. });
  76489. /**
  76490. * Force the compilation of the entire pipeline.
  76491. */
  76492. DefaultRenderingPipeline.prototype.prepare = function () {
  76493. var previousState = this._buildAllowed;
  76494. this._buildAllowed = true;
  76495. this._buildPipeline();
  76496. this._buildAllowed = previousState;
  76497. };
  76498. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76499. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76500. if (this._hasCleared) {
  76501. postProcess.autoClear = false;
  76502. }
  76503. else {
  76504. postProcess.autoClear = true;
  76505. this._scene.autoClear = false;
  76506. this._hasCleared = true;
  76507. }
  76508. if (!skipTextureSharing) {
  76509. if (this._prevPrevPostProcess) {
  76510. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76511. }
  76512. else {
  76513. postProcess.useOwnOutput();
  76514. }
  76515. if (this._prevPostProcess) {
  76516. this._prevPrevPostProcess = this._prevPostProcess;
  76517. }
  76518. this._prevPostProcess = postProcess;
  76519. }
  76520. };
  76521. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76522. var _this = this;
  76523. if (!this._buildAllowed) {
  76524. return;
  76525. }
  76526. this._scene.autoClear = true;
  76527. var engine = this._scene.getEngine();
  76528. this._disposePostProcesses();
  76529. if (this._cameras !== null) {
  76530. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76531. // get back cameras to be used to reattach pipeline
  76532. this._cameras = this._originalCameras.slice();
  76533. }
  76534. this._reset();
  76535. this._prevPostProcess = null;
  76536. this._prevPrevPostProcess = null;
  76537. this._hasCleared = false;
  76538. if (this.depthOfFieldEnabled) {
  76539. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76540. this.depthOfField.depthTexture = depthTexture;
  76541. if (!this.depthOfField._isReady()) {
  76542. this.depthOfField._updateEffects();
  76543. }
  76544. this.addEffect(this.depthOfField);
  76545. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76546. }
  76547. if (this.bloomEnabled) {
  76548. if (!this.bloom._isReady()) {
  76549. this.bloom._updateEffects();
  76550. }
  76551. this.addEffect(this.bloom);
  76552. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76553. }
  76554. if (this._imageProcessingEnabled) {
  76555. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76556. if (this._hdr) {
  76557. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76558. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76559. }
  76560. else {
  76561. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76562. }
  76563. }
  76564. if (this.sharpenEnabled) {
  76565. if (!this.sharpen.isReady()) {
  76566. this.sharpen.updateEffect();
  76567. }
  76568. this.addEffect(this._sharpenEffect);
  76569. this._setAutoClearAndTextureSharing(this.sharpen);
  76570. }
  76571. if (this.grainEnabled) {
  76572. if (!this.grain.isReady()) {
  76573. this.grain.updateEffect();
  76574. }
  76575. this.addEffect(this._grainEffect);
  76576. this._setAutoClearAndTextureSharing(this.grain);
  76577. }
  76578. if (this.chromaticAberrationEnabled) {
  76579. if (!this.chromaticAberration.isReady()) {
  76580. this.chromaticAberration.updateEffect();
  76581. }
  76582. this.addEffect(this._chromaticAberrationEffect);
  76583. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76584. }
  76585. if (this.fxaaEnabled) {
  76586. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76587. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76588. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76589. }
  76590. if (this._cameras !== null) {
  76591. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76592. }
  76593. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76594. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76595. }
  76596. };
  76597. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76598. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76599. for (var i = 0; i < this._cameras.length; i++) {
  76600. var camera = this._cameras[i];
  76601. if (this.imageProcessing) {
  76602. this.imageProcessing.dispose(camera);
  76603. }
  76604. if (this.fxaa) {
  76605. this.fxaa.dispose(camera);
  76606. }
  76607. // These are created in the constructor and should not be disposed on every pipeline change
  76608. if (disposeNonRecreated) {
  76609. if (this.sharpen) {
  76610. this.sharpen.dispose(camera);
  76611. }
  76612. if (this.depthOfField) {
  76613. this.depthOfField.disposeEffects(camera);
  76614. }
  76615. if (this.bloom) {
  76616. this.bloom.disposeEffects(camera);
  76617. }
  76618. if (this.chromaticAberration) {
  76619. this.chromaticAberration.dispose(camera);
  76620. }
  76621. if (this.grain) {
  76622. this.grain.dispose(camera);
  76623. }
  76624. if (this._glowLayer) {
  76625. this._glowLayer.dispose();
  76626. }
  76627. }
  76628. }
  76629. this.imageProcessing = null;
  76630. this.fxaa = null;
  76631. if (disposeNonRecreated) {
  76632. this.sharpen = null;
  76633. this._sharpenEffect = null;
  76634. this.depthOfField = null;
  76635. this.bloom = null;
  76636. this.chromaticAberration = null;
  76637. this._chromaticAberrationEffect = null;
  76638. this.grain = null;
  76639. this._grainEffect = null;
  76640. this._glowLayer = null;
  76641. }
  76642. };
  76643. /**
  76644. * Dispose of the pipeline and stop all post processes
  76645. */
  76646. DefaultRenderingPipeline.prototype.dispose = function () {
  76647. this._disposePostProcesses(true);
  76648. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76649. this._scene.autoClear = true;
  76650. if (this._resizeObserver) {
  76651. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76652. this._resizeObserver = null;
  76653. }
  76654. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76655. _super.prototype.dispose.call(this);
  76656. };
  76657. /**
  76658. * Serialize the rendering pipeline (Used when exporting)
  76659. * @returns the serialized object
  76660. */
  76661. DefaultRenderingPipeline.prototype.serialize = function () {
  76662. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76663. serializationObject.customType = "DefaultRenderingPipeline";
  76664. return serializationObject;
  76665. };
  76666. /**
  76667. * Parse the serialized pipeline
  76668. * @param source Source pipeline.
  76669. * @param scene The scene to load the pipeline to.
  76670. * @param rootUrl The URL of the serialized pipeline.
  76671. * @returns An instantiated pipeline from the serialized object.
  76672. */
  76673. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76674. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76675. };
  76676. __decorate([
  76677. BABYLON.serialize()
  76678. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76679. __decorate([
  76680. BABYLON.serialize()
  76681. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76682. __decorate([
  76683. BABYLON.serialize()
  76684. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76685. __decorate([
  76686. BABYLON.serialize()
  76687. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76688. __decorate([
  76689. BABYLON.serialize()
  76690. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76691. __decorate([
  76692. BABYLON.serialize()
  76693. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76694. __decorate([
  76695. BABYLON.serialize()
  76696. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76697. __decorate([
  76698. BABYLON.serialize()
  76699. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76700. __decorate([
  76701. BABYLON.serialize()
  76702. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76703. __decorate([
  76704. BABYLON.serialize()
  76705. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76706. __decorate([
  76707. BABYLON.serialize()
  76708. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76709. __decorate([
  76710. BABYLON.serialize()
  76711. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76712. __decorate([
  76713. BABYLON.serialize()
  76714. ], DefaultRenderingPipeline.prototype, "samples", null);
  76715. __decorate([
  76716. BABYLON.serialize()
  76717. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76718. __decorate([
  76719. BABYLON.serialize()
  76720. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76721. __decorate([
  76722. BABYLON.serialize()
  76723. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76724. __decorate([
  76725. BABYLON.serialize()
  76726. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76727. return DefaultRenderingPipeline;
  76728. }(BABYLON.PostProcessRenderPipeline));
  76729. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76730. })(BABYLON || (BABYLON = {}));
  76731. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76732. var BABYLON;
  76733. (function (BABYLON) {
  76734. /**
  76735. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76736. */
  76737. var GeometryBufferRenderer = /** @class */ (function () {
  76738. /**
  76739. * Creates a new G Buffer for the scene
  76740. * @param scene The scene the buffer belongs to
  76741. * @param ratio How big is the buffer related to the main canvas.
  76742. */
  76743. function GeometryBufferRenderer(scene, ratio) {
  76744. if (ratio === void 0) { ratio = 1; }
  76745. this._enablePosition = false;
  76746. this._scene = scene;
  76747. this._ratio = ratio;
  76748. // Render target
  76749. this._createRenderTargets();
  76750. }
  76751. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76752. /**
  76753. * Set the render list (meshes to be rendered) used in the G buffer.
  76754. */
  76755. set: function (meshes) {
  76756. this._multiRenderTarget.renderList = meshes;
  76757. },
  76758. enumerable: true,
  76759. configurable: true
  76760. });
  76761. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76762. /**
  76763. * Gets wether or not G buffer are supported by the running hardware.
  76764. * This requires draw buffer supports
  76765. */
  76766. get: function () {
  76767. return this._multiRenderTarget.isSupported;
  76768. },
  76769. enumerable: true,
  76770. configurable: true
  76771. });
  76772. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76773. /**
  76774. * Gets wether or not position are enabled for the G buffer.
  76775. */
  76776. get: function () {
  76777. return this._enablePosition;
  76778. },
  76779. /**
  76780. * Sets wether or not position are enabled for the G buffer.
  76781. */
  76782. set: function (enable) {
  76783. this._enablePosition = enable;
  76784. this.dispose();
  76785. this._createRenderTargets();
  76786. },
  76787. enumerable: true,
  76788. configurable: true
  76789. });
  76790. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76791. /**
  76792. * Gets the scene associated with the buffer.
  76793. */
  76794. get: function () {
  76795. return this._scene;
  76796. },
  76797. enumerable: true,
  76798. configurable: true
  76799. });
  76800. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76801. /**
  76802. * Gets the ratio used by the buffer during its creation.
  76803. * How big is the buffer related to the main canvas.
  76804. */
  76805. get: function () {
  76806. return this._ratio;
  76807. },
  76808. enumerable: true,
  76809. configurable: true
  76810. });
  76811. /**
  76812. * Checks wether everything is ready to render a submesh to the G buffer.
  76813. * @param subMesh the submesh to check readiness for
  76814. * @param useInstances is the mesh drawn using instance or not
  76815. * @returns true if ready otherwise false
  76816. */
  76817. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76818. var material = subMesh.getMaterial();
  76819. if (material && material.disableDepthWrite) {
  76820. return false;
  76821. }
  76822. var defines = [];
  76823. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76824. var mesh = subMesh.getMesh();
  76825. // Alpha test
  76826. if (material && material.needAlphaTesting()) {
  76827. defines.push("#define ALPHATEST");
  76828. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76829. attribs.push(BABYLON.VertexBuffer.UVKind);
  76830. defines.push("#define UV1");
  76831. }
  76832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76833. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76834. defines.push("#define UV2");
  76835. }
  76836. }
  76837. // Buffers
  76838. if (this._enablePosition) {
  76839. defines.push("#define POSITION");
  76840. }
  76841. // Bones
  76842. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76843. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76844. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76845. if (mesh.numBoneInfluencers > 4) {
  76846. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76847. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76848. }
  76849. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76850. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76851. }
  76852. else {
  76853. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76854. }
  76855. // Instances
  76856. if (useInstances) {
  76857. defines.push("#define INSTANCES");
  76858. attribs.push("world0");
  76859. attribs.push("world1");
  76860. attribs.push("world2");
  76861. attribs.push("world3");
  76862. }
  76863. // Get correct effect
  76864. var join = defines.join("\n");
  76865. if (this._cachedDefines !== join) {
  76866. this._cachedDefines = join;
  76867. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76868. }
  76869. return this._effect.isReady();
  76870. };
  76871. /**
  76872. * Gets the current underlying G Buffer.
  76873. * @returns the buffer
  76874. */
  76875. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76876. return this._multiRenderTarget;
  76877. };
  76878. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76879. /**
  76880. * Gets the number of samples used to render the buffer (anti aliasing).
  76881. */
  76882. get: function () {
  76883. return this._multiRenderTarget.samples;
  76884. },
  76885. /**
  76886. * Sets the number of samples used to render the buffer (anti aliasing).
  76887. */
  76888. set: function (value) {
  76889. this._multiRenderTarget.samples = value;
  76890. },
  76891. enumerable: true,
  76892. configurable: true
  76893. });
  76894. /**
  76895. * Disposes the renderer and frees up associated resources.
  76896. */
  76897. GeometryBufferRenderer.prototype.dispose = function () {
  76898. this.getGBuffer().dispose();
  76899. };
  76900. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76901. var _this = this;
  76902. var engine = this._scene.getEngine();
  76903. var count = this._enablePosition ? 3 : 2;
  76904. 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 });
  76905. if (!this.isSupported) {
  76906. return;
  76907. }
  76908. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76909. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76910. this._multiRenderTarget.refreshRate = 1;
  76911. this._multiRenderTarget.renderParticles = false;
  76912. this._multiRenderTarget.renderList = null;
  76913. // set default depth value to 1.0 (far away)
  76914. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76915. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76916. });
  76917. // Custom render function
  76918. var renderSubMesh = function (subMesh) {
  76919. var mesh = subMesh.getRenderingMesh();
  76920. var scene = _this._scene;
  76921. var engine = scene.getEngine();
  76922. var material = subMesh.getMaterial();
  76923. if (!material) {
  76924. return;
  76925. }
  76926. // Culling
  76927. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76928. // Managing instances
  76929. var batch = mesh._getInstancesRenderList(subMesh._id);
  76930. if (batch.mustReturn) {
  76931. return;
  76932. }
  76933. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76934. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76935. engine.enableEffect(_this._effect);
  76936. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76937. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76938. _this._effect.setMatrix("view", scene.getViewMatrix());
  76939. // Alpha test
  76940. if (material && material.needAlphaTesting()) {
  76941. var alphaTexture = material.getAlphaTestTexture();
  76942. if (alphaTexture) {
  76943. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76944. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76945. }
  76946. }
  76947. // Bones
  76948. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76949. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76950. }
  76951. // Draw
  76952. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76953. }
  76954. };
  76955. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76956. var index;
  76957. if (depthOnlySubMeshes.length) {
  76958. engine.setColorWrite(false);
  76959. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76960. renderSubMesh(depthOnlySubMeshes.data[index]);
  76961. }
  76962. engine.setColorWrite(true);
  76963. }
  76964. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76965. renderSubMesh(opaqueSubMeshes.data[index]);
  76966. }
  76967. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76968. renderSubMesh(alphaTestSubMeshes.data[index]);
  76969. }
  76970. };
  76971. };
  76972. return GeometryBufferRenderer;
  76973. }());
  76974. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76975. })(BABYLON || (BABYLON = {}));
  76976. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76977. var BABYLON;
  76978. (function (BABYLON) {
  76979. var RefractionPostProcess = /** @class */ (function (_super) {
  76980. __extends(RefractionPostProcess, _super);
  76981. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76982. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76983. _this.color = color;
  76984. _this.depth = depth;
  76985. _this.colorLevel = colorLevel;
  76986. _this._ownRefractionTexture = true;
  76987. _this.onActivateObservable.add(function (cam) {
  76988. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76989. });
  76990. _this.onApplyObservable.add(function (effect) {
  76991. effect.setColor3("baseColor", _this.color);
  76992. effect.setFloat("depth", _this.depth);
  76993. effect.setFloat("colorLevel", _this.colorLevel);
  76994. effect.setTexture("refractionSampler", _this._refTexture);
  76995. });
  76996. return _this;
  76997. }
  76998. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76999. /**
  77000. * Gets or sets the refraction texture
  77001. * Please note that you are responsible for disposing the texture if you set it manually
  77002. */
  77003. get: function () {
  77004. return this._refTexture;
  77005. },
  77006. set: function (value) {
  77007. if (this._refTexture && this._ownRefractionTexture) {
  77008. this._refTexture.dispose();
  77009. }
  77010. this._refTexture = value;
  77011. this._ownRefractionTexture = false;
  77012. },
  77013. enumerable: true,
  77014. configurable: true
  77015. });
  77016. // Methods
  77017. RefractionPostProcess.prototype.dispose = function (camera) {
  77018. if (this._refTexture && this._ownRefractionTexture) {
  77019. this._refTexture.dispose();
  77020. this._refTexture = null;
  77021. }
  77022. _super.prototype.dispose.call(this, camera);
  77023. };
  77024. return RefractionPostProcess;
  77025. }(BABYLON.PostProcess));
  77026. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77027. })(BABYLON || (BABYLON = {}));
  77028. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77029. var BABYLON;
  77030. (function (BABYLON) {
  77031. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77032. __extends(BlackAndWhitePostProcess, _super);
  77033. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77034. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77035. _this.degree = 1;
  77036. _this.onApplyObservable.add(function (effect) {
  77037. effect.setFloat("degree", _this.degree);
  77038. });
  77039. return _this;
  77040. }
  77041. return BlackAndWhitePostProcess;
  77042. }(BABYLON.PostProcess));
  77043. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77044. })(BABYLON || (BABYLON = {}));
  77045. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77046. var BABYLON;
  77047. (function (BABYLON) {
  77048. /**
  77049. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77050. * input texture to perform effects such as edge detection or sharpening
  77051. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77052. */
  77053. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77054. __extends(ConvolutionPostProcess, _super);
  77055. /**
  77056. * Creates a new instance ConvolutionPostProcess
  77057. * @param name The name of the effect.
  77058. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77059. * @param options The required width/height ratio to downsize to before computing the render pass.
  77060. * @param camera The camera to apply the render pass to.
  77061. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77062. * @param engine The engine which the post process will be applied. (default: current engine)
  77063. * @param reusable If the post process can be reused on the same frame. (default: false)
  77064. * @param textureType Type of textures used when performing the post process. (default: 0)
  77065. */
  77066. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77067. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77068. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77069. _this.kernel = kernel;
  77070. _this.onApply = function (effect) {
  77071. effect.setFloat2("screenSize", _this.width, _this.height);
  77072. effect.setArray("kernel", _this.kernel);
  77073. };
  77074. return _this;
  77075. }
  77076. // Statics
  77077. /**
  77078. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77079. */
  77080. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77081. /**
  77082. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77083. */
  77084. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77085. /**
  77086. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77087. */
  77088. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77089. /**
  77090. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77091. */
  77092. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77093. /**
  77094. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77095. */
  77096. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77097. /**
  77098. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77099. */
  77100. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77101. return ConvolutionPostProcess;
  77102. }(BABYLON.PostProcess));
  77103. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77104. })(BABYLON || (BABYLON = {}));
  77105. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77106. var BABYLON;
  77107. (function (BABYLON) {
  77108. var FilterPostProcess = /** @class */ (function (_super) {
  77109. __extends(FilterPostProcess, _super);
  77110. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77111. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77112. _this.kernelMatrix = kernelMatrix;
  77113. _this.onApply = function (effect) {
  77114. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77115. };
  77116. return _this;
  77117. }
  77118. return FilterPostProcess;
  77119. }(BABYLON.PostProcess));
  77120. BABYLON.FilterPostProcess = FilterPostProcess;
  77121. })(BABYLON || (BABYLON = {}));
  77122. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77123. var BABYLON;
  77124. (function (BABYLON) {
  77125. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77126. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77127. __extends(VolumetricLightScatteringPostProcess, _super);
  77128. /**
  77129. * @constructor
  77130. * @param {string} name - The post-process name
  77131. * @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)
  77132. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77133. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77134. * @param {number} samples - The post-process quality, default 100
  77135. * @param {number} samplingMode - The post-process filtering mode
  77136. * @param {BABYLON.Engine} engine - The babylon engine
  77137. * @param {boolean} reusable - If the post-process is reusable
  77138. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77139. */
  77140. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77141. if (samples === void 0) { samples = 100; }
  77142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77143. 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;
  77144. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77145. /**
  77146. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77147. */
  77148. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77149. /**
  77150. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77151. */
  77152. _this.useCustomMeshPosition = false;
  77153. /**
  77154. * If the post-process should inverse the light scattering direction
  77155. */
  77156. _this.invert = true;
  77157. /**
  77158. * Array containing the excluded meshes not rendered in the internal pass
  77159. */
  77160. _this.excludedMeshes = new Array();
  77161. /**
  77162. * Controls the overall intensity of the post-process
  77163. */
  77164. _this.exposure = 0.3;
  77165. /**
  77166. * Dissipates each sample's contribution in range [0, 1]
  77167. */
  77168. _this.decay = 0.96815;
  77169. /**
  77170. * Controls the overall intensity of each sample
  77171. */
  77172. _this.weight = 0.58767;
  77173. /**
  77174. * Controls the density of each sample
  77175. */
  77176. _this.density = 0.926;
  77177. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77178. engine = scene.getEngine();
  77179. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77180. // Configure mesh
  77181. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77182. // Configure
  77183. _this._createPass(scene, ratio.passRatio || ratio);
  77184. _this.onActivate = function (camera) {
  77185. if (!_this.isSupported) {
  77186. _this.dispose(camera);
  77187. }
  77188. _this.onActivate = null;
  77189. };
  77190. _this.onApplyObservable.add(function (effect) {
  77191. _this._updateMeshScreenCoordinates(scene);
  77192. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77193. effect.setFloat("exposure", _this.exposure);
  77194. effect.setFloat("decay", _this.decay);
  77195. effect.setFloat("weight", _this.weight);
  77196. effect.setFloat("density", _this.density);
  77197. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77198. });
  77199. return _this;
  77200. }
  77201. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77202. get: function () {
  77203. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77204. return false;
  77205. },
  77206. set: function (useDiffuseColor) {
  77207. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77208. },
  77209. enumerable: true,
  77210. configurable: true
  77211. });
  77212. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77213. return "VolumetricLightScatteringPostProcess";
  77214. };
  77215. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77216. var mesh = subMesh.getMesh();
  77217. // Render this.mesh as default
  77218. if (mesh === this.mesh && mesh.material) {
  77219. return mesh.material.isReady(mesh);
  77220. }
  77221. var defines = [];
  77222. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77223. var material = subMesh.getMaterial();
  77224. // Alpha test
  77225. if (material) {
  77226. if (material.needAlphaTesting()) {
  77227. defines.push("#define ALPHATEST");
  77228. }
  77229. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77230. attribs.push(BABYLON.VertexBuffer.UVKind);
  77231. defines.push("#define UV1");
  77232. }
  77233. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77234. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77235. defines.push("#define UV2");
  77236. }
  77237. }
  77238. // Bones
  77239. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77240. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77241. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77242. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77243. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77244. }
  77245. else {
  77246. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77247. }
  77248. // Instances
  77249. if (useInstances) {
  77250. defines.push("#define INSTANCES");
  77251. attribs.push("world0");
  77252. attribs.push("world1");
  77253. attribs.push("world2");
  77254. attribs.push("world3");
  77255. }
  77256. // Get correct effect
  77257. var join = defines.join("\n");
  77258. if (this._cachedDefines !== join) {
  77259. this._cachedDefines = join;
  77260. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77261. }
  77262. return this._volumetricLightScatteringPass.isReady();
  77263. };
  77264. /**
  77265. * Sets the new light position for light scattering effect
  77266. * @param {BABYLON.Vector3} The new custom light position
  77267. */
  77268. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77269. this.customMeshPosition = position;
  77270. };
  77271. /**
  77272. * Returns the light position for light scattering effect
  77273. * @return {BABYLON.Vector3} The custom light position
  77274. */
  77275. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77276. return this.customMeshPosition;
  77277. };
  77278. /**
  77279. * Disposes the internal assets and detaches the post-process from the camera
  77280. */
  77281. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77282. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77283. if (rttIndex !== -1) {
  77284. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77285. }
  77286. this._volumetricLightScatteringRTT.dispose();
  77287. _super.prototype.dispose.call(this, camera);
  77288. };
  77289. /**
  77290. * Returns the render target texture used by the post-process
  77291. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77292. */
  77293. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77294. return this._volumetricLightScatteringRTT;
  77295. };
  77296. // Private methods
  77297. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77298. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77299. return true;
  77300. }
  77301. return false;
  77302. };
  77303. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77304. var _this = this;
  77305. var engine = scene.getEngine();
  77306. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77307. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77308. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77309. this._volumetricLightScatteringRTT.renderList = null;
  77310. this._volumetricLightScatteringRTT.renderParticles = false;
  77311. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77312. var camera = this.getCamera();
  77313. if (camera) {
  77314. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77315. }
  77316. else {
  77317. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77318. }
  77319. // Custom render function for submeshes
  77320. var renderSubMesh = function (subMesh) {
  77321. var mesh = subMesh.getRenderingMesh();
  77322. if (_this._meshExcluded(mesh)) {
  77323. return;
  77324. }
  77325. var material = subMesh.getMaterial();
  77326. if (!material) {
  77327. return;
  77328. }
  77329. var scene = mesh.getScene();
  77330. var engine = scene.getEngine();
  77331. // Culling
  77332. engine.setState(material.backFaceCulling);
  77333. // Managing instances
  77334. var batch = mesh._getInstancesRenderList(subMesh._id);
  77335. if (batch.mustReturn) {
  77336. return;
  77337. }
  77338. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77339. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77340. var effect = _this._volumetricLightScatteringPass;
  77341. if (mesh === _this.mesh) {
  77342. if (subMesh.effect) {
  77343. effect = subMesh.effect;
  77344. }
  77345. else {
  77346. effect = material.getEffect();
  77347. }
  77348. }
  77349. engine.enableEffect(effect);
  77350. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77351. if (mesh === _this.mesh) {
  77352. material.bind(mesh.getWorldMatrix(), mesh);
  77353. }
  77354. else {
  77355. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77356. // Alpha test
  77357. if (material && material.needAlphaTesting()) {
  77358. var alphaTexture = material.getAlphaTestTexture();
  77359. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77360. if (alphaTexture) {
  77361. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77362. }
  77363. }
  77364. // Bones
  77365. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77366. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77367. }
  77368. }
  77369. // Draw
  77370. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77371. }
  77372. };
  77373. // Render target texture callbacks
  77374. var savedSceneClearColor;
  77375. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77376. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77377. savedSceneClearColor = scene.clearColor;
  77378. scene.clearColor = sceneClearColor;
  77379. });
  77380. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77381. scene.clearColor = savedSceneClearColor;
  77382. });
  77383. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77384. var engine = scene.getEngine();
  77385. var index;
  77386. if (depthOnlySubMeshes.length) {
  77387. engine.setColorWrite(false);
  77388. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77389. renderSubMesh(depthOnlySubMeshes.data[index]);
  77390. }
  77391. engine.setColorWrite(true);
  77392. }
  77393. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77394. renderSubMesh(opaqueSubMeshes.data[index]);
  77395. }
  77396. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77397. renderSubMesh(alphaTestSubMeshes.data[index]);
  77398. }
  77399. if (transparentSubMeshes.length) {
  77400. // Sort sub meshes
  77401. for (index = 0; index < transparentSubMeshes.length; index++) {
  77402. var submesh = transparentSubMeshes.data[index];
  77403. var boundingInfo = submesh.getBoundingInfo();
  77404. if (boundingInfo && scene.activeCamera) {
  77405. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77406. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77407. }
  77408. }
  77409. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77410. sortedArray.sort(function (a, b) {
  77411. // Alpha index first
  77412. if (a._alphaIndex > b._alphaIndex) {
  77413. return 1;
  77414. }
  77415. if (a._alphaIndex < b._alphaIndex) {
  77416. return -1;
  77417. }
  77418. // Then distance to camera
  77419. if (a._distanceToCamera < b._distanceToCamera) {
  77420. return 1;
  77421. }
  77422. if (a._distanceToCamera > b._distanceToCamera) {
  77423. return -1;
  77424. }
  77425. return 0;
  77426. });
  77427. // Render sub meshes
  77428. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77429. for (index = 0; index < sortedArray.length; index++) {
  77430. renderSubMesh(sortedArray[index]);
  77431. }
  77432. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77433. }
  77434. };
  77435. };
  77436. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77437. var transform = scene.getTransformMatrix();
  77438. var meshPosition;
  77439. if (this.useCustomMeshPosition) {
  77440. meshPosition = this.customMeshPosition;
  77441. }
  77442. else if (this.attachedNode) {
  77443. meshPosition = this.attachedNode.position;
  77444. }
  77445. else {
  77446. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77447. }
  77448. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77449. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77450. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77451. if (this.invert)
  77452. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77453. };
  77454. // Static methods
  77455. /**
  77456. * Creates a default mesh for the Volumeric Light Scattering post-process
  77457. * @param {string} The mesh name
  77458. * @param {BABYLON.Scene} The scene where to create the mesh
  77459. * @return {BABYLON.Mesh} the default mesh
  77460. */
  77461. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77462. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77463. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77464. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77465. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77466. mesh.material = material;
  77467. return mesh;
  77468. };
  77469. __decorate([
  77470. BABYLON.serializeAsVector3()
  77471. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77472. __decorate([
  77473. BABYLON.serialize()
  77474. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77475. __decorate([
  77476. BABYLON.serialize()
  77477. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77478. __decorate([
  77479. BABYLON.serializeAsMeshReference()
  77480. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77481. __decorate([
  77482. BABYLON.serialize()
  77483. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77484. __decorate([
  77485. BABYLON.serialize()
  77486. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77487. __decorate([
  77488. BABYLON.serialize()
  77489. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77490. __decorate([
  77491. BABYLON.serialize()
  77492. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77493. __decorate([
  77494. BABYLON.serialize()
  77495. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77496. return VolumetricLightScatteringPostProcess;
  77497. }(BABYLON.PostProcess));
  77498. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77499. })(BABYLON || (BABYLON = {}));
  77500. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77501. //
  77502. // This post-process allows the modification of rendered colors by using
  77503. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77504. //
  77505. // The object needs to be provided an url to a texture containing the color
  77506. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77507. // Use an image editing software to tweak the LUT to match your needs.
  77508. //
  77509. // For an example of a color LUT, see here:
  77510. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77511. // For explanations on color grading, see here:
  77512. // http://udn.epicgames.com/Three/ColorGrading.html
  77513. //
  77514. var BABYLON;
  77515. (function (BABYLON) {
  77516. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77517. __extends(ColorCorrectionPostProcess, _super);
  77518. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77519. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77520. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77521. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77522. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77523. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77524. _this.onApply = function (effect) {
  77525. effect.setTexture("colorTable", _this._colorTableTexture);
  77526. };
  77527. return _this;
  77528. }
  77529. return ColorCorrectionPostProcess;
  77530. }(BABYLON.PostProcess));
  77531. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77532. })(BABYLON || (BABYLON = {}));
  77533. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77534. var BABYLON;
  77535. (function (BABYLON) {
  77536. /** Defines operator used for tonemapping */
  77537. var TonemappingOperator;
  77538. (function (TonemappingOperator) {
  77539. /** Hable */
  77540. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77541. /** Reinhard */
  77542. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77543. /** HejiDawson */
  77544. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77545. /** Photographic */
  77546. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77547. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77548. ;
  77549. /**
  77550. * Defines a post process to apply tone mapping
  77551. */
  77552. var TonemapPostProcess = /** @class */ (function (_super) {
  77553. __extends(TonemapPostProcess, _super);
  77554. /**
  77555. * Creates a new TonemapPostProcess
  77556. * @param name defines the name of the postprocess
  77557. * @param _operator defines the operator to use
  77558. * @param exposureAdjustment defines the required exposure adjustement
  77559. * @param camera defines the camera to use (can be null)
  77560. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77561. * @param engine defines the hosting engine (can be ignore if camera is set)
  77562. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77563. */
  77564. function TonemapPostProcess(name, _operator,
  77565. /** Defines the required exposure adjustement */
  77566. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77567. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77568. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77569. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77570. _this._operator = _operator;
  77571. _this.exposureAdjustment = exposureAdjustment;
  77572. var defines = "#define ";
  77573. if (_this._operator === TonemappingOperator.Hable)
  77574. defines += "HABLE_TONEMAPPING";
  77575. else if (_this._operator === TonemappingOperator.Reinhard)
  77576. defines += "REINHARD_TONEMAPPING";
  77577. else if (_this._operator === TonemappingOperator.HejiDawson)
  77578. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77579. else if (_this._operator === TonemappingOperator.Photographic)
  77580. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77581. //sadly a second call to create the effect.
  77582. _this.updateEffect(defines);
  77583. _this.onApply = function (effect) {
  77584. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77585. };
  77586. return _this;
  77587. }
  77588. return TonemapPostProcess;
  77589. }(BABYLON.PostProcess));
  77590. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77591. })(BABYLON || (BABYLON = {}));
  77592. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77593. var BABYLON;
  77594. (function (BABYLON) {
  77595. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77596. __extends(DisplayPassPostProcess, _super);
  77597. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77598. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77599. }
  77600. return DisplayPassPostProcess;
  77601. }(BABYLON.PostProcess));
  77602. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77603. })(BABYLON || (BABYLON = {}));
  77604. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77605. var BABYLON;
  77606. (function (BABYLON) {
  77607. var HighlightsPostProcess = /** @class */ (function (_super) {
  77608. __extends(HighlightsPostProcess, _super);
  77609. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77610. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77611. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77612. }
  77613. return HighlightsPostProcess;
  77614. }(BABYLON.PostProcess));
  77615. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77616. })(BABYLON || (BABYLON = {}));
  77617. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77618. var BABYLON;
  77619. (function (BABYLON) {
  77620. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77621. __extends(ImageProcessingPostProcess, _super);
  77622. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77623. if (camera === void 0) { camera = null; }
  77624. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77625. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77626. _this._fromLinearSpace = true;
  77627. /**
  77628. * Defines cache preventing GC.
  77629. */
  77630. _this._defines = {
  77631. IMAGEPROCESSING: false,
  77632. VIGNETTE: false,
  77633. VIGNETTEBLENDMODEMULTIPLY: false,
  77634. VIGNETTEBLENDMODEOPAQUE: false,
  77635. TONEMAPPING: false,
  77636. CONTRAST: false,
  77637. COLORCURVES: false,
  77638. COLORGRADING: false,
  77639. COLORGRADING3D: false,
  77640. FROMLINEARSPACE: false,
  77641. SAMPLER3DGREENDEPTH: false,
  77642. SAMPLER3DBGRMAP: false,
  77643. IMAGEPROCESSINGPOSTPROCESS: false,
  77644. EXPOSURE: false,
  77645. };
  77646. // Setup the configuration as forced by the constructor. This would then not force the
  77647. // scene materials output in linear space and let untouched the default forward pass.
  77648. if (imageProcessingConfiguration) {
  77649. imageProcessingConfiguration.applyByPostProcess = true;
  77650. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77651. // This will cause the shader to be compiled
  77652. _this.fromLinearSpace = false;
  77653. }
  77654. // Setup the default processing configuration to the scene.
  77655. else {
  77656. _this._attachImageProcessingConfiguration(null, true);
  77657. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77658. }
  77659. _this.onApply = function (effect) {
  77660. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77661. };
  77662. return _this;
  77663. }
  77664. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77665. /**
  77666. * Gets the image processing configuration used either in this material.
  77667. */
  77668. get: function () {
  77669. return this._imageProcessingConfiguration;
  77670. },
  77671. /**
  77672. * Sets the Default image processing configuration used either in the this material.
  77673. *
  77674. * If sets to null, the scene one is in use.
  77675. */
  77676. set: function (value) {
  77677. this._attachImageProcessingConfiguration(value);
  77678. },
  77679. enumerable: true,
  77680. configurable: true
  77681. });
  77682. /**
  77683. * Attaches a new image processing configuration to the PBR Material.
  77684. * @param configuration
  77685. */
  77686. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77687. var _this = this;
  77688. if (doNotBuild === void 0) { doNotBuild = false; }
  77689. if (configuration === this._imageProcessingConfiguration) {
  77690. return;
  77691. }
  77692. // Detaches observer.
  77693. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77694. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77695. }
  77696. // Pick the scene configuration if needed.
  77697. if (!configuration) {
  77698. var scene = null;
  77699. var engine = this.getEngine();
  77700. var camera = this.getCamera();
  77701. if (camera) {
  77702. scene = camera.getScene();
  77703. }
  77704. else if (engine && engine.scenes) {
  77705. var scenes = engine.scenes;
  77706. scene = scenes[scenes.length - 1];
  77707. }
  77708. else {
  77709. scene = BABYLON.Engine.LastCreatedScene;
  77710. }
  77711. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77712. }
  77713. else {
  77714. this._imageProcessingConfiguration = configuration;
  77715. }
  77716. // Attaches observer.
  77717. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77718. _this._updateParameters();
  77719. });
  77720. // Ensure the effect will be rebuilt.
  77721. if (!doNotBuild) {
  77722. this._updateParameters();
  77723. }
  77724. };
  77725. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77726. /**
  77727. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77728. */
  77729. get: function () {
  77730. return this.imageProcessingConfiguration.colorCurves;
  77731. },
  77732. /**
  77733. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77734. */
  77735. set: function (value) {
  77736. this.imageProcessingConfiguration.colorCurves = value;
  77737. },
  77738. enumerable: true,
  77739. configurable: true
  77740. });
  77741. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77742. /**
  77743. * Gets wether the color curves effect is enabled.
  77744. */
  77745. get: function () {
  77746. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77747. },
  77748. /**
  77749. * Sets wether the color curves effect is enabled.
  77750. */
  77751. set: function (value) {
  77752. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77753. },
  77754. enumerable: true,
  77755. configurable: true
  77756. });
  77757. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77758. /**
  77759. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77760. */
  77761. get: function () {
  77762. return this.imageProcessingConfiguration.colorGradingTexture;
  77763. },
  77764. /**
  77765. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77766. */
  77767. set: function (value) {
  77768. this.imageProcessingConfiguration.colorGradingTexture = value;
  77769. },
  77770. enumerable: true,
  77771. configurable: true
  77772. });
  77773. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77774. /**
  77775. * Gets wether the color grading effect is enabled.
  77776. */
  77777. get: function () {
  77778. return this.imageProcessingConfiguration.colorGradingEnabled;
  77779. },
  77780. /**
  77781. * Gets wether the color grading effect is enabled.
  77782. */
  77783. set: function (value) {
  77784. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77785. },
  77786. enumerable: true,
  77787. configurable: true
  77788. });
  77789. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77790. /**
  77791. * Gets exposure used in the effect.
  77792. */
  77793. get: function () {
  77794. return this.imageProcessingConfiguration.exposure;
  77795. },
  77796. /**
  77797. * Sets exposure used in the effect.
  77798. */
  77799. set: function (value) {
  77800. this.imageProcessingConfiguration.exposure = value;
  77801. },
  77802. enumerable: true,
  77803. configurable: true
  77804. });
  77805. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77806. /**
  77807. * Gets wether tonemapping is enabled or not.
  77808. */
  77809. get: function () {
  77810. return this._imageProcessingConfiguration.toneMappingEnabled;
  77811. },
  77812. /**
  77813. * Sets wether tonemapping is enabled or not
  77814. */
  77815. set: function (value) {
  77816. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77817. },
  77818. enumerable: true,
  77819. configurable: true
  77820. });
  77821. ;
  77822. ;
  77823. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77824. /**
  77825. * Gets contrast used in the effect.
  77826. */
  77827. get: function () {
  77828. return this.imageProcessingConfiguration.contrast;
  77829. },
  77830. /**
  77831. * Sets contrast used in the effect.
  77832. */
  77833. set: function (value) {
  77834. this.imageProcessingConfiguration.contrast = value;
  77835. },
  77836. enumerable: true,
  77837. configurable: true
  77838. });
  77839. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77840. /**
  77841. * Gets Vignette stretch size.
  77842. */
  77843. get: function () {
  77844. return this.imageProcessingConfiguration.vignetteStretch;
  77845. },
  77846. /**
  77847. * Sets Vignette stretch size.
  77848. */
  77849. set: function (value) {
  77850. this.imageProcessingConfiguration.vignetteStretch = value;
  77851. },
  77852. enumerable: true,
  77853. configurable: true
  77854. });
  77855. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77856. /**
  77857. * Gets Vignette centre X Offset.
  77858. */
  77859. get: function () {
  77860. return this.imageProcessingConfiguration.vignetteCentreX;
  77861. },
  77862. /**
  77863. * Sets Vignette centre X Offset.
  77864. */
  77865. set: function (value) {
  77866. this.imageProcessingConfiguration.vignetteCentreX = value;
  77867. },
  77868. enumerable: true,
  77869. configurable: true
  77870. });
  77871. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77872. /**
  77873. * Gets Vignette centre Y Offset.
  77874. */
  77875. get: function () {
  77876. return this.imageProcessingConfiguration.vignetteCentreY;
  77877. },
  77878. /**
  77879. * Sets Vignette centre Y Offset.
  77880. */
  77881. set: function (value) {
  77882. this.imageProcessingConfiguration.vignetteCentreY = value;
  77883. },
  77884. enumerable: true,
  77885. configurable: true
  77886. });
  77887. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77888. /**
  77889. * Gets Vignette weight or intensity of the vignette effect.
  77890. */
  77891. get: function () {
  77892. return this.imageProcessingConfiguration.vignetteWeight;
  77893. },
  77894. /**
  77895. * Sets Vignette weight or intensity of the vignette effect.
  77896. */
  77897. set: function (value) {
  77898. this.imageProcessingConfiguration.vignetteWeight = value;
  77899. },
  77900. enumerable: true,
  77901. configurable: true
  77902. });
  77903. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77904. /**
  77905. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77906. * if vignetteEnabled is set to true.
  77907. */
  77908. get: function () {
  77909. return this.imageProcessingConfiguration.vignetteColor;
  77910. },
  77911. /**
  77912. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77913. * if vignetteEnabled is set to true.
  77914. */
  77915. set: function (value) {
  77916. this.imageProcessingConfiguration.vignetteColor = value;
  77917. },
  77918. enumerable: true,
  77919. configurable: true
  77920. });
  77921. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77922. /**
  77923. * Gets Camera field of view used by the Vignette effect.
  77924. */
  77925. get: function () {
  77926. return this.imageProcessingConfiguration.vignetteCameraFov;
  77927. },
  77928. /**
  77929. * Sets Camera field of view used by the Vignette effect.
  77930. */
  77931. set: function (value) {
  77932. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77933. },
  77934. enumerable: true,
  77935. configurable: true
  77936. });
  77937. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77938. /**
  77939. * Gets the vignette blend mode allowing different kind of effect.
  77940. */
  77941. get: function () {
  77942. return this.imageProcessingConfiguration.vignetteBlendMode;
  77943. },
  77944. /**
  77945. * Sets the vignette blend mode allowing different kind of effect.
  77946. */
  77947. set: function (value) {
  77948. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77949. },
  77950. enumerable: true,
  77951. configurable: true
  77952. });
  77953. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77954. /**
  77955. * Gets wether the vignette effect is enabled.
  77956. */
  77957. get: function () {
  77958. return this.imageProcessingConfiguration.vignetteEnabled;
  77959. },
  77960. /**
  77961. * Sets wether the vignette effect is enabled.
  77962. */
  77963. set: function (value) {
  77964. this.imageProcessingConfiguration.vignetteEnabled = value;
  77965. },
  77966. enumerable: true,
  77967. configurable: true
  77968. });
  77969. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77970. /**
  77971. * Gets wether the input of the processing is in Gamma or Linear Space.
  77972. */
  77973. get: function () {
  77974. return this._fromLinearSpace;
  77975. },
  77976. /**
  77977. * Sets wether the input of the processing is in Gamma or Linear Space.
  77978. */
  77979. set: function (value) {
  77980. if (this._fromLinearSpace === value) {
  77981. return;
  77982. }
  77983. this._fromLinearSpace = value;
  77984. this._updateParameters();
  77985. },
  77986. enumerable: true,
  77987. configurable: true
  77988. });
  77989. ImageProcessingPostProcess.prototype.getClassName = function () {
  77990. return "ImageProcessingPostProcess";
  77991. };
  77992. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77993. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77994. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77995. var defines = "";
  77996. for (var define in this._defines) {
  77997. if (this._defines[define]) {
  77998. defines += "#define " + define + ";\r\n";
  77999. }
  78000. }
  78001. var samplers = ["textureSampler"];
  78002. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78003. var uniforms = ["scale"];
  78004. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78005. this.updateEffect(defines, uniforms, samplers);
  78006. };
  78007. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78008. _super.prototype.dispose.call(this, camera);
  78009. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78010. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78011. }
  78012. this.imageProcessingConfiguration.applyByPostProcess = false;
  78013. };
  78014. __decorate([
  78015. BABYLON.serialize()
  78016. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78017. return ImageProcessingPostProcess;
  78018. }(BABYLON.PostProcess));
  78019. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78020. })(BABYLON || (BABYLON = {}));
  78021. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78022. var BABYLON;
  78023. (function (BABYLON) {
  78024. /**
  78025. * Class used to store bone information
  78026. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78027. */
  78028. var Bone = /** @class */ (function (_super) {
  78029. __extends(Bone, _super);
  78030. /**
  78031. * Create a new bone
  78032. * @param name defines the bone name
  78033. * @param skeleton defines the parent skeleton
  78034. * @param parentBone defines the parent (can be null if the bone is the root)
  78035. * @param localMatrix defines the local matrix
  78036. * @param restPose defines the rest pose matrix
  78037. * @param baseMatrix defines the base matrix
  78038. * @param index defines index of the bone in the hiearchy
  78039. */
  78040. function Bone(
  78041. /**
  78042. * defines the bone name
  78043. */
  78044. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78045. if (parentBone === void 0) { parentBone = null; }
  78046. if (localMatrix === void 0) { localMatrix = null; }
  78047. if (restPose === void 0) { restPose = null; }
  78048. if (baseMatrix === void 0) { baseMatrix = null; }
  78049. if (index === void 0) { index = null; }
  78050. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78051. _this.name = name;
  78052. /**
  78053. * Gets the list of child bones
  78054. */
  78055. _this.children = new Array();
  78056. /** Gets the animations associated with this bone */
  78057. _this.animations = new Array();
  78058. /**
  78059. * @hidden Internal only
  78060. * Set this value to map this bone to a different index in the transform matrices
  78061. * Set this value to -1 to exclude the bone from the transform matrices
  78062. */
  78063. _this._index = null;
  78064. _this._absoluteTransform = new BABYLON.Matrix();
  78065. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78066. _this._scalingDeterminant = 1;
  78067. _this._worldTransform = new BABYLON.Matrix();
  78068. _this._needToDecompose = true;
  78069. _this._needToCompose = false;
  78070. _this._skeleton = skeleton;
  78071. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78072. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78073. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78074. _this._index = index;
  78075. skeleton.bones.push(_this);
  78076. _this.setParent(parentBone, false);
  78077. if (baseMatrix || localMatrix) {
  78078. _this._updateDifferenceMatrix();
  78079. }
  78080. return _this;
  78081. }
  78082. Object.defineProperty(Bone.prototype, "_matrix", {
  78083. /** @hidden */
  78084. get: function () {
  78085. this._compose();
  78086. return this._localMatrix;
  78087. },
  78088. /** @hidden */
  78089. set: function (value) {
  78090. this._localMatrix.copyFrom(value);
  78091. this._needToDecompose = true;
  78092. },
  78093. enumerable: true,
  78094. configurable: true
  78095. });
  78096. // Members
  78097. /**
  78098. * Gets the parent skeleton
  78099. * @returns a skeleton
  78100. */
  78101. Bone.prototype.getSkeleton = function () {
  78102. return this._skeleton;
  78103. };
  78104. /**
  78105. * Gets parent bone
  78106. * @returns a bone or null if the bone is the root of the bone hierarchy
  78107. */
  78108. Bone.prototype.getParent = function () {
  78109. return this._parent;
  78110. };
  78111. /**
  78112. * Sets the parent bone
  78113. * @param parent defines the parent (can be null if the bone is the root)
  78114. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78115. */
  78116. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78117. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78118. if (this._parent === parent) {
  78119. return;
  78120. }
  78121. if (this._parent) {
  78122. var index = this._parent.children.indexOf(this);
  78123. if (index !== -1) {
  78124. this._parent.children.splice(index, 1);
  78125. }
  78126. }
  78127. this._parent = parent;
  78128. if (this._parent) {
  78129. this._parent.children.push(this);
  78130. }
  78131. if (updateDifferenceMatrix) {
  78132. this._updateDifferenceMatrix();
  78133. }
  78134. this.markAsDirty();
  78135. };
  78136. /**
  78137. * Gets the local matrix
  78138. * @returns a matrix
  78139. */
  78140. Bone.prototype.getLocalMatrix = function () {
  78141. this._compose();
  78142. return this._localMatrix;
  78143. };
  78144. /**
  78145. * Gets the base matrix (initial matrix which remains unchanged)
  78146. * @returns a matrix
  78147. */
  78148. Bone.prototype.getBaseMatrix = function () {
  78149. return this._baseMatrix;
  78150. };
  78151. /**
  78152. * Gets the rest pose matrix
  78153. * @returns a matrix
  78154. */
  78155. Bone.prototype.getRestPose = function () {
  78156. return this._restPose;
  78157. };
  78158. /**
  78159. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78160. */
  78161. Bone.prototype.getWorldMatrix = function () {
  78162. return this._worldTransform;
  78163. };
  78164. /**
  78165. * Sets the local matrix to rest pose matrix
  78166. */
  78167. Bone.prototype.returnToRest = function () {
  78168. this.updateMatrix(this._restPose.clone());
  78169. };
  78170. /**
  78171. * Gets the inverse of the absolute transform matrix.
  78172. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78173. * @returns a matrix
  78174. */
  78175. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78176. return this._invertedAbsoluteTransform;
  78177. };
  78178. /**
  78179. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78180. * @returns a matrix
  78181. */
  78182. Bone.prototype.getAbsoluteTransform = function () {
  78183. return this._absoluteTransform;
  78184. };
  78185. Object.defineProperty(Bone.prototype, "position", {
  78186. // Properties (matches AbstractMesh properties)
  78187. /** Gets or sets current position (in local space) */
  78188. get: function () {
  78189. this._decompose();
  78190. return this._localPosition;
  78191. },
  78192. set: function (newPosition) {
  78193. this._decompose();
  78194. this._localPosition.copyFrom(newPosition);
  78195. this._markAsDirtyAndCompose();
  78196. },
  78197. enumerable: true,
  78198. configurable: true
  78199. });
  78200. Object.defineProperty(Bone.prototype, "rotation", {
  78201. /** Gets or sets current rotation (in local space) */
  78202. get: function () {
  78203. return this.getRotation();
  78204. },
  78205. set: function (newRotation) {
  78206. this.setRotation(newRotation);
  78207. },
  78208. enumerable: true,
  78209. configurable: true
  78210. });
  78211. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78212. /** Gets or sets current rotation quaternion (in local space) */
  78213. get: function () {
  78214. this._decompose();
  78215. return this._localRotation;
  78216. },
  78217. set: function (newRotation) {
  78218. this.setRotationQuaternion(newRotation);
  78219. },
  78220. enumerable: true,
  78221. configurable: true
  78222. });
  78223. Object.defineProperty(Bone.prototype, "scaling", {
  78224. /** Gets or sets current scaling (in local space) */
  78225. get: function () {
  78226. return this.getScale();
  78227. },
  78228. set: function (newScaling) {
  78229. this.setScale(newScaling);
  78230. },
  78231. enumerable: true,
  78232. configurable: true
  78233. });
  78234. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78235. /**
  78236. * Gets the animation properties override
  78237. */
  78238. get: function () {
  78239. return this._skeleton.animationPropertiesOverride;
  78240. },
  78241. enumerable: true,
  78242. configurable: true
  78243. });
  78244. // Methods
  78245. Bone.prototype._decompose = function () {
  78246. if (!this._needToDecompose) {
  78247. return;
  78248. }
  78249. this._needToDecompose = false;
  78250. if (!this._localScaling) {
  78251. this._localScaling = BABYLON.Vector3.Zero();
  78252. this._localRotation = BABYLON.Quaternion.Zero();
  78253. this._localPosition = BABYLON.Vector3.Zero();
  78254. }
  78255. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78256. };
  78257. Bone.prototype._compose = function () {
  78258. if (!this._needToCompose) {
  78259. return;
  78260. }
  78261. this._needToCompose = false;
  78262. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78263. };
  78264. /**
  78265. * Update the base and local matrices
  78266. * @param matrix defines the new base or local matrix
  78267. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78268. * @param updateLocalMatrix defines if the local matrix should be updated
  78269. */
  78270. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78271. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78272. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78273. this._baseMatrix.copyFrom(matrix);
  78274. if (updateDifferenceMatrix) {
  78275. this._updateDifferenceMatrix();
  78276. }
  78277. if (updateLocalMatrix) {
  78278. this._localMatrix.copyFrom(matrix);
  78279. this._markAsDirtyAndDecompose();
  78280. }
  78281. else {
  78282. this.markAsDirty();
  78283. }
  78284. };
  78285. /** @hidden */
  78286. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78287. if (updateChildren === void 0) { updateChildren = true; }
  78288. if (!rootMatrix) {
  78289. rootMatrix = this._baseMatrix;
  78290. }
  78291. if (this._parent) {
  78292. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78293. }
  78294. else {
  78295. this._absoluteTransform.copyFrom(rootMatrix);
  78296. }
  78297. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78298. if (updateChildren) {
  78299. for (var index = 0; index < this.children.length; index++) {
  78300. this.children[index]._updateDifferenceMatrix();
  78301. }
  78302. }
  78303. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78304. };
  78305. /**
  78306. * Flag the bone as dirty (Forcing it to update everything)
  78307. */
  78308. Bone.prototype.markAsDirty = function () {
  78309. this._currentRenderId++;
  78310. this._childRenderId++;
  78311. this._skeleton._markAsDirty();
  78312. };
  78313. Bone.prototype._markAsDirtyAndCompose = function () {
  78314. this.markAsDirty();
  78315. this._needToCompose = true;
  78316. };
  78317. Bone.prototype._markAsDirtyAndDecompose = function () {
  78318. this.markAsDirty();
  78319. this._needToDecompose = true;
  78320. };
  78321. /**
  78322. * Copy an animation range from another bone
  78323. * @param source defines the source bone
  78324. * @param rangeName defines the range name to copy
  78325. * @param frameOffset defines the frame offset
  78326. * @param rescaleAsRequired defines if rescaling must be applied if required
  78327. * @param skelDimensionsRatio defines the scaling ratio
  78328. * @returns true if operation was successful
  78329. */
  78330. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78331. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78332. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78333. // all animation may be coming from a library skeleton, so may need to create animation
  78334. if (this.animations.length === 0) {
  78335. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78336. this.animations[0].setKeys([]);
  78337. }
  78338. // get animation info / verify there is such a range from the source bone
  78339. var sourceRange = source.animations[0].getRange(rangeName);
  78340. if (!sourceRange) {
  78341. return false;
  78342. }
  78343. var from = sourceRange.from;
  78344. var to = sourceRange.to;
  78345. var sourceKeys = source.animations[0].getKeys();
  78346. // rescaling prep
  78347. var sourceBoneLength = source.length;
  78348. var sourceParent = source.getParent();
  78349. var parent = this.getParent();
  78350. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78351. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78352. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78353. var destKeys = this.animations[0].getKeys();
  78354. // loop vars declaration
  78355. var orig;
  78356. var origTranslation;
  78357. var mat;
  78358. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78359. orig = sourceKeys[key];
  78360. if (orig.frame >= from && orig.frame <= to) {
  78361. if (rescaleAsRequired) {
  78362. mat = orig.value.clone();
  78363. // scale based on parent ratio, when bone has parent
  78364. if (parentScalingReqd) {
  78365. origTranslation = mat.getTranslation();
  78366. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78367. // scale based on skeleton dimension ratio when root bone, and value is passed
  78368. }
  78369. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78370. origTranslation = mat.getTranslation();
  78371. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78372. // use original when root bone, and no data for skelDimensionsRatio
  78373. }
  78374. else {
  78375. mat = orig.value;
  78376. }
  78377. }
  78378. else {
  78379. mat = orig.value;
  78380. }
  78381. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78382. }
  78383. }
  78384. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78385. return true;
  78386. };
  78387. /**
  78388. * Translate the bone in local or world space
  78389. * @param vec The amount to translate the bone
  78390. * @param space The space that the translation is in
  78391. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78392. */
  78393. Bone.prototype.translate = function (vec, space, mesh) {
  78394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78395. var lm = this.getLocalMatrix();
  78396. if (space == BABYLON.Space.LOCAL) {
  78397. lm.m[12] += vec.x;
  78398. lm.m[13] += vec.y;
  78399. lm.m[14] += vec.z;
  78400. }
  78401. else {
  78402. var wm = null;
  78403. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78404. if (mesh) {
  78405. wm = mesh.getWorldMatrix();
  78406. }
  78407. this._skeleton.computeAbsoluteTransforms();
  78408. var tmat = Bone._tmpMats[0];
  78409. var tvec = Bone._tmpVecs[0];
  78410. if (this._parent) {
  78411. if (mesh && wm) {
  78412. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78413. tmat.multiplyToRef(wm, tmat);
  78414. }
  78415. else {
  78416. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78417. }
  78418. }
  78419. tmat.m[12] = 0;
  78420. tmat.m[13] = 0;
  78421. tmat.m[14] = 0;
  78422. tmat.invert();
  78423. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78424. lm.m[12] += tvec.x;
  78425. lm.m[13] += tvec.y;
  78426. lm.m[14] += tvec.z;
  78427. }
  78428. this._markAsDirtyAndDecompose();
  78429. };
  78430. /**
  78431. * Set the postion of the bone in local or world space
  78432. * @param position The position to set the bone
  78433. * @param space The space that the position is in
  78434. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78435. */
  78436. Bone.prototype.setPosition = function (position, space, mesh) {
  78437. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78438. var lm = this.getLocalMatrix();
  78439. if (space == BABYLON.Space.LOCAL) {
  78440. lm.m[12] = position.x;
  78441. lm.m[13] = position.y;
  78442. lm.m[14] = position.z;
  78443. }
  78444. else {
  78445. var wm = null;
  78446. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78447. if (mesh) {
  78448. wm = mesh.getWorldMatrix();
  78449. }
  78450. this._skeleton.computeAbsoluteTransforms();
  78451. var tmat = Bone._tmpMats[0];
  78452. var vec = Bone._tmpVecs[0];
  78453. if (this._parent) {
  78454. if (mesh && wm) {
  78455. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78456. tmat.multiplyToRef(wm, tmat);
  78457. }
  78458. else {
  78459. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78460. }
  78461. }
  78462. tmat.invert();
  78463. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78464. lm.m[12] = vec.x;
  78465. lm.m[13] = vec.y;
  78466. lm.m[14] = vec.z;
  78467. }
  78468. this._markAsDirtyAndDecompose();
  78469. };
  78470. /**
  78471. * Set the absolute position of the bone (world space)
  78472. * @param position The position to set the bone
  78473. * @param mesh The mesh that this bone is attached to
  78474. */
  78475. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78476. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78477. };
  78478. /**
  78479. * Scale the bone on the x, y and z axes (in local space)
  78480. * @param x The amount to scale the bone on the x axis
  78481. * @param y The amount to scale the bone on the y axis
  78482. * @param z The amount to scale the bone on the z axis
  78483. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78484. */
  78485. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78486. if (scaleChildren === void 0) { scaleChildren = false; }
  78487. var locMat = this.getLocalMatrix();
  78488. // Apply new scaling on top of current local matrix
  78489. var scaleMat = Bone._tmpMats[0];
  78490. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78491. scaleMat.multiplyToRef(locMat, locMat);
  78492. // Invert scaling matrix and apply the inverse to all children
  78493. scaleMat.invert();
  78494. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78495. var child = _a[_i];
  78496. var cm = child.getLocalMatrix();
  78497. cm.multiplyToRef(scaleMat, cm);
  78498. cm.m[12] *= x;
  78499. cm.m[13] *= y;
  78500. cm.m[14] *= z;
  78501. child._markAsDirtyAndDecompose();
  78502. }
  78503. this._markAsDirtyAndDecompose();
  78504. if (scaleChildren) {
  78505. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78506. var child = _c[_b];
  78507. child.scale(x, y, z, scaleChildren);
  78508. }
  78509. }
  78510. };
  78511. /**
  78512. * Set the bone scaling in local space
  78513. * @param scale defines the scaling vector
  78514. */
  78515. Bone.prototype.setScale = function (scale) {
  78516. this._decompose();
  78517. this._localScaling.copyFrom(scale);
  78518. this._markAsDirtyAndCompose();
  78519. };
  78520. /**
  78521. * Gets the current scaling in local space
  78522. * @returns the current scaling vector
  78523. */
  78524. Bone.prototype.getScale = function () {
  78525. this._decompose();
  78526. return this._localScaling;
  78527. };
  78528. /**
  78529. * Gets the current scaling in local space and stores it in a target vector
  78530. * @param result defines the target vector
  78531. */
  78532. Bone.prototype.getScaleToRef = function (result) {
  78533. this._decompose();
  78534. result.copyFrom(this._localScaling);
  78535. };
  78536. /**
  78537. * Set the yaw, pitch, and roll of the bone in local or world space
  78538. * @param yaw The rotation of the bone on the y axis
  78539. * @param pitch The rotation of the bone on the x axis
  78540. * @param roll The rotation of the bone on the z axis
  78541. * @param space The space that the axes of rotation are in
  78542. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78543. */
  78544. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78545. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78546. if (space === BABYLON.Space.LOCAL) {
  78547. var quat = Bone._tmpQuat;
  78548. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78549. this.setRotationQuaternion(quat, space, mesh);
  78550. return;
  78551. }
  78552. var rotMatInv = Bone._tmpMats[0];
  78553. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78554. return;
  78555. }
  78556. var rotMat = Bone._tmpMats[1];
  78557. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78558. rotMatInv.multiplyToRef(rotMat, rotMat);
  78559. this._rotateWithMatrix(rotMat, space, mesh);
  78560. };
  78561. /**
  78562. * Add a rotation to the bone on an axis in local or world space
  78563. * @param axis The axis to rotate the bone on
  78564. * @param amount The amount to rotate the bone
  78565. * @param space The space that the axis is in
  78566. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78567. */
  78568. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78569. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78570. var rmat = Bone._tmpMats[0];
  78571. rmat.m[12] = 0;
  78572. rmat.m[13] = 0;
  78573. rmat.m[14] = 0;
  78574. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78575. this._rotateWithMatrix(rmat, space, mesh);
  78576. };
  78577. /**
  78578. * Set the rotation of the bone to a particular axis angle in local or world space
  78579. * @param axis The axis to rotate the bone on
  78580. * @param angle The angle that the bone should be rotated to
  78581. * @param space The space that the axis is in
  78582. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78583. */
  78584. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78585. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78586. if (space === BABYLON.Space.LOCAL) {
  78587. var quat = Bone._tmpQuat;
  78588. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78589. this.setRotationQuaternion(quat, space, mesh);
  78590. return;
  78591. }
  78592. var rotMatInv = Bone._tmpMats[0];
  78593. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78594. return;
  78595. }
  78596. var rotMat = Bone._tmpMats[1];
  78597. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78598. rotMatInv.multiplyToRef(rotMat, rotMat);
  78599. this._rotateWithMatrix(rotMat, space, mesh);
  78600. };
  78601. /**
  78602. * Set the euler rotation of the bone in local of world space
  78603. * @param rotation The euler rotation that the bone should be set to
  78604. * @param space The space that the rotation is in
  78605. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78606. */
  78607. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78609. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78610. };
  78611. /**
  78612. * Set the quaternion rotation of the bone in local of world space
  78613. * @param quat The quaternion rotation that the bone should be set to
  78614. * @param space The space that the rotation is in
  78615. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78616. */
  78617. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78618. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78619. if (space === BABYLON.Space.LOCAL) {
  78620. this._decompose();
  78621. this._localRotation.copyFrom(quat);
  78622. this._markAsDirtyAndCompose();
  78623. return;
  78624. }
  78625. var rotMatInv = Bone._tmpMats[0];
  78626. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78627. return;
  78628. }
  78629. var rotMat = Bone._tmpMats[1];
  78630. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78631. rotMatInv.multiplyToRef(rotMat, rotMat);
  78632. this._rotateWithMatrix(rotMat, space, mesh);
  78633. };
  78634. /**
  78635. * Set the rotation matrix of the bone in local of world space
  78636. * @param rotMat The rotation matrix that the bone should be set to
  78637. * @param space The space that the rotation is in
  78638. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78639. */
  78640. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78641. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78642. if (space === BABYLON.Space.LOCAL) {
  78643. var quat = Bone._tmpQuat;
  78644. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78645. this.setRotationQuaternion(quat, space, mesh);
  78646. return;
  78647. }
  78648. var rotMatInv = Bone._tmpMats[0];
  78649. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78650. return;
  78651. }
  78652. var rotMat2 = Bone._tmpMats[1];
  78653. rotMat2.copyFrom(rotMat);
  78654. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78655. this._rotateWithMatrix(rotMat2, space, mesh);
  78656. };
  78657. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78658. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78659. var lmat = this.getLocalMatrix();
  78660. var lx = lmat.m[12];
  78661. var ly = lmat.m[13];
  78662. var lz = lmat.m[14];
  78663. var parent = this.getParent();
  78664. var parentScale = Bone._tmpMats[3];
  78665. var parentScaleInv = Bone._tmpMats[4];
  78666. if (parent && space == BABYLON.Space.WORLD) {
  78667. if (mesh) {
  78668. parentScale.copyFrom(mesh.getWorldMatrix());
  78669. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78670. }
  78671. else {
  78672. parentScale.copyFrom(parent.getAbsoluteTransform());
  78673. }
  78674. parentScaleInv.copyFrom(parentScale);
  78675. parentScaleInv.invert();
  78676. lmat.multiplyToRef(parentScale, lmat);
  78677. lmat.multiplyToRef(rmat, lmat);
  78678. lmat.multiplyToRef(parentScaleInv, lmat);
  78679. }
  78680. else {
  78681. if (space == BABYLON.Space.WORLD && mesh) {
  78682. parentScale.copyFrom(mesh.getWorldMatrix());
  78683. parentScaleInv.copyFrom(parentScale);
  78684. parentScaleInv.invert();
  78685. lmat.multiplyToRef(parentScale, lmat);
  78686. lmat.multiplyToRef(rmat, lmat);
  78687. lmat.multiplyToRef(parentScaleInv, lmat);
  78688. }
  78689. else {
  78690. lmat.multiplyToRef(rmat, lmat);
  78691. }
  78692. }
  78693. lmat.m[12] = lx;
  78694. lmat.m[13] = ly;
  78695. lmat.m[14] = lz;
  78696. this.computeAbsoluteTransforms();
  78697. this._markAsDirtyAndDecompose();
  78698. };
  78699. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78700. var scaleMatrix = Bone._tmpMats[2];
  78701. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78702. if (mesh) {
  78703. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78704. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78705. }
  78706. rotMatInv.invert();
  78707. if (isNaN(rotMatInv.m[0])) {
  78708. // Matrix failed to invert.
  78709. // This can happen if scale is zero for example.
  78710. return false;
  78711. }
  78712. scaleMatrix.m[0] *= this._scalingDeterminant;
  78713. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78714. return true;
  78715. };
  78716. /**
  78717. * Get the position of the bone in local or world space
  78718. * @param space The space that the returned position is in
  78719. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78720. * @returns The position of the bone
  78721. */
  78722. Bone.prototype.getPosition = function (space, mesh) {
  78723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78724. if (mesh === void 0) { mesh = null; }
  78725. var pos = BABYLON.Vector3.Zero();
  78726. this.getPositionToRef(space, mesh, pos);
  78727. return pos;
  78728. };
  78729. /**
  78730. * Copy the position of the bone to a vector3 in local or world space
  78731. * @param space The space that the returned position is in
  78732. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78733. * @param result The vector3 to copy the position to
  78734. */
  78735. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78736. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78737. if (space == BABYLON.Space.LOCAL) {
  78738. var lm = this.getLocalMatrix();
  78739. result.x = lm.m[12];
  78740. result.y = lm.m[13];
  78741. result.z = lm.m[14];
  78742. }
  78743. else {
  78744. var wm = null;
  78745. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78746. if (mesh) {
  78747. wm = mesh.getWorldMatrix();
  78748. }
  78749. this._skeleton.computeAbsoluteTransforms();
  78750. var tmat = Bone._tmpMats[0];
  78751. if (mesh && wm) {
  78752. tmat.copyFrom(this.getAbsoluteTransform());
  78753. tmat.multiplyToRef(wm, tmat);
  78754. }
  78755. else {
  78756. tmat = this.getAbsoluteTransform();
  78757. }
  78758. result.x = tmat.m[12];
  78759. result.y = tmat.m[13];
  78760. result.z = tmat.m[14];
  78761. }
  78762. };
  78763. /**
  78764. * Get the absolute position of the bone (world space)
  78765. * @param mesh The mesh that this bone is attached to
  78766. * @returns The absolute position of the bone
  78767. */
  78768. Bone.prototype.getAbsolutePosition = function (mesh) {
  78769. if (mesh === void 0) { mesh = null; }
  78770. var pos = BABYLON.Vector3.Zero();
  78771. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78772. return pos;
  78773. };
  78774. /**
  78775. * Copy the absolute position of the bone (world space) to the result param
  78776. * @param mesh The mesh that this bone is attached to
  78777. * @param result The vector3 to copy the absolute position to
  78778. */
  78779. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78780. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78781. };
  78782. /**
  78783. * Compute the absolute transforms of this bone and its children
  78784. */
  78785. Bone.prototype.computeAbsoluteTransforms = function () {
  78786. this._compose();
  78787. if (this._parent) {
  78788. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78789. }
  78790. else {
  78791. this._absoluteTransform.copyFrom(this._localMatrix);
  78792. var poseMatrix = this._skeleton.getPoseMatrix();
  78793. if (poseMatrix) {
  78794. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78795. }
  78796. }
  78797. var children = this.children;
  78798. var len = children.length;
  78799. for (var i = 0; i < len; i++) {
  78800. children[i].computeAbsoluteTransforms();
  78801. }
  78802. };
  78803. /**
  78804. * Get the world direction from an axis that is in the local space of the bone
  78805. * @param localAxis The local direction that is used to compute the world direction
  78806. * @param mesh The mesh that this bone is attached to
  78807. * @returns The world direction
  78808. */
  78809. Bone.prototype.getDirection = function (localAxis, mesh) {
  78810. if (mesh === void 0) { mesh = null; }
  78811. var result = BABYLON.Vector3.Zero();
  78812. this.getDirectionToRef(localAxis, mesh, result);
  78813. return result;
  78814. };
  78815. /**
  78816. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78817. * @param localAxis The local direction that is used to compute the world direction
  78818. * @param mesh The mesh that this bone is attached to
  78819. * @param result The vector3 that the world direction will be copied to
  78820. */
  78821. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78822. if (mesh === void 0) { mesh = null; }
  78823. var wm = null;
  78824. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78825. if (mesh) {
  78826. wm = mesh.getWorldMatrix();
  78827. }
  78828. this._skeleton.computeAbsoluteTransforms();
  78829. var mat = Bone._tmpMats[0];
  78830. mat.copyFrom(this.getAbsoluteTransform());
  78831. if (mesh && wm) {
  78832. mat.multiplyToRef(wm, mat);
  78833. }
  78834. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78835. result.normalize();
  78836. };
  78837. /**
  78838. * Get the euler rotation of the bone in local or world space
  78839. * @param space The space that the rotation should be in
  78840. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78841. * @returns The euler rotation
  78842. */
  78843. Bone.prototype.getRotation = function (space, mesh) {
  78844. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78845. if (mesh === void 0) { mesh = null; }
  78846. var result = BABYLON.Vector3.Zero();
  78847. this.getRotationToRef(space, mesh, result);
  78848. return result;
  78849. };
  78850. /**
  78851. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78852. * @param space The space that the rotation should be in
  78853. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78854. * @param result The vector3 that the rotation should be copied to
  78855. */
  78856. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78857. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78858. if (mesh === void 0) { mesh = null; }
  78859. var quat = Bone._tmpQuat;
  78860. this.getRotationQuaternionToRef(space, mesh, quat);
  78861. quat.toEulerAnglesToRef(result);
  78862. };
  78863. /**
  78864. * Get the quaternion rotation of the bone in either local or world space
  78865. * @param space The space that the rotation should be in
  78866. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78867. * @returns The quaternion rotation
  78868. */
  78869. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78870. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78871. if (mesh === void 0) { mesh = null; }
  78872. var result = BABYLON.Quaternion.Identity();
  78873. this.getRotationQuaternionToRef(space, mesh, result);
  78874. return result;
  78875. };
  78876. /**
  78877. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78878. * @param space The space that the rotation should be in
  78879. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78880. * @param result The quaternion that the rotation should be copied to
  78881. */
  78882. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78883. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78884. if (mesh === void 0) { mesh = null; }
  78885. if (space == BABYLON.Space.LOCAL) {
  78886. this._decompose();
  78887. result.copyFrom(this._localRotation);
  78888. }
  78889. else {
  78890. var mat = Bone._tmpMats[0];
  78891. var amat = this.getAbsoluteTransform();
  78892. if (mesh) {
  78893. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78894. }
  78895. else {
  78896. mat.copyFrom(amat);
  78897. }
  78898. mat.m[0] *= this._scalingDeterminant;
  78899. mat.m[1] *= this._scalingDeterminant;
  78900. mat.m[2] *= this._scalingDeterminant;
  78901. mat.decompose(undefined, result, undefined);
  78902. }
  78903. };
  78904. /**
  78905. * Get the rotation matrix of the bone in local or world space
  78906. * @param space The space that the rotation should be in
  78907. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78908. * @returns The rotation matrix
  78909. */
  78910. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78912. var result = BABYLON.Matrix.Identity();
  78913. this.getRotationMatrixToRef(space, mesh, result);
  78914. return result;
  78915. };
  78916. /**
  78917. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78918. * @param space The space that the rotation should be in
  78919. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78920. * @param result The quaternion that the rotation should be copied to
  78921. */
  78922. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78923. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78924. if (space == BABYLON.Space.LOCAL) {
  78925. this.getLocalMatrix().getRotationMatrixToRef(result);
  78926. }
  78927. else {
  78928. var mat = Bone._tmpMats[0];
  78929. var amat = this.getAbsoluteTransform();
  78930. if (mesh) {
  78931. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78932. }
  78933. else {
  78934. mat.copyFrom(amat);
  78935. }
  78936. mat.m[0] *= this._scalingDeterminant;
  78937. mat.m[1] *= this._scalingDeterminant;
  78938. mat.m[2] *= this._scalingDeterminant;
  78939. mat.getRotationMatrixToRef(result);
  78940. }
  78941. };
  78942. /**
  78943. * Get the world position of a point that is in the local space of the bone
  78944. * @param position The local position
  78945. * @param mesh The mesh that this bone is attached to
  78946. * @returns The world position
  78947. */
  78948. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78949. if (mesh === void 0) { mesh = null; }
  78950. var result = BABYLON.Vector3.Zero();
  78951. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78952. return result;
  78953. };
  78954. /**
  78955. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78956. * @param position The local position
  78957. * @param mesh The mesh that this bone is attached to
  78958. * @param result The vector3 that the world position should be copied to
  78959. */
  78960. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78961. if (mesh === void 0) { mesh = null; }
  78962. var wm = null;
  78963. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78964. if (mesh) {
  78965. wm = mesh.getWorldMatrix();
  78966. }
  78967. this._skeleton.computeAbsoluteTransforms();
  78968. var tmat = Bone._tmpMats[0];
  78969. if (mesh && wm) {
  78970. tmat.copyFrom(this.getAbsoluteTransform());
  78971. tmat.multiplyToRef(wm, tmat);
  78972. }
  78973. else {
  78974. tmat = this.getAbsoluteTransform();
  78975. }
  78976. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78977. };
  78978. /**
  78979. * Get the local position of a point that is in world space
  78980. * @param position The world position
  78981. * @param mesh The mesh that this bone is attached to
  78982. * @returns The local position
  78983. */
  78984. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78985. if (mesh === void 0) { mesh = null; }
  78986. var result = BABYLON.Vector3.Zero();
  78987. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78988. return result;
  78989. };
  78990. /**
  78991. * Get the local position of a point that is in world space and copy it to the result param
  78992. * @param position The world position
  78993. * @param mesh The mesh that this bone is attached to
  78994. * @param result The vector3 that the local position should be copied to
  78995. */
  78996. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78997. if (mesh === void 0) { mesh = null; }
  78998. var wm = null;
  78999. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79000. if (mesh) {
  79001. wm = mesh.getWorldMatrix();
  79002. }
  79003. this._skeleton.computeAbsoluteTransforms();
  79004. var tmat = Bone._tmpMats[0];
  79005. tmat.copyFrom(this.getAbsoluteTransform());
  79006. if (mesh && wm) {
  79007. tmat.multiplyToRef(wm, tmat);
  79008. }
  79009. tmat.invert();
  79010. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79011. };
  79012. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79013. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79014. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79015. return Bone;
  79016. }(BABYLON.Node));
  79017. BABYLON.Bone = Bone;
  79018. })(BABYLON || (BABYLON = {}));
  79019. //# sourceMappingURL=babylon.bone.js.map
  79020. var BABYLON;
  79021. (function (BABYLON) {
  79022. /**
  79023. * Class used to apply inverse kinematics to bones
  79024. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79025. */
  79026. var BoneIKController = /** @class */ (function () {
  79027. /**
  79028. * Creates a new BoneIKController
  79029. * @param mesh defines the mesh to control
  79030. * @param bone defines the bone to control
  79031. * @param options defines options to set up the controller
  79032. */
  79033. function BoneIKController(mesh, bone, options) {
  79034. /**
  79035. * Gets or sets the target position
  79036. */
  79037. this.targetPosition = BABYLON.Vector3.Zero();
  79038. /**
  79039. * Gets or sets the pole target position
  79040. */
  79041. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79042. /**
  79043. * Gets or sets the pole target local offset
  79044. */
  79045. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79046. /**
  79047. * Gets or sets the pole angle
  79048. */
  79049. this.poleAngle = 0;
  79050. /**
  79051. * 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)
  79052. */
  79053. this.slerpAmount = 1;
  79054. this._bone1Quat = BABYLON.Quaternion.Identity();
  79055. this._bone1Mat = BABYLON.Matrix.Identity();
  79056. this._bone2Ang = Math.PI;
  79057. this._maxAngle = Math.PI;
  79058. this._rightHandedSystem = false;
  79059. this._bendAxis = BABYLON.Vector3.Right();
  79060. this._slerping = false;
  79061. this._adjustRoll = 0;
  79062. this._bone2 = bone;
  79063. this._bone1 = bone.getParent();
  79064. if (!this._bone1) {
  79065. return;
  79066. }
  79067. this.mesh = mesh;
  79068. var bonePos = bone.getPosition();
  79069. if (bone.getAbsoluteTransform().determinant() > 0) {
  79070. this._rightHandedSystem = true;
  79071. this._bendAxis.x = 0;
  79072. this._bendAxis.y = 0;
  79073. this._bendAxis.z = -1;
  79074. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79075. this._adjustRoll = Math.PI * .5;
  79076. this._bendAxis.z = 1;
  79077. }
  79078. }
  79079. if (this._bone1.length) {
  79080. var boneScale1 = this._bone1.getScale();
  79081. var boneScale2 = this._bone2.getScale();
  79082. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79083. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79084. }
  79085. else if (this._bone1.children[0]) {
  79086. mesh.computeWorldMatrix(true);
  79087. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79088. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79089. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79090. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79091. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79092. }
  79093. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79094. this.maxAngle = Math.PI;
  79095. if (options) {
  79096. if (options.targetMesh) {
  79097. this.targetMesh = options.targetMesh;
  79098. this.targetMesh.computeWorldMatrix(true);
  79099. }
  79100. if (options.poleTargetMesh) {
  79101. this.poleTargetMesh = options.poleTargetMesh;
  79102. this.poleTargetMesh.computeWorldMatrix(true);
  79103. }
  79104. else if (options.poleTargetBone) {
  79105. this.poleTargetBone = options.poleTargetBone;
  79106. }
  79107. else if (this._bone1.getParent()) {
  79108. this.poleTargetBone = this._bone1.getParent();
  79109. }
  79110. if (options.poleTargetLocalOffset) {
  79111. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79112. }
  79113. if (options.poleAngle) {
  79114. this.poleAngle = options.poleAngle;
  79115. }
  79116. if (options.bendAxis) {
  79117. this._bendAxis.copyFrom(options.bendAxis);
  79118. }
  79119. if (options.maxAngle) {
  79120. this.maxAngle = options.maxAngle;
  79121. }
  79122. if (options.slerpAmount) {
  79123. this.slerpAmount = options.slerpAmount;
  79124. }
  79125. }
  79126. }
  79127. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79128. /**
  79129. * Gets or sets maximum allowed angle
  79130. */
  79131. get: function () {
  79132. return this._maxAngle;
  79133. },
  79134. set: function (value) {
  79135. this._setMaxAngle(value);
  79136. },
  79137. enumerable: true,
  79138. configurable: true
  79139. });
  79140. BoneIKController.prototype._setMaxAngle = function (ang) {
  79141. if (ang < 0) {
  79142. ang = 0;
  79143. }
  79144. if (ang > Math.PI || ang == undefined) {
  79145. ang = Math.PI;
  79146. }
  79147. this._maxAngle = ang;
  79148. var a = this._bone1Length;
  79149. var b = this._bone2Length;
  79150. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79151. };
  79152. /**
  79153. * Force the controller to update the bones
  79154. */
  79155. BoneIKController.prototype.update = function () {
  79156. var bone1 = this._bone1;
  79157. if (!bone1) {
  79158. return;
  79159. }
  79160. var target = this.targetPosition;
  79161. var poleTarget = this.poleTargetPosition;
  79162. var mat1 = BoneIKController._tmpMats[0];
  79163. var mat2 = BoneIKController._tmpMats[1];
  79164. if (this.targetMesh) {
  79165. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79166. }
  79167. if (this.poleTargetBone) {
  79168. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79169. }
  79170. else if (this.poleTargetMesh) {
  79171. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79172. }
  79173. var bonePos = BoneIKController._tmpVecs[0];
  79174. var zaxis = BoneIKController._tmpVecs[1];
  79175. var xaxis = BoneIKController._tmpVecs[2];
  79176. var yaxis = BoneIKController._tmpVecs[3];
  79177. var upAxis = BoneIKController._tmpVecs[4];
  79178. var _tmpQuat = BoneIKController._tmpQuat;
  79179. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79180. poleTarget.subtractToRef(bonePos, upAxis);
  79181. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79182. upAxis.y = 1;
  79183. }
  79184. else {
  79185. upAxis.normalize();
  79186. }
  79187. target.subtractToRef(bonePos, yaxis);
  79188. yaxis.normalize();
  79189. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79190. zaxis.normalize();
  79191. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79192. xaxis.normalize();
  79193. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79194. var a = this._bone1Length;
  79195. var b = this._bone2Length;
  79196. var c = BABYLON.Vector3.Distance(bonePos, target);
  79197. if (this._maxReach > 0) {
  79198. c = Math.min(this._maxReach, c);
  79199. }
  79200. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79201. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79202. if (acosa > 1) {
  79203. acosa = 1;
  79204. }
  79205. if (acosb > 1) {
  79206. acosb = 1;
  79207. }
  79208. if (acosa < -1) {
  79209. acosa = -1;
  79210. }
  79211. if (acosb < -1) {
  79212. acosb = -1;
  79213. }
  79214. var angA = Math.acos(acosa);
  79215. var angB = Math.acos(acosb);
  79216. var angC = -angA - angB;
  79217. if (this._rightHandedSystem) {
  79218. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79219. mat2.multiplyToRef(mat1, mat1);
  79220. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79221. mat2.multiplyToRef(mat1, mat1);
  79222. }
  79223. else {
  79224. var _tmpVec = BoneIKController._tmpVecs[5];
  79225. _tmpVec.copyFrom(this._bendAxis);
  79226. _tmpVec.x *= -1;
  79227. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79228. mat2.multiplyToRef(mat1, mat1);
  79229. }
  79230. if (this.poleAngle) {
  79231. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79232. mat1.multiplyToRef(mat2, mat1);
  79233. }
  79234. if (this._bone1) {
  79235. if (this.slerpAmount < 1) {
  79236. if (!this._slerping) {
  79237. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79238. }
  79239. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79240. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79241. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79242. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79243. this._slerping = true;
  79244. }
  79245. else {
  79246. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79247. this._bone1Mat.copyFrom(mat1);
  79248. this._slerping = false;
  79249. }
  79250. }
  79251. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79252. this._bone2Ang = angC;
  79253. };
  79254. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79255. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79256. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79257. return BoneIKController;
  79258. }());
  79259. BABYLON.BoneIKController = BoneIKController;
  79260. })(BABYLON || (BABYLON = {}));
  79261. //# sourceMappingURL=babylon.boneIKController.js.map
  79262. var BABYLON;
  79263. (function (BABYLON) {
  79264. /**
  79265. * Class used to make a bone look toward a point in space
  79266. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79267. */
  79268. var BoneLookController = /** @class */ (function () {
  79269. /**
  79270. * Create a BoneLookController
  79271. * @param mesh the mesh that the bone belongs to
  79272. * @param bone the bone that will be looking to the target
  79273. * @param target the target Vector3 to look at
  79274. * @param settings optional settings:
  79275. * * maxYaw: the maximum angle the bone will yaw to
  79276. * * minYaw: the minimum angle the bone will yaw to
  79277. * * maxPitch: the maximum angle the bone will pitch to
  79278. * * minPitch: the minimum angle the bone will yaw to
  79279. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79280. * * upAxis: the up axis of the coordinate system
  79281. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79282. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79283. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79284. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79285. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79286. * * adjustRoll: used to make an adjustment to the roll of the bone
  79287. **/
  79288. function BoneLookController(mesh, bone, target, options) {
  79289. /**
  79290. * The up axis of the coordinate system that is used when the bone is rotated
  79291. */
  79292. this.upAxis = BABYLON.Vector3.Up();
  79293. /**
  79294. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79295. */
  79296. this.upAxisSpace = BABYLON.Space.LOCAL;
  79297. /**
  79298. * Used to make an adjustment to the yaw of the bone
  79299. */
  79300. this.adjustYaw = 0;
  79301. /**
  79302. * Used to make an adjustment to the pitch of the bone
  79303. */
  79304. this.adjustPitch = 0;
  79305. /**
  79306. * Used to make an adjustment to the roll of the bone
  79307. */
  79308. this.adjustRoll = 0;
  79309. /**
  79310. * 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)
  79311. */
  79312. this.slerpAmount = 1;
  79313. this._boneQuat = BABYLON.Quaternion.Identity();
  79314. this._slerping = false;
  79315. this._firstFrameSkipped = false;
  79316. this._fowardAxis = BABYLON.Vector3.Forward();
  79317. this.mesh = mesh;
  79318. this.bone = bone;
  79319. this.target = target;
  79320. if (options) {
  79321. if (options.adjustYaw) {
  79322. this.adjustYaw = options.adjustYaw;
  79323. }
  79324. if (options.adjustPitch) {
  79325. this.adjustPitch = options.adjustPitch;
  79326. }
  79327. if (options.adjustRoll) {
  79328. this.adjustRoll = options.adjustRoll;
  79329. }
  79330. if (options.maxYaw != null) {
  79331. this.maxYaw = options.maxYaw;
  79332. }
  79333. else {
  79334. this.maxYaw = Math.PI;
  79335. }
  79336. if (options.minYaw != null) {
  79337. this.minYaw = options.minYaw;
  79338. }
  79339. else {
  79340. this.minYaw = -Math.PI;
  79341. }
  79342. if (options.maxPitch != null) {
  79343. this.maxPitch = options.maxPitch;
  79344. }
  79345. else {
  79346. this.maxPitch = Math.PI;
  79347. }
  79348. if (options.minPitch != null) {
  79349. this.minPitch = options.minPitch;
  79350. }
  79351. else {
  79352. this.minPitch = -Math.PI;
  79353. }
  79354. if (options.slerpAmount != null) {
  79355. this.slerpAmount = options.slerpAmount;
  79356. }
  79357. if (options.upAxis != null) {
  79358. this.upAxis = options.upAxis;
  79359. }
  79360. if (options.upAxisSpace != null) {
  79361. this.upAxisSpace = options.upAxisSpace;
  79362. }
  79363. if (options.yawAxis != null || options.pitchAxis != null) {
  79364. var newYawAxis = BABYLON.Axis.Y;
  79365. var newPitchAxis = BABYLON.Axis.X;
  79366. if (options.yawAxis != null) {
  79367. newYawAxis = options.yawAxis.clone();
  79368. newYawAxis.normalize();
  79369. }
  79370. if (options.pitchAxis != null) {
  79371. newPitchAxis = options.pitchAxis.clone();
  79372. newPitchAxis.normalize();
  79373. }
  79374. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79375. this._transformYawPitch = BABYLON.Matrix.Identity();
  79376. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79377. this._transformYawPitchInv = this._transformYawPitch.clone();
  79378. this._transformYawPitch.invert();
  79379. }
  79380. }
  79381. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79382. this.upAxisSpace = BABYLON.Space.LOCAL;
  79383. }
  79384. }
  79385. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79386. /**
  79387. * Gets or sets the minimum yaw angle that the bone can look to
  79388. */
  79389. get: function () {
  79390. return this._minYaw;
  79391. },
  79392. set: function (value) {
  79393. this._minYaw = value;
  79394. this._minYawSin = Math.sin(value);
  79395. this._minYawCos = Math.cos(value);
  79396. if (this._maxYaw != null) {
  79397. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79398. this._yawRange = this._maxYaw - this._minYaw;
  79399. }
  79400. },
  79401. enumerable: true,
  79402. configurable: true
  79403. });
  79404. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79405. /**
  79406. * Gets or sets the maximum yaw angle that the bone can look to
  79407. */
  79408. get: function () {
  79409. return this._maxYaw;
  79410. },
  79411. set: function (value) {
  79412. this._maxYaw = value;
  79413. this._maxYawSin = Math.sin(value);
  79414. this._maxYawCos = Math.cos(value);
  79415. if (this._minYaw != null) {
  79416. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79417. this._yawRange = this._maxYaw - this._minYaw;
  79418. }
  79419. },
  79420. enumerable: true,
  79421. configurable: true
  79422. });
  79423. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79424. /**
  79425. * Gets or sets the minimum pitch angle that the bone can look to
  79426. */
  79427. get: function () {
  79428. return this._minPitch;
  79429. },
  79430. set: function (value) {
  79431. this._minPitch = value;
  79432. this._minPitchTan = Math.tan(value);
  79433. },
  79434. enumerable: true,
  79435. configurable: true
  79436. });
  79437. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79438. /**
  79439. * Gets or sets the maximum pitch angle that the bone can look to
  79440. */
  79441. get: function () {
  79442. return this._maxPitch;
  79443. },
  79444. set: function (value) {
  79445. this._maxPitch = value;
  79446. this._maxPitchTan = Math.tan(value);
  79447. },
  79448. enumerable: true,
  79449. configurable: true
  79450. });
  79451. /**
  79452. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79453. */
  79454. BoneLookController.prototype.update = function () {
  79455. //skip the first frame when slerping so that the mesh rotation is correct
  79456. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79457. this._firstFrameSkipped = true;
  79458. return;
  79459. }
  79460. var bone = this.bone;
  79461. var bonePos = BoneLookController._tmpVecs[0];
  79462. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79463. var target = this.target;
  79464. var _tmpMat1 = BoneLookController._tmpMats[0];
  79465. var _tmpMat2 = BoneLookController._tmpMats[1];
  79466. var mesh = this.mesh;
  79467. var parentBone = bone.getParent();
  79468. var upAxis = BoneLookController._tmpVecs[1];
  79469. upAxis.copyFrom(this.upAxis);
  79470. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79471. if (this._transformYawPitch) {
  79472. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79473. }
  79474. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79475. }
  79476. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79477. mesh.getDirectionToRef(upAxis, upAxis);
  79478. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79479. upAxis.normalize();
  79480. }
  79481. }
  79482. var checkYaw = false;
  79483. var checkPitch = false;
  79484. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79485. checkYaw = true;
  79486. }
  79487. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79488. checkPitch = true;
  79489. }
  79490. if (checkYaw || checkPitch) {
  79491. var spaceMat = BoneLookController._tmpMats[2];
  79492. var spaceMatInv = BoneLookController._tmpMats[3];
  79493. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79494. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79495. }
  79496. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79497. spaceMat.copyFrom(mesh.getWorldMatrix());
  79498. }
  79499. else {
  79500. var forwardAxis = BoneLookController._tmpVecs[2];
  79501. forwardAxis.copyFrom(this._fowardAxis);
  79502. if (this._transformYawPitch) {
  79503. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79504. }
  79505. if (parentBone) {
  79506. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79507. }
  79508. else {
  79509. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79510. }
  79511. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79512. rightAxis.normalize();
  79513. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79514. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79515. }
  79516. spaceMat.invertToRef(spaceMatInv);
  79517. var xzlen = null;
  79518. if (checkPitch) {
  79519. var localTarget = BoneLookController._tmpVecs[3];
  79520. target.subtractToRef(bonePos, localTarget);
  79521. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79522. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79523. var pitch = Math.atan2(localTarget.y, xzlen);
  79524. var newPitch = pitch;
  79525. if (pitch > this._maxPitch) {
  79526. localTarget.y = this._maxPitchTan * xzlen;
  79527. newPitch = this._maxPitch;
  79528. }
  79529. else if (pitch < this._minPitch) {
  79530. localTarget.y = this._minPitchTan * xzlen;
  79531. newPitch = this._minPitch;
  79532. }
  79533. if (pitch != newPitch) {
  79534. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79535. localTarget.addInPlace(bonePos);
  79536. target = localTarget;
  79537. }
  79538. }
  79539. if (checkYaw) {
  79540. var localTarget = BoneLookController._tmpVecs[4];
  79541. target.subtractToRef(bonePos, localTarget);
  79542. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79543. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79544. var newYaw = yaw;
  79545. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79546. if (xzlen == null) {
  79547. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79548. }
  79549. if (this._yawRange > Math.PI) {
  79550. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79551. localTarget.z = this._maxYawCos * xzlen;
  79552. localTarget.x = this._maxYawSin * xzlen;
  79553. newYaw = this._maxYaw;
  79554. }
  79555. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79556. localTarget.z = this._minYawCos * xzlen;
  79557. localTarget.x = this._minYawSin * xzlen;
  79558. newYaw = this._minYaw;
  79559. }
  79560. }
  79561. else {
  79562. if (yaw > this._maxYaw) {
  79563. localTarget.z = this._maxYawCos * xzlen;
  79564. localTarget.x = this._maxYawSin * xzlen;
  79565. newYaw = this._maxYaw;
  79566. }
  79567. else if (yaw < this._minYaw) {
  79568. localTarget.z = this._minYawCos * xzlen;
  79569. localTarget.x = this._minYawSin * xzlen;
  79570. newYaw = this._minYaw;
  79571. }
  79572. }
  79573. }
  79574. if (this._slerping && this._yawRange > Math.PI) {
  79575. //are we going to be crossing into the min/max region?
  79576. var boneFwd = BoneLookController._tmpVecs[8];
  79577. boneFwd.copyFrom(BABYLON.Axis.Z);
  79578. if (this._transformYawPitch) {
  79579. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79580. }
  79581. var boneRotMat = BoneLookController._tmpMats[4];
  79582. this._boneQuat.toRotationMatrix(boneRotMat);
  79583. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79584. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79585. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79586. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79587. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79588. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79589. if (angBtwTar > angBtwMidYaw) {
  79590. if (xzlen == null) {
  79591. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79592. }
  79593. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79594. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79595. if (angBtwMin < angBtwMax) {
  79596. newYaw = boneYaw + Math.PI * .75;
  79597. localTarget.z = Math.cos(newYaw) * xzlen;
  79598. localTarget.x = Math.sin(newYaw) * xzlen;
  79599. }
  79600. else {
  79601. newYaw = boneYaw - Math.PI * .75;
  79602. localTarget.z = Math.cos(newYaw) * xzlen;
  79603. localTarget.x = Math.sin(newYaw) * xzlen;
  79604. }
  79605. }
  79606. }
  79607. if (yaw != newYaw) {
  79608. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79609. localTarget.addInPlace(bonePos);
  79610. target = localTarget;
  79611. }
  79612. }
  79613. }
  79614. var zaxis = BoneLookController._tmpVecs[5];
  79615. var xaxis = BoneLookController._tmpVecs[6];
  79616. var yaxis = BoneLookController._tmpVecs[7];
  79617. var _tmpQuat = BoneLookController._tmpQuat;
  79618. target.subtractToRef(bonePos, zaxis);
  79619. zaxis.normalize();
  79620. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79621. xaxis.normalize();
  79622. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79623. yaxis.normalize();
  79624. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79625. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79626. return;
  79627. }
  79628. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79629. return;
  79630. }
  79631. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79632. return;
  79633. }
  79634. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79635. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79636. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79637. }
  79638. if (this.slerpAmount < 1) {
  79639. if (!this._slerping) {
  79640. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79641. }
  79642. if (this._transformYawPitch) {
  79643. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79644. }
  79645. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79646. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79647. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79648. this._slerping = true;
  79649. }
  79650. else {
  79651. if (this._transformYawPitch) {
  79652. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79653. }
  79654. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79655. this._slerping = false;
  79656. }
  79657. };
  79658. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79659. var angDiff = ang2 - ang1;
  79660. angDiff %= Math.PI * 2;
  79661. if (angDiff > Math.PI) {
  79662. angDiff -= Math.PI * 2;
  79663. }
  79664. else if (angDiff < -Math.PI) {
  79665. angDiff += Math.PI * 2;
  79666. }
  79667. return angDiff;
  79668. };
  79669. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79670. ang1 %= (2 * Math.PI);
  79671. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79672. ang2 %= (2 * Math.PI);
  79673. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79674. var ab = 0;
  79675. if (ang1 < ang2) {
  79676. ab = ang2 - ang1;
  79677. }
  79678. else {
  79679. ab = ang1 - ang2;
  79680. }
  79681. if (ab > Math.PI) {
  79682. ab = Math.PI * 2 - ab;
  79683. }
  79684. return ab;
  79685. };
  79686. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79687. ang %= (2 * Math.PI);
  79688. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79689. ang1 %= (2 * Math.PI);
  79690. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79691. ang2 %= (2 * Math.PI);
  79692. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79693. if (ang1 < ang2) {
  79694. if (ang > ang1 && ang < ang2) {
  79695. return true;
  79696. }
  79697. }
  79698. else {
  79699. if (ang > ang2 && ang < ang1) {
  79700. return true;
  79701. }
  79702. }
  79703. return false;
  79704. };
  79705. 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()];
  79706. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79707. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79708. return BoneLookController;
  79709. }());
  79710. BABYLON.BoneLookController = BoneLookController;
  79711. })(BABYLON || (BABYLON = {}));
  79712. //# sourceMappingURL=babylon.boneLookController.js.map
  79713. var BABYLON;
  79714. (function (BABYLON) {
  79715. /**
  79716. * Class used to handle skinning animations
  79717. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79718. */
  79719. var Skeleton = /** @class */ (function () {
  79720. /**
  79721. * Creates a new skeleton
  79722. * @param name defines the skeleton name
  79723. * @param id defines the skeleton Id
  79724. * @param scene defines the hosting scene
  79725. */
  79726. function Skeleton(
  79727. /** defines the skeleton name */
  79728. name,
  79729. /** defines the skeleton Id */
  79730. id, scene) {
  79731. this.name = name;
  79732. this.id = id;
  79733. /**
  79734. * Gets the list of child bones
  79735. */
  79736. this.bones = new Array();
  79737. /**
  79738. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79739. */
  79740. this.needInitialSkinMatrix = false;
  79741. this._isDirty = true;
  79742. this._meshesWithPoseMatrix = new Array();
  79743. this._identity = BABYLON.Matrix.Identity();
  79744. this._ranges = {};
  79745. this._lastAbsoluteTransformsUpdateId = -1;
  79746. /**
  79747. * Specifies if the skeleton should be serialized
  79748. */
  79749. this.doNotSerialize = false;
  79750. this._animationPropertiesOverride = null;
  79751. // Events
  79752. /**
  79753. * An observable triggered before computing the skeleton's matrices
  79754. */
  79755. this.onBeforeComputeObservable = new BABYLON.Observable();
  79756. this.bones = [];
  79757. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79758. scene.skeletons.push(this);
  79759. //make sure it will recalculate the matrix next time prepare is called.
  79760. this._isDirty = true;
  79761. }
  79762. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79763. /**
  79764. * Gets or sets the animation properties override
  79765. */
  79766. get: function () {
  79767. if (!this._animationPropertiesOverride) {
  79768. return this._scene.animationPropertiesOverride;
  79769. }
  79770. return this._animationPropertiesOverride;
  79771. },
  79772. set: function (value) {
  79773. this._animationPropertiesOverride = value;
  79774. },
  79775. enumerable: true,
  79776. configurable: true
  79777. });
  79778. // Members
  79779. /**
  79780. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79781. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79782. * @returns a Float32Array containing matrices data
  79783. */
  79784. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79785. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79786. return mesh._bonesTransformMatrices;
  79787. }
  79788. if (!this._transformMatrices) {
  79789. this.prepare();
  79790. }
  79791. return this._transformMatrices;
  79792. };
  79793. /**
  79794. * Gets the current hosting scene
  79795. * @returns a scene object
  79796. */
  79797. Skeleton.prototype.getScene = function () {
  79798. return this._scene;
  79799. };
  79800. // Methods
  79801. /**
  79802. * Gets a string representing the current skeleton data
  79803. * @param fullDetails defines a boolean indicating if we want a verbose version
  79804. * @returns a string representing the current skeleton data
  79805. */
  79806. Skeleton.prototype.toString = function (fullDetails) {
  79807. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79808. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79809. if (fullDetails) {
  79810. ret += ", Ranges: {";
  79811. var first = true;
  79812. for (var name_1 in this._ranges) {
  79813. if (first) {
  79814. ret += ", ";
  79815. first = false;
  79816. }
  79817. ret += name_1;
  79818. }
  79819. ret += "}";
  79820. }
  79821. return ret;
  79822. };
  79823. /**
  79824. * Get bone's index searching by name
  79825. * @param name defines bone's name to search for
  79826. * @return the indice of the bone. Returns -1 if not found
  79827. */
  79828. Skeleton.prototype.getBoneIndexByName = function (name) {
  79829. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79830. if (this.bones[boneIndex].name === name) {
  79831. return boneIndex;
  79832. }
  79833. }
  79834. return -1;
  79835. };
  79836. /**
  79837. * Creater a new animation range
  79838. * @param name defines the name of the range
  79839. * @param from defines the start key
  79840. * @param to defines the end key
  79841. */
  79842. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79843. // check name not already in use
  79844. if (!this._ranges[name]) {
  79845. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79846. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79847. if (this.bones[i].animations[0]) {
  79848. this.bones[i].animations[0].createRange(name, from, to);
  79849. }
  79850. }
  79851. }
  79852. };
  79853. /**
  79854. * Delete a specific animation range
  79855. * @param name defines the name of the range
  79856. * @param deleteFrames defines if frames must be removed as well
  79857. */
  79858. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79859. if (deleteFrames === void 0) { deleteFrames = true; }
  79860. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79861. if (this.bones[i].animations[0]) {
  79862. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79863. }
  79864. }
  79865. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79866. };
  79867. /**
  79868. * Gets a specific animation range
  79869. * @param name defines the name of the range to look for
  79870. * @returns the requested animation range or null if not found
  79871. */
  79872. Skeleton.prototype.getAnimationRange = function (name) {
  79873. return this._ranges[name];
  79874. };
  79875. /**
  79876. * Gets the list of all animation ranges defined on this skeleton
  79877. * @returns an array
  79878. */
  79879. Skeleton.prototype.getAnimationRanges = function () {
  79880. var animationRanges = [];
  79881. var name;
  79882. var i = 0;
  79883. for (name in this._ranges) {
  79884. animationRanges[i] = this._ranges[name];
  79885. i++;
  79886. }
  79887. return animationRanges;
  79888. };
  79889. /**
  79890. * Copy animation range from a source skeleton.
  79891. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79892. * @param source defines the source skeleton
  79893. * @param name defines the name of the range to copy
  79894. * @param rescaleAsRequired defines if rescaling must be applied if required
  79895. * @returns true if operation was successful
  79896. */
  79897. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79898. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79899. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79900. return false;
  79901. }
  79902. var ret = true;
  79903. var frameOffset = this._getHighestAnimationFrame() + 1;
  79904. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79905. var boneDict = {};
  79906. var sourceBones = source.bones;
  79907. var nBones;
  79908. var i;
  79909. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79910. boneDict[sourceBones[i].name] = sourceBones[i];
  79911. }
  79912. if (this.bones.length !== sourceBones.length) {
  79913. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79914. ret = false;
  79915. }
  79916. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79917. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79918. var boneName = this.bones[i].name;
  79919. var sourceBone = boneDict[boneName];
  79920. if (sourceBone) {
  79921. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79922. }
  79923. else {
  79924. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79925. ret = false;
  79926. }
  79927. }
  79928. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79929. var range = source.getAnimationRange(name);
  79930. if (range) {
  79931. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79932. }
  79933. return ret;
  79934. };
  79935. /**
  79936. * Forces the skeleton to go to rest pose
  79937. */
  79938. Skeleton.prototype.returnToRest = function () {
  79939. for (var index = 0; index < this.bones.length; index++) {
  79940. this.bones[index].returnToRest();
  79941. }
  79942. };
  79943. Skeleton.prototype._getHighestAnimationFrame = function () {
  79944. var ret = 0;
  79945. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79946. if (this.bones[i].animations[0]) {
  79947. var highest = this.bones[i].animations[0].getHighestFrame();
  79948. if (ret < highest) {
  79949. ret = highest;
  79950. }
  79951. }
  79952. }
  79953. return ret;
  79954. };
  79955. /**
  79956. * Begin a specific animation range
  79957. * @param name defines the name of the range to start
  79958. * @param loop defines if looping must be turned on (false by default)
  79959. * @param speedRatio defines the speed ratio to apply (1 by default)
  79960. * @param onAnimationEnd defines a callback which will be called when animation will end
  79961. * @returns a new animatable
  79962. */
  79963. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79964. var range = this.getAnimationRange(name);
  79965. if (!range) {
  79966. return null;
  79967. }
  79968. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79969. };
  79970. /** @hidden */
  79971. Skeleton.prototype._markAsDirty = function () {
  79972. this._isDirty = true;
  79973. };
  79974. /** @hidden */
  79975. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79976. this._meshesWithPoseMatrix.push(mesh);
  79977. };
  79978. /** @hidden */
  79979. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79980. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79981. if (index > -1) {
  79982. this._meshesWithPoseMatrix.splice(index, 1);
  79983. }
  79984. };
  79985. /** @hidden */
  79986. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79987. this.onBeforeComputeObservable.notifyObservers(this);
  79988. for (var index = 0; index < this.bones.length; index++) {
  79989. var bone = this.bones[index];
  79990. var parentBone = bone.getParent();
  79991. if (parentBone) {
  79992. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79993. }
  79994. else {
  79995. if (initialSkinMatrix) {
  79996. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79997. }
  79998. else {
  79999. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80000. }
  80001. }
  80002. if (bone._index !== -1) {
  80003. var mappedIndex = bone._index === null ? index : bone._index;
  80004. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80005. }
  80006. }
  80007. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80008. };
  80009. /**
  80010. * Build all resources required to render a skeleton
  80011. */
  80012. Skeleton.prototype.prepare = function () {
  80013. if (!this._isDirty) {
  80014. return;
  80015. }
  80016. if (this.needInitialSkinMatrix) {
  80017. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80018. var mesh = this._meshesWithPoseMatrix[index];
  80019. var poseMatrix = mesh.getPoseMatrix();
  80020. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80021. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80022. }
  80023. if (this._synchronizedWithMesh !== mesh) {
  80024. this._synchronizedWithMesh = mesh;
  80025. // Prepare bones
  80026. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80027. var bone = this.bones[boneIndex];
  80028. if (!bone.getParent()) {
  80029. var matrix = bone.getBaseMatrix();
  80030. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80031. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80032. }
  80033. }
  80034. }
  80035. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80036. }
  80037. }
  80038. else {
  80039. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80040. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80041. }
  80042. this._computeTransformMatrices(this._transformMatrices, null);
  80043. }
  80044. this._isDirty = false;
  80045. this._scene._activeBones.addCount(this.bones.length, false);
  80046. };
  80047. /**
  80048. * Gets the list of animatables currently running for this skeleton
  80049. * @returns an array of animatables
  80050. */
  80051. Skeleton.prototype.getAnimatables = function () {
  80052. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80053. this._animatables = [];
  80054. for (var index = 0; index < this.bones.length; index++) {
  80055. this._animatables.push(this.bones[index]);
  80056. }
  80057. }
  80058. return this._animatables;
  80059. };
  80060. /**
  80061. * Clone the current skeleton
  80062. * @param name defines the name of the new skeleton
  80063. * @param id defines the id of the enw skeleton
  80064. * @returns the new skeleton
  80065. */
  80066. Skeleton.prototype.clone = function (name, id) {
  80067. var result = new Skeleton(name, id || name, this._scene);
  80068. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80069. for (var index = 0; index < this.bones.length; index++) {
  80070. var source = this.bones[index];
  80071. var parentBone = null;
  80072. var parent_1 = source.getParent();
  80073. if (parent_1) {
  80074. var parentIndex = this.bones.indexOf(parent_1);
  80075. parentBone = result.bones[parentIndex];
  80076. }
  80077. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80078. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80079. }
  80080. if (this._ranges) {
  80081. result._ranges = {};
  80082. for (var rangeName in this._ranges) {
  80083. var range = this._ranges[rangeName];
  80084. if (range) {
  80085. result._ranges[rangeName] = range.clone();
  80086. }
  80087. }
  80088. }
  80089. this._isDirty = true;
  80090. return result;
  80091. };
  80092. /**
  80093. * Enable animation blending for this skeleton
  80094. * @param blendingSpeed defines the blending speed to apply
  80095. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80096. */
  80097. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80098. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80099. this.bones.forEach(function (bone) {
  80100. bone.animations.forEach(function (animation) {
  80101. animation.enableBlending = true;
  80102. animation.blendingSpeed = blendingSpeed;
  80103. });
  80104. });
  80105. };
  80106. /**
  80107. * Releases all resources associated with the current skeleton
  80108. */
  80109. Skeleton.prototype.dispose = function () {
  80110. this._meshesWithPoseMatrix = [];
  80111. // Animations
  80112. this.getScene().stopAnimation(this);
  80113. // Remove from scene
  80114. this.getScene().removeSkeleton(this);
  80115. };
  80116. /**
  80117. * Serialize the skeleton in a JSON object
  80118. * @returns a JSON object
  80119. */
  80120. Skeleton.prototype.serialize = function () {
  80121. var serializationObject = {};
  80122. serializationObject.name = this.name;
  80123. serializationObject.id = this.id;
  80124. if (this.dimensionsAtRest) {
  80125. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80126. }
  80127. serializationObject.bones = [];
  80128. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80129. for (var index = 0; index < this.bones.length; index++) {
  80130. var bone = this.bones[index];
  80131. var parent_2 = bone.getParent();
  80132. var serializedBone = {
  80133. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80134. name: bone.name,
  80135. matrix: bone.getBaseMatrix().toArray(),
  80136. rest: bone.getRestPose().toArray()
  80137. };
  80138. serializationObject.bones.push(serializedBone);
  80139. if (bone.length) {
  80140. serializedBone.length = bone.length;
  80141. }
  80142. if (bone.metadata) {
  80143. serializedBone.metadata = bone.metadata;
  80144. }
  80145. if (bone.animations && bone.animations.length > 0) {
  80146. serializedBone.animation = bone.animations[0].serialize();
  80147. }
  80148. serializationObject.ranges = [];
  80149. for (var name in this._ranges) {
  80150. var source = this._ranges[name];
  80151. if (!source) {
  80152. continue;
  80153. }
  80154. var range = {};
  80155. range.name = name;
  80156. range.from = source.from;
  80157. range.to = source.to;
  80158. serializationObject.ranges.push(range);
  80159. }
  80160. }
  80161. return serializationObject;
  80162. };
  80163. /**
  80164. * Creates a new skeleton from serialized data
  80165. * @param parsedSkeleton defines the serialized data
  80166. * @param scene defines the hosting scene
  80167. * @returns a new skeleton
  80168. */
  80169. Skeleton.Parse = function (parsedSkeleton, scene) {
  80170. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80171. if (parsedSkeleton.dimensionsAtRest) {
  80172. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80173. }
  80174. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80175. var index;
  80176. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80177. var parsedBone = parsedSkeleton.bones[index];
  80178. var parentBone = null;
  80179. if (parsedBone.parentBoneIndex > -1) {
  80180. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80181. }
  80182. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80183. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80184. if (parsedBone.length) {
  80185. bone.length = parsedBone.length;
  80186. }
  80187. if (parsedBone.metadata) {
  80188. bone.metadata = parsedBone.metadata;
  80189. }
  80190. if (parsedBone.animation) {
  80191. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80192. }
  80193. }
  80194. // placed after bones, so createAnimationRange can cascade down
  80195. if (parsedSkeleton.ranges) {
  80196. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80197. var data = parsedSkeleton.ranges[index];
  80198. skeleton.createAnimationRange(data.name, data.from, data.to);
  80199. }
  80200. }
  80201. return skeleton;
  80202. };
  80203. /**
  80204. * Compute all node absolute transforms
  80205. * @param forceUpdate defines if computation must be done even if cache is up to date
  80206. */
  80207. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80208. if (forceUpdate === void 0) { forceUpdate = false; }
  80209. var renderId = this._scene.getRenderId();
  80210. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80211. this.bones[0].computeAbsoluteTransforms();
  80212. this._lastAbsoluteTransformsUpdateId = renderId;
  80213. }
  80214. };
  80215. /**
  80216. * Gets the root pose matrix
  80217. * @returns a matrix
  80218. */
  80219. Skeleton.prototype.getPoseMatrix = function () {
  80220. var poseMatrix = null;
  80221. if (this._meshesWithPoseMatrix.length > 0) {
  80222. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80223. }
  80224. return poseMatrix;
  80225. };
  80226. /**
  80227. * Sorts bones per internal index
  80228. */
  80229. Skeleton.prototype.sortBones = function () {
  80230. var bones = new Array();
  80231. var visited = new Array(this.bones.length);
  80232. for (var index = 0; index < this.bones.length; index++) {
  80233. this._sortBones(index, bones, visited);
  80234. }
  80235. this.bones = bones;
  80236. };
  80237. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80238. if (visited[index]) {
  80239. return;
  80240. }
  80241. visited[index] = true;
  80242. var bone = this.bones[index];
  80243. if (bone._index === undefined) {
  80244. bone._index = index;
  80245. }
  80246. var parentBone = bone.getParent();
  80247. if (parentBone) {
  80248. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80249. }
  80250. bones.push(bone);
  80251. };
  80252. return Skeleton;
  80253. }());
  80254. BABYLON.Skeleton = Skeleton;
  80255. })(BABYLON || (BABYLON = {}));
  80256. //# sourceMappingURL=babylon.skeleton.js.map
  80257. var BABYLON;
  80258. (function (BABYLON) {
  80259. var SphericalPolynomial = /** @class */ (function () {
  80260. function SphericalPolynomial() {
  80261. this.x = BABYLON.Vector3.Zero();
  80262. this.y = BABYLON.Vector3.Zero();
  80263. this.z = BABYLON.Vector3.Zero();
  80264. this.xx = BABYLON.Vector3.Zero();
  80265. this.yy = BABYLON.Vector3.Zero();
  80266. this.zz = BABYLON.Vector3.Zero();
  80267. this.xy = BABYLON.Vector3.Zero();
  80268. this.yz = BABYLON.Vector3.Zero();
  80269. this.zx = BABYLON.Vector3.Zero();
  80270. }
  80271. SphericalPolynomial.prototype.addAmbient = function (color) {
  80272. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80273. this.xx = this.xx.add(colorVector);
  80274. this.yy = this.yy.add(colorVector);
  80275. this.zz = this.zz.add(colorVector);
  80276. };
  80277. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80278. var result = new SphericalPolynomial();
  80279. result.x = harmonics.L11.scale(1.02333);
  80280. result.y = harmonics.L1_1.scale(1.02333);
  80281. result.z = harmonics.L10.scale(1.02333);
  80282. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80283. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80284. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80285. result.yz = harmonics.L2_1.scale(0.858086);
  80286. result.zx = harmonics.L21.scale(0.858086);
  80287. result.xy = harmonics.L2_2.scale(0.858086);
  80288. result.scale(1.0 / Math.PI);
  80289. return result;
  80290. };
  80291. SphericalPolynomial.prototype.scale = function (scale) {
  80292. this.x = this.x.scale(scale);
  80293. this.y = this.y.scale(scale);
  80294. this.z = this.z.scale(scale);
  80295. this.xx = this.xx.scale(scale);
  80296. this.yy = this.yy.scale(scale);
  80297. this.zz = this.zz.scale(scale);
  80298. this.yz = this.yz.scale(scale);
  80299. this.zx = this.zx.scale(scale);
  80300. this.xy = this.xy.scale(scale);
  80301. };
  80302. return SphericalPolynomial;
  80303. }());
  80304. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80305. var SphericalHarmonics = /** @class */ (function () {
  80306. function SphericalHarmonics() {
  80307. this.L00 = BABYLON.Vector3.Zero();
  80308. this.L1_1 = BABYLON.Vector3.Zero();
  80309. this.L10 = BABYLON.Vector3.Zero();
  80310. this.L11 = BABYLON.Vector3.Zero();
  80311. this.L2_2 = BABYLON.Vector3.Zero();
  80312. this.L2_1 = BABYLON.Vector3.Zero();
  80313. this.L20 = BABYLON.Vector3.Zero();
  80314. this.L21 = BABYLON.Vector3.Zero();
  80315. this.L22 = BABYLON.Vector3.Zero();
  80316. }
  80317. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80318. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80319. var c = colorVector.scale(deltaSolidAngle);
  80320. this.L00 = this.L00.add(c.scale(0.282095));
  80321. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80322. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80323. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80324. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80325. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80326. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80327. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80328. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80329. };
  80330. SphericalHarmonics.prototype.scale = function (scale) {
  80331. this.L00 = this.L00.scale(scale);
  80332. this.L1_1 = this.L1_1.scale(scale);
  80333. this.L10 = this.L10.scale(scale);
  80334. this.L11 = this.L11.scale(scale);
  80335. this.L2_2 = this.L2_2.scale(scale);
  80336. this.L2_1 = this.L2_1.scale(scale);
  80337. this.L20 = this.L20.scale(scale);
  80338. this.L21 = this.L21.scale(scale);
  80339. this.L22 = this.L22.scale(scale);
  80340. };
  80341. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80342. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80343. //
  80344. // E_lm = A_l * L_lm
  80345. //
  80346. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80347. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80348. // the scaling factors are given in equation 9.
  80349. // Constant (Band 0)
  80350. this.L00 = this.L00.scale(3.141593);
  80351. // Linear (Band 1)
  80352. this.L1_1 = this.L1_1.scale(2.094395);
  80353. this.L10 = this.L10.scale(2.094395);
  80354. this.L11 = this.L11.scale(2.094395);
  80355. // Quadratic (Band 2)
  80356. this.L2_2 = this.L2_2.scale(0.785398);
  80357. this.L2_1 = this.L2_1.scale(0.785398);
  80358. this.L20 = this.L20.scale(0.785398);
  80359. this.L21 = this.L21.scale(0.785398);
  80360. this.L22 = this.L22.scale(0.785398);
  80361. };
  80362. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80363. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80364. // L = (1/pi) * E * rho
  80365. //
  80366. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80367. this.scale(1.0 / Math.PI);
  80368. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80369. // (The pixel shader must apply albedo after texture fetches, etc).
  80370. };
  80371. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80372. var result = new SphericalHarmonics();
  80373. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80374. result.L1_1 = polynomial.y.scale(0.977204);
  80375. result.L10 = polynomial.z.scale(0.977204);
  80376. result.L11 = polynomial.x.scale(0.977204);
  80377. result.L2_2 = polynomial.xy.scale(1.16538);
  80378. result.L2_1 = polynomial.yz.scale(1.16538);
  80379. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80380. result.L21 = polynomial.zx.scale(1.16538);
  80381. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80382. result.scale(Math.PI);
  80383. return result;
  80384. };
  80385. return SphericalHarmonics;
  80386. }());
  80387. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80388. })(BABYLON || (BABYLON = {}));
  80389. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80390. var BABYLON;
  80391. (function (BABYLON) {
  80392. var FileFaceOrientation = /** @class */ (function () {
  80393. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80394. this.name = name;
  80395. this.worldAxisForNormal = worldAxisForNormal;
  80396. this.worldAxisForFileX = worldAxisForFileX;
  80397. this.worldAxisForFileY = worldAxisForFileY;
  80398. }
  80399. return FileFaceOrientation;
  80400. }());
  80401. ;
  80402. /**
  80403. * Helper class dealing with the extraction of spherical polynomial dataArray
  80404. * from a cube map.
  80405. */
  80406. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80407. function CubeMapToSphericalPolynomialTools() {
  80408. }
  80409. /**
  80410. * Converts a texture to the according Spherical Polynomial data.
  80411. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80412. *
  80413. * @param texture The texture to extract the information from.
  80414. * @return The Spherical Polynomial data.
  80415. */
  80416. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80417. if (!texture.isCube) {
  80418. // Only supports cube Textures currently.
  80419. return null;
  80420. }
  80421. var size = texture.getSize().width;
  80422. var right = texture.readPixels(0);
  80423. var left = texture.readPixels(1);
  80424. var up;
  80425. var down;
  80426. if (texture.isRenderTarget) {
  80427. up = texture.readPixels(3);
  80428. down = texture.readPixels(2);
  80429. }
  80430. else {
  80431. up = texture.readPixels(2);
  80432. down = texture.readPixels(3);
  80433. }
  80434. var front = texture.readPixels(4);
  80435. var back = texture.readPixels(5);
  80436. var gammaSpace = texture.gammaSpace;
  80437. // Always read as RGBA.
  80438. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80439. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80440. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80441. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80442. }
  80443. var cubeInfo = {
  80444. size: size,
  80445. right: right,
  80446. left: left,
  80447. up: up,
  80448. down: down,
  80449. front: front,
  80450. back: back,
  80451. format: format,
  80452. type: type,
  80453. gammaSpace: gammaSpace,
  80454. };
  80455. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80456. };
  80457. /**
  80458. * Converts a cubemap to the according Spherical Polynomial data.
  80459. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80460. *
  80461. * @param cubeInfo The Cube map to extract the information from.
  80462. * @return The Spherical Polynomial data.
  80463. */
  80464. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80465. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80466. var totalSolidAngle = 0.0;
  80467. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80468. var du = 2.0 / cubeInfo.size;
  80469. var dv = du;
  80470. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80471. var minUV = du * 0.5 - 1.0;
  80472. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80473. var fileFace = this.FileFaces[faceIndex];
  80474. var dataArray = cubeInfo[fileFace.name];
  80475. var v = minUV;
  80476. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80477. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80478. // Because SP is still linear, so summation is fine in that basis.
  80479. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80480. for (var y = 0; y < cubeInfo.size; y++) {
  80481. var u = minUV;
  80482. for (var x = 0; x < cubeInfo.size; x++) {
  80483. // World direction (not normalised)
  80484. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80485. worldDirection.normalize();
  80486. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80487. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80488. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80489. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80490. // Handle Integer types.
  80491. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80492. r /= 255;
  80493. g /= 255;
  80494. b /= 255;
  80495. }
  80496. // Handle Gamma space textures.
  80497. if (cubeInfo.gammaSpace) {
  80498. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80499. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80500. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80501. }
  80502. var color = new BABYLON.Color3(r, g, b);
  80503. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80504. totalSolidAngle += deltaSolidAngle;
  80505. u += du;
  80506. }
  80507. v += dv;
  80508. }
  80509. }
  80510. // Solid angle for entire sphere is 4*pi
  80511. var sphereSolidAngle = 4.0 * Math.PI;
  80512. // Adjust the solid angle to allow for how many faces we processed.
  80513. var facesProcessed = 6.0;
  80514. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80515. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80516. // This is needed because the numerical integration over the cube uses a
  80517. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80518. // and also to compensate for accumulative error due to float precision in the summation.
  80519. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80520. sphericalHarmonics.scale(correctionFactor);
  80521. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80522. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80523. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80524. };
  80525. CubeMapToSphericalPolynomialTools.FileFaces = [
  80526. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80527. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80528. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80529. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80530. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80531. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80532. ];
  80533. return CubeMapToSphericalPolynomialTools;
  80534. }());
  80535. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80536. })(BABYLON || (BABYLON = {}));
  80537. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80538. var BABYLON;
  80539. (function (BABYLON) {
  80540. /**
  80541. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80542. */
  80543. var PanoramaToCubeMapTools = /** @class */ (function () {
  80544. function PanoramaToCubeMapTools() {
  80545. }
  80546. /**
  80547. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80548. *
  80549. * @param float32Array The source data.
  80550. * @param inputWidth The width of the input panorama.
  80551. * @param inputhHeight The height of the input panorama.
  80552. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80553. * @return The cubemap data
  80554. */
  80555. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80556. if (!float32Array) {
  80557. throw "ConvertPanoramaToCubemap: input cannot be null";
  80558. }
  80559. if (float32Array.length != inputWidth * inputHeight * 3) {
  80560. throw "ConvertPanoramaToCubemap: input size is wrong";
  80561. }
  80562. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80563. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80564. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80565. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80566. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80567. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80568. return {
  80569. front: textureFront,
  80570. back: textureBack,
  80571. left: textureLeft,
  80572. right: textureRight,
  80573. up: textureUp,
  80574. down: textureDown,
  80575. size: size,
  80576. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80577. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80578. gammaSpace: false,
  80579. };
  80580. };
  80581. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80582. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80583. var textureArray = new Float32Array(buffer);
  80584. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80585. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80586. var dy = 1 / texSize;
  80587. var fy = 0;
  80588. for (var y = 0; y < texSize; y++) {
  80589. var xv1 = faceData[0];
  80590. var xv2 = faceData[2];
  80591. for (var x = 0; x < texSize; x++) {
  80592. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80593. v.normalize();
  80594. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80595. // 3 channels per pixels
  80596. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80597. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80598. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80599. xv1 = xv1.add(rotDX1);
  80600. xv2 = xv2.add(rotDX2);
  80601. }
  80602. fy += dy;
  80603. }
  80604. return textureArray;
  80605. };
  80606. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80607. var theta = Math.atan2(vDir.z, vDir.x);
  80608. var phi = Math.acos(vDir.y);
  80609. while (theta < -Math.PI)
  80610. theta += 2 * Math.PI;
  80611. while (theta > Math.PI)
  80612. theta -= 2 * Math.PI;
  80613. var dx = theta / Math.PI;
  80614. var dy = phi / Math.PI;
  80615. // recenter.
  80616. dx = dx * 0.5 + 0.5;
  80617. var px = Math.round(dx * inputWidth);
  80618. if (px < 0)
  80619. px = 0;
  80620. else if (px >= inputWidth)
  80621. px = inputWidth - 1;
  80622. var py = Math.round(dy * inputHeight);
  80623. if (py < 0)
  80624. py = 0;
  80625. else if (py >= inputHeight)
  80626. py = inputHeight - 1;
  80627. var inputY = (inputHeight - py - 1);
  80628. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80629. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80630. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80631. return {
  80632. r: r,
  80633. g: g,
  80634. b: b
  80635. };
  80636. };
  80637. PanoramaToCubeMapTools.FACE_FRONT = [
  80638. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80639. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80640. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80641. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80642. ];
  80643. PanoramaToCubeMapTools.FACE_BACK = [
  80644. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80645. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80646. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80647. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80648. ];
  80649. PanoramaToCubeMapTools.FACE_RIGHT = [
  80650. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80651. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80652. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80653. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80654. ];
  80655. PanoramaToCubeMapTools.FACE_LEFT = [
  80656. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80657. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80658. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80659. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80660. ];
  80661. PanoramaToCubeMapTools.FACE_DOWN = [
  80662. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80663. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80664. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80665. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80666. ];
  80667. PanoramaToCubeMapTools.FACE_UP = [
  80668. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80669. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80670. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80671. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80672. ];
  80673. return PanoramaToCubeMapTools;
  80674. }());
  80675. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80676. })(BABYLON || (BABYLON = {}));
  80677. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80678. var BABYLON;
  80679. (function (BABYLON) {
  80680. ;
  80681. /**
  80682. * This groups tools to convert HDR texture to native colors array.
  80683. */
  80684. var HDRTools = /** @class */ (function () {
  80685. function HDRTools() {
  80686. }
  80687. HDRTools.Ldexp = function (mantissa, exponent) {
  80688. if (exponent > 1023) {
  80689. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80690. }
  80691. if (exponent < -1074) {
  80692. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80693. }
  80694. return mantissa * Math.pow(2, exponent);
  80695. };
  80696. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80697. if (exponent > 0) { /*nonzero pixel*/
  80698. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80699. float32array[index + 0] = red * exponent;
  80700. float32array[index + 1] = green * exponent;
  80701. float32array[index + 2] = blue * exponent;
  80702. }
  80703. else {
  80704. float32array[index + 0] = 0;
  80705. float32array[index + 1] = 0;
  80706. float32array[index + 2] = 0;
  80707. }
  80708. };
  80709. HDRTools.readStringLine = function (uint8array, startIndex) {
  80710. var line = "";
  80711. var character = "";
  80712. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80713. character = String.fromCharCode(uint8array[i]);
  80714. if (character == "\n") {
  80715. break;
  80716. }
  80717. line += character;
  80718. }
  80719. return line;
  80720. };
  80721. /**
  80722. * Reads header information from an RGBE texture stored in a native array.
  80723. * More information on this format are available here:
  80724. * https://en.wikipedia.org/wiki/RGBE_image_format
  80725. *
  80726. * @param uint8array The binary file stored in native array.
  80727. * @return The header information.
  80728. */
  80729. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80730. var height = 0;
  80731. var width = 0;
  80732. var line = this.readStringLine(uint8array, 0);
  80733. if (line[0] != '#' || line[1] != '?') {
  80734. throw "Bad HDR Format.";
  80735. }
  80736. var endOfHeader = false;
  80737. var findFormat = false;
  80738. var lineIndex = 0;
  80739. do {
  80740. lineIndex += (line.length + 1);
  80741. line = this.readStringLine(uint8array, lineIndex);
  80742. if (line == "FORMAT=32-bit_rle_rgbe") {
  80743. findFormat = true;
  80744. }
  80745. else if (line.length == 0) {
  80746. endOfHeader = true;
  80747. }
  80748. } while (!endOfHeader);
  80749. if (!findFormat) {
  80750. throw "HDR Bad header format, unsupported FORMAT";
  80751. }
  80752. lineIndex += (line.length + 1);
  80753. line = this.readStringLine(uint8array, lineIndex);
  80754. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80755. var match = sizeRegexp.exec(line);
  80756. // TODO. Support +Y and -X if needed.
  80757. if (!match || match.length < 3) {
  80758. throw "HDR Bad header format, no size";
  80759. }
  80760. width = parseInt(match[2]);
  80761. height = parseInt(match[1]);
  80762. if (width < 8 || width > 0x7fff) {
  80763. throw "HDR Bad header format, unsupported size";
  80764. }
  80765. lineIndex += (line.length + 1);
  80766. return {
  80767. height: height,
  80768. width: width,
  80769. dataPosition: lineIndex
  80770. };
  80771. };
  80772. /**
  80773. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80774. * This RGBE texture needs to store the information as a panorama.
  80775. *
  80776. * More information on this format are available here:
  80777. * https://en.wikipedia.org/wiki/RGBE_image_format
  80778. *
  80779. * @param buffer The binary file stored in an array buffer.
  80780. * @param size The expected size of the extracted cubemap.
  80781. * @return The Cube Map information.
  80782. */
  80783. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80784. var uint8array = new Uint8Array(buffer);
  80785. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80786. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80787. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80788. return cubeMapData;
  80789. };
  80790. /**
  80791. * Returns the pixels data extracted from an RGBE texture.
  80792. * This pixels will be stored left to right up to down in the R G B order in one array.
  80793. *
  80794. * More information on this format are available here:
  80795. * https://en.wikipedia.org/wiki/RGBE_image_format
  80796. *
  80797. * @param uint8array The binary file stored in an array buffer.
  80798. * @param hdrInfo The header information of the file.
  80799. * @return The pixels data in RGB right to left up to down order.
  80800. */
  80801. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80802. // Keep for multi format supports.
  80803. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80804. };
  80805. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80806. var num_scanlines = hdrInfo.height;
  80807. var scanline_width = hdrInfo.width;
  80808. var a, b, c, d, count;
  80809. var dataIndex = hdrInfo.dataPosition;
  80810. var index = 0, endIndex = 0, i = 0;
  80811. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80812. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80813. // 3 channels of 4 bytes per pixel in float.
  80814. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80815. var resultArray = new Float32Array(resultBuffer);
  80816. // read in each successive scanline
  80817. while (num_scanlines > 0) {
  80818. a = uint8array[dataIndex++];
  80819. b = uint8array[dataIndex++];
  80820. c = uint8array[dataIndex++];
  80821. d = uint8array[dataIndex++];
  80822. if (a != 2 || b != 2 || (c & 0x80)) {
  80823. // this file is not run length encoded
  80824. throw "HDR Bad header format, not RLE";
  80825. }
  80826. if (((c << 8) | d) != scanline_width) {
  80827. throw "HDR Bad header format, wrong scan line width";
  80828. }
  80829. index = 0;
  80830. // read each of the four channels for the scanline into the buffer
  80831. for (i = 0; i < 4; i++) {
  80832. endIndex = (i + 1) * scanline_width;
  80833. while (index < endIndex) {
  80834. a = uint8array[dataIndex++];
  80835. b = uint8array[dataIndex++];
  80836. if (a > 128) {
  80837. // a run of the same value
  80838. count = a - 128;
  80839. if ((count == 0) || (count > endIndex - index)) {
  80840. throw "HDR Bad Format, bad scanline data (run)";
  80841. }
  80842. while (count-- > 0) {
  80843. scanLineArray[index++] = b;
  80844. }
  80845. }
  80846. else {
  80847. // a non-run
  80848. count = a;
  80849. if ((count == 0) || (count > endIndex - index)) {
  80850. throw "HDR Bad Format, bad scanline data (non-run)";
  80851. }
  80852. scanLineArray[index++] = b;
  80853. if (--count > 0) {
  80854. for (var j = 0; j < count; j++) {
  80855. scanLineArray[index++] = uint8array[dataIndex++];
  80856. }
  80857. }
  80858. }
  80859. }
  80860. }
  80861. // now convert data from buffer into floats
  80862. for (i = 0; i < scanline_width; i++) {
  80863. a = scanLineArray[i];
  80864. b = scanLineArray[i + scanline_width];
  80865. c = scanLineArray[i + 2 * scanline_width];
  80866. d = scanLineArray[i + 3 * scanline_width];
  80867. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80868. }
  80869. num_scanlines--;
  80870. }
  80871. return resultArray;
  80872. };
  80873. return HDRTools;
  80874. }());
  80875. BABYLON.HDRTools = HDRTools;
  80876. })(BABYLON || (BABYLON = {}));
  80877. //# sourceMappingURL=babylon.hdr.js.map
  80878. var BABYLON;
  80879. (function (BABYLON) {
  80880. /**
  80881. * This represents a texture coming from an HDR input.
  80882. *
  80883. * The only supported format is currently panorama picture stored in RGBE format.
  80884. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80885. */
  80886. var HDRCubeTexture = /** @class */ (function (_super) {
  80887. __extends(HDRCubeTexture, _super);
  80888. /**
  80889. * Instantiates an HDRTexture from the following parameters.
  80890. *
  80891. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80892. * @param scene The scene the texture will be used in
  80893. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80894. * @param noMipmap Forces to not generate the mipmap if true
  80895. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80896. * @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)
  80897. * @param reserved Reserved flag for internal use.
  80898. */
  80899. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80900. if (noMipmap === void 0) { noMipmap = false; }
  80901. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80902. if (gammaSpace === void 0) { gammaSpace = false; }
  80903. if (reserved === void 0) { reserved = false; }
  80904. if (onLoad === void 0) { onLoad = null; }
  80905. if (onError === void 0) { onError = null; }
  80906. var _this = _super.call(this, scene) || this;
  80907. _this._generateHarmonics = true;
  80908. _this._onLoad = null;
  80909. _this._onError = null;
  80910. /**
  80911. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80912. */
  80913. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80914. _this._isBlocking = true;
  80915. _this._rotationY = 0;
  80916. /**
  80917. * Gets or sets the center of the bounding box associated with the cube texture
  80918. * It must define where the camera used to render the texture was set
  80919. */
  80920. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80921. if (!url) {
  80922. return _this;
  80923. }
  80924. _this.name = url;
  80925. _this.url = url;
  80926. _this.hasAlpha = false;
  80927. _this.isCube = true;
  80928. _this._textureMatrix = BABYLON.Matrix.Identity();
  80929. _this._onLoad = onLoad;
  80930. _this._onError = onError;
  80931. _this.gammaSpace = gammaSpace;
  80932. _this._noMipmap = noMipmap;
  80933. _this._size = size;
  80934. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80935. if (!_this._texture) {
  80936. if (!scene.useDelayedTextureLoading) {
  80937. _this.loadTexture();
  80938. }
  80939. else {
  80940. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80941. }
  80942. }
  80943. return _this;
  80944. }
  80945. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80946. /**
  80947. * Gets wether or not the texture is blocking during loading.
  80948. */
  80949. get: function () {
  80950. return this._isBlocking;
  80951. },
  80952. /**
  80953. * Sets wether or not the texture is blocking during loading.
  80954. */
  80955. set: function (value) {
  80956. this._isBlocking = value;
  80957. },
  80958. enumerable: true,
  80959. configurable: true
  80960. });
  80961. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80962. /**
  80963. * Gets texture matrix rotation angle around Y axis radians.
  80964. */
  80965. get: function () {
  80966. return this._rotationY;
  80967. },
  80968. /**
  80969. * Sets texture matrix rotation angle around Y axis in radians.
  80970. */
  80971. set: function (value) {
  80972. this._rotationY = value;
  80973. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80974. },
  80975. enumerable: true,
  80976. configurable: true
  80977. });
  80978. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80979. get: function () {
  80980. return this._boundingBoxSize;
  80981. },
  80982. /**
  80983. * Gets or sets the size of the bounding box associated with the cube texture
  80984. * When defined, the cubemap will switch to local mode
  80985. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80986. * @example https://www.babylonjs-playground.com/#RNASML
  80987. */
  80988. set: function (value) {
  80989. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80990. return;
  80991. }
  80992. this._boundingBoxSize = value;
  80993. var scene = this.getScene();
  80994. if (scene) {
  80995. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80996. }
  80997. },
  80998. enumerable: true,
  80999. configurable: true
  81000. });
  81001. /**
  81002. * Occurs when the file is raw .hdr file.
  81003. */
  81004. HDRCubeTexture.prototype.loadTexture = function () {
  81005. var _this = this;
  81006. var callback = function (buffer) {
  81007. var scene = _this.getScene();
  81008. if (!scene) {
  81009. return null;
  81010. }
  81011. // Extract the raw linear data.
  81012. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81013. // Generate harmonics if needed.
  81014. if (_this._generateHarmonics) {
  81015. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81016. _this.sphericalPolynomial = sphericalPolynomial;
  81017. }
  81018. var results = [];
  81019. var byteArray = null;
  81020. // Push each faces.
  81021. for (var j = 0; j < 6; j++) {
  81022. // Create uintarray fallback.
  81023. if (!scene.getEngine().getCaps().textureFloat) {
  81024. // 3 channels of 1 bytes per pixel in bytes.
  81025. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81026. byteArray = new Uint8Array(byteBuffer);
  81027. }
  81028. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81029. // If special cases.
  81030. if (_this.gammaSpace || byteArray) {
  81031. for (var i = 0; i < _this._size * _this._size; i++) {
  81032. // Put in gamma space if requested.
  81033. if (_this.gammaSpace) {
  81034. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81035. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81036. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81037. }
  81038. // Convert to int texture for fallback.
  81039. if (byteArray) {
  81040. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81041. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81042. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81043. // May use luminance instead if the result is not accurate.
  81044. var max = Math.max(Math.max(r, g), b);
  81045. if (max > 255) {
  81046. var scale = 255 / max;
  81047. r *= scale;
  81048. g *= scale;
  81049. b *= scale;
  81050. }
  81051. byteArray[(i * 3) + 0] = r;
  81052. byteArray[(i * 3) + 1] = g;
  81053. byteArray[(i * 3) + 2] = b;
  81054. }
  81055. }
  81056. }
  81057. if (byteArray) {
  81058. results.push(byteArray);
  81059. }
  81060. else {
  81061. results.push(dataFace);
  81062. }
  81063. }
  81064. return results;
  81065. };
  81066. var scene = this.getScene();
  81067. if (scene) {
  81068. 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);
  81069. }
  81070. };
  81071. HDRCubeTexture.prototype.clone = function () {
  81072. var scene = this.getScene();
  81073. if (!scene) {
  81074. return this;
  81075. }
  81076. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81077. // Base texture
  81078. newTexture.level = this.level;
  81079. newTexture.wrapU = this.wrapU;
  81080. newTexture.wrapV = this.wrapV;
  81081. newTexture.coordinatesIndex = this.coordinatesIndex;
  81082. newTexture.coordinatesMode = this.coordinatesMode;
  81083. return newTexture;
  81084. };
  81085. // Methods
  81086. HDRCubeTexture.prototype.delayLoad = function () {
  81087. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81088. return;
  81089. }
  81090. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81091. this._texture = this._getFromCache(this.url, this._noMipmap);
  81092. if (!this._texture) {
  81093. this.loadTexture();
  81094. }
  81095. };
  81096. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81097. return this._textureMatrix;
  81098. };
  81099. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81100. this._textureMatrix = value;
  81101. };
  81102. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81103. var texture = null;
  81104. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81105. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81106. texture.name = parsedTexture.name;
  81107. texture.hasAlpha = parsedTexture.hasAlpha;
  81108. texture.level = parsedTexture.level;
  81109. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81110. texture.isBlocking = parsedTexture.isBlocking;
  81111. }
  81112. if (texture) {
  81113. if (parsedTexture.boundingBoxPosition) {
  81114. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81115. }
  81116. if (parsedTexture.boundingBoxSize) {
  81117. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81118. }
  81119. if (parsedTexture.rotationY) {
  81120. texture.rotationY = parsedTexture.rotationY;
  81121. }
  81122. }
  81123. return texture;
  81124. };
  81125. HDRCubeTexture.prototype.serialize = function () {
  81126. if (!this.name) {
  81127. return null;
  81128. }
  81129. var serializationObject = {};
  81130. serializationObject.name = this.name;
  81131. serializationObject.hasAlpha = this.hasAlpha;
  81132. serializationObject.isCube = true;
  81133. serializationObject.level = this.level;
  81134. serializationObject.size = this._size;
  81135. serializationObject.coordinatesMode = this.coordinatesMode;
  81136. serializationObject.useInGammaSpace = this.gammaSpace;
  81137. serializationObject.generateHarmonics = this._generateHarmonics;
  81138. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81139. serializationObject.noMipmap = this._noMipmap;
  81140. serializationObject.isBlocking = this._isBlocking;
  81141. serializationObject.rotationY = this._rotationY;
  81142. return serializationObject;
  81143. };
  81144. HDRCubeTexture._facesMapping = [
  81145. "right",
  81146. "left",
  81147. "up",
  81148. "down",
  81149. "front",
  81150. "back"
  81151. ];
  81152. return HDRCubeTexture;
  81153. }(BABYLON.BaseTexture));
  81154. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81155. })(BABYLON || (BABYLON = {}));
  81156. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81157. var BABYLON;
  81158. (function (BABYLON) {
  81159. var IndexedVector2 = /** @class */ (function (_super) {
  81160. __extends(IndexedVector2, _super);
  81161. function IndexedVector2(original, index) {
  81162. var _this = _super.call(this, original.x, original.y) || this;
  81163. _this.index = index;
  81164. return _this;
  81165. }
  81166. return IndexedVector2;
  81167. }(BABYLON.Vector2));
  81168. var PolygonPoints = /** @class */ (function () {
  81169. function PolygonPoints() {
  81170. this.elements = new Array();
  81171. }
  81172. PolygonPoints.prototype.add = function (originalPoints) {
  81173. var _this = this;
  81174. var result = new Array();
  81175. originalPoints.forEach(function (point) {
  81176. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81177. var newPoint = new IndexedVector2(point, _this.elements.length);
  81178. result.push(newPoint);
  81179. _this.elements.push(newPoint);
  81180. }
  81181. });
  81182. return result;
  81183. };
  81184. PolygonPoints.prototype.computeBounds = function () {
  81185. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81186. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81187. this.elements.forEach(function (point) {
  81188. // x
  81189. if (point.x < lmin.x) {
  81190. lmin.x = point.x;
  81191. }
  81192. else if (point.x > lmax.x) {
  81193. lmax.x = point.x;
  81194. }
  81195. // y
  81196. if (point.y < lmin.y) {
  81197. lmin.y = point.y;
  81198. }
  81199. else if (point.y > lmax.y) {
  81200. lmax.y = point.y;
  81201. }
  81202. });
  81203. return {
  81204. min: lmin,
  81205. max: lmax,
  81206. width: lmax.x - lmin.x,
  81207. height: lmax.y - lmin.y
  81208. };
  81209. };
  81210. return PolygonPoints;
  81211. }());
  81212. var Polygon = /** @class */ (function () {
  81213. function Polygon() {
  81214. }
  81215. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81216. return [
  81217. new BABYLON.Vector2(xmin, ymin),
  81218. new BABYLON.Vector2(xmax, ymin),
  81219. new BABYLON.Vector2(xmax, ymax),
  81220. new BABYLON.Vector2(xmin, ymax)
  81221. ];
  81222. };
  81223. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81224. if (cx === void 0) { cx = 0; }
  81225. if (cy === void 0) { cy = 0; }
  81226. if (numberOfSides === void 0) { numberOfSides = 32; }
  81227. var result = new Array();
  81228. var angle = 0;
  81229. var increment = (Math.PI * 2) / numberOfSides;
  81230. for (var i = 0; i < numberOfSides; i++) {
  81231. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81232. angle -= increment;
  81233. }
  81234. return result;
  81235. };
  81236. Polygon.Parse = function (input) {
  81237. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81238. var i, result = [];
  81239. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81240. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81241. }
  81242. return result;
  81243. };
  81244. Polygon.StartingAt = function (x, y) {
  81245. return BABYLON.Path2.StartingAt(x, y);
  81246. };
  81247. return Polygon;
  81248. }());
  81249. BABYLON.Polygon = Polygon;
  81250. var PolygonMeshBuilder = /** @class */ (function () {
  81251. function PolygonMeshBuilder(name, contours, scene) {
  81252. this._points = new PolygonPoints();
  81253. this._outlinepoints = new PolygonPoints();
  81254. this._holes = new Array();
  81255. this._epoints = new Array();
  81256. this._eholes = new Array();
  81257. this._name = name;
  81258. this._scene = scene;
  81259. var points;
  81260. if (contours instanceof BABYLON.Path2) {
  81261. points = contours.getPoints();
  81262. }
  81263. else {
  81264. points = contours;
  81265. }
  81266. this._addToepoint(points);
  81267. this._points.add(points);
  81268. this._outlinepoints.add(points);
  81269. if (typeof earcut === 'undefined') {
  81270. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81271. }
  81272. }
  81273. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81274. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81275. var p = points_1[_i];
  81276. this._epoints.push(p.x, p.y);
  81277. }
  81278. };
  81279. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81280. this._points.add(hole);
  81281. var holepoints = new PolygonPoints();
  81282. holepoints.add(hole);
  81283. this._holes.push(holepoints);
  81284. this._eholes.push(this._epoints.length / 2);
  81285. this._addToepoint(hole);
  81286. return this;
  81287. };
  81288. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81289. var _this = this;
  81290. if (updatable === void 0) { updatable = false; }
  81291. if (depth === void 0) { depth = 0; }
  81292. var result = new BABYLON.Mesh(this._name, this._scene);
  81293. var normals = new Array();
  81294. var positions = new Array();
  81295. var uvs = new Array();
  81296. var bounds = this._points.computeBounds();
  81297. this._points.elements.forEach(function (p) {
  81298. normals.push(0, 1.0, 0);
  81299. positions.push(p.x, 0, p.y);
  81300. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81301. });
  81302. var indices = new Array();
  81303. var res = earcut(this._epoints, this._eholes, 2);
  81304. for (var i = 0; i < res.length; i++) {
  81305. indices.push(res[i]);
  81306. }
  81307. if (depth > 0) {
  81308. var positionscount = (positions.length / 3); //get the current pointcount
  81309. this._points.elements.forEach(function (p) {
  81310. normals.push(0, -1.0, 0);
  81311. positions.push(p.x, -depth, p.y);
  81312. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81313. });
  81314. var totalCount = indices.length;
  81315. for (var i = 0; i < totalCount; i += 3) {
  81316. var i0 = indices[i + 0];
  81317. var i1 = indices[i + 1];
  81318. var i2 = indices[i + 2];
  81319. indices.push(i2 + positionscount);
  81320. indices.push(i1 + positionscount);
  81321. indices.push(i0 + positionscount);
  81322. }
  81323. //Add the sides
  81324. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81325. this._holes.forEach(function (hole) {
  81326. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81327. });
  81328. }
  81329. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81330. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81331. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81332. result.setIndices(indices);
  81333. return result;
  81334. };
  81335. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81336. var StartIndex = positions.length / 3;
  81337. var ulength = 0;
  81338. for (var i = 0; i < points.elements.length; i++) {
  81339. var p = points.elements[i];
  81340. var p1;
  81341. if ((i + 1) > points.elements.length - 1) {
  81342. p1 = points.elements[0];
  81343. }
  81344. else {
  81345. p1 = points.elements[i + 1];
  81346. }
  81347. positions.push(p.x, 0, p.y);
  81348. positions.push(p.x, -depth, p.y);
  81349. positions.push(p1.x, 0, p1.y);
  81350. positions.push(p1.x, -depth, p1.y);
  81351. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81352. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81353. var v3 = v2.subtract(v1);
  81354. var v4 = new BABYLON.Vector3(0, 1, 0);
  81355. var vn = BABYLON.Vector3.Cross(v3, v4);
  81356. vn = vn.normalize();
  81357. uvs.push(ulength / bounds.width, 0);
  81358. uvs.push(ulength / bounds.width, 1);
  81359. ulength += v3.length();
  81360. uvs.push((ulength / bounds.width), 0);
  81361. uvs.push((ulength / bounds.width), 1);
  81362. if (!flip) {
  81363. normals.push(-vn.x, -vn.y, -vn.z);
  81364. normals.push(-vn.x, -vn.y, -vn.z);
  81365. normals.push(-vn.x, -vn.y, -vn.z);
  81366. normals.push(-vn.x, -vn.y, -vn.z);
  81367. indices.push(StartIndex);
  81368. indices.push(StartIndex + 1);
  81369. indices.push(StartIndex + 2);
  81370. indices.push(StartIndex + 1);
  81371. indices.push(StartIndex + 3);
  81372. indices.push(StartIndex + 2);
  81373. }
  81374. else {
  81375. normals.push(vn.x, vn.y, vn.z);
  81376. normals.push(vn.x, vn.y, vn.z);
  81377. normals.push(vn.x, vn.y, vn.z);
  81378. normals.push(vn.x, vn.y, vn.z);
  81379. indices.push(StartIndex);
  81380. indices.push(StartIndex + 2);
  81381. indices.push(StartIndex + 1);
  81382. indices.push(StartIndex + 1);
  81383. indices.push(StartIndex + 2);
  81384. indices.push(StartIndex + 3);
  81385. }
  81386. StartIndex += 4;
  81387. }
  81388. ;
  81389. };
  81390. return PolygonMeshBuilder;
  81391. }());
  81392. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81393. })(BABYLON || (BABYLON = {}));
  81394. //# sourceMappingURL=babylon.polygonMesh.js.map
  81395. var BABYLON;
  81396. (function (BABYLON) {
  81397. // Unique ID when we import meshes from Babylon to CSG
  81398. var currentCSGMeshId = 0;
  81399. // # class Vertex
  81400. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81401. // one to provide additional features like texture coordinates and vertex
  81402. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81403. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81404. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81405. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81406. // is not used anywhere else.
  81407. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81408. var Vertex = /** @class */ (function () {
  81409. function Vertex(pos, normal, uv) {
  81410. this.pos = pos;
  81411. this.normal = normal;
  81412. this.uv = uv;
  81413. }
  81414. Vertex.prototype.clone = function () {
  81415. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81416. };
  81417. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81418. // orientation of a polygon is flipped.
  81419. Vertex.prototype.flip = function () {
  81420. this.normal = this.normal.scale(-1);
  81421. };
  81422. // Create a new vertex between this vertex and `other` by linearly
  81423. // interpolating all properties using a parameter of `t`. Subclasses should
  81424. // override this to interpolate additional properties.
  81425. Vertex.prototype.interpolate = function (other, t) {
  81426. 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));
  81427. };
  81428. return Vertex;
  81429. }());
  81430. // # class Plane
  81431. // Represents a plane in 3D space.
  81432. var Plane = /** @class */ (function () {
  81433. function Plane(normal, w) {
  81434. this.normal = normal;
  81435. this.w = w;
  81436. }
  81437. Plane.FromPoints = function (a, b, c) {
  81438. var v0 = c.subtract(a);
  81439. var v1 = b.subtract(a);
  81440. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81441. return null;
  81442. }
  81443. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81444. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81445. };
  81446. Plane.prototype.clone = function () {
  81447. return new Plane(this.normal.clone(), this.w);
  81448. };
  81449. Plane.prototype.flip = function () {
  81450. this.normal.scaleInPlace(-1);
  81451. this.w = -this.w;
  81452. };
  81453. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81454. // fragments in the appropriate lists. Coplanar polygons go into either
  81455. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81456. // respect to this plane. Polygons in front or in back of this plane go into
  81457. // either `front` or `back`.
  81458. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81459. var COPLANAR = 0;
  81460. var FRONT = 1;
  81461. var BACK = 2;
  81462. var SPANNING = 3;
  81463. // Classify each point as well as the entire polygon into one of the above
  81464. // four classes.
  81465. var polygonType = 0;
  81466. var types = [];
  81467. var i;
  81468. var t;
  81469. for (i = 0; i < polygon.vertices.length; i++) {
  81470. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81471. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81472. polygonType |= type;
  81473. types.push(type);
  81474. }
  81475. // Put the polygon in the correct list, splitting it when necessary.
  81476. switch (polygonType) {
  81477. case COPLANAR:
  81478. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81479. break;
  81480. case FRONT:
  81481. front.push(polygon);
  81482. break;
  81483. case BACK:
  81484. back.push(polygon);
  81485. break;
  81486. case SPANNING:
  81487. var f = [], b = [];
  81488. for (i = 0; i < polygon.vertices.length; i++) {
  81489. var j = (i + 1) % polygon.vertices.length;
  81490. var ti = types[i], tj = types[j];
  81491. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81492. if (ti !== BACK)
  81493. f.push(vi);
  81494. if (ti !== FRONT)
  81495. b.push(ti !== BACK ? vi.clone() : vi);
  81496. if ((ti | tj) === SPANNING) {
  81497. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81498. var v = vi.interpolate(vj, t);
  81499. f.push(v);
  81500. b.push(v.clone());
  81501. }
  81502. }
  81503. var poly;
  81504. if (f.length >= 3) {
  81505. poly = new Polygon(f, polygon.shared);
  81506. if (poly.plane)
  81507. front.push(poly);
  81508. }
  81509. if (b.length >= 3) {
  81510. poly = new Polygon(b, polygon.shared);
  81511. if (poly.plane)
  81512. back.push(poly);
  81513. }
  81514. break;
  81515. }
  81516. };
  81517. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81518. // point is on the plane.
  81519. Plane.EPSILON = 1e-5;
  81520. return Plane;
  81521. }());
  81522. // # class Polygon
  81523. // Represents a convex polygon. The vertices used to initialize a polygon must
  81524. // be coplanar and form a convex loop.
  81525. //
  81526. // Each convex polygon has a `shared` property, which is shared between all
  81527. // polygons that are clones of each other or were split from the same polygon.
  81528. // This can be used to define per-polygon properties (such as surface color).
  81529. var Polygon = /** @class */ (function () {
  81530. function Polygon(vertices, shared) {
  81531. this.vertices = vertices;
  81532. this.shared = shared;
  81533. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81534. }
  81535. Polygon.prototype.clone = function () {
  81536. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81537. return new Polygon(vertices, this.shared);
  81538. };
  81539. Polygon.prototype.flip = function () {
  81540. this.vertices.reverse().map(function (v) { v.flip(); });
  81541. this.plane.flip();
  81542. };
  81543. return Polygon;
  81544. }());
  81545. // # class Node
  81546. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81547. // by picking a polygon to split along. That polygon (and all other coplanar
  81548. // polygons) are added directly to that node and the other polygons are added to
  81549. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81550. // no distinction between internal and leaf nodes.
  81551. var Node = /** @class */ (function () {
  81552. function Node(polygons) {
  81553. this.plane = null;
  81554. this.front = null;
  81555. this.back = null;
  81556. this.polygons = new Array();
  81557. if (polygons) {
  81558. this.build(polygons);
  81559. }
  81560. }
  81561. Node.prototype.clone = function () {
  81562. var node = new Node();
  81563. node.plane = this.plane && this.plane.clone();
  81564. node.front = this.front && this.front.clone();
  81565. node.back = this.back && this.back.clone();
  81566. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81567. return node;
  81568. };
  81569. // Convert solid space to empty space and empty space to solid space.
  81570. Node.prototype.invert = function () {
  81571. for (var i = 0; i < this.polygons.length; i++) {
  81572. this.polygons[i].flip();
  81573. }
  81574. if (this.plane) {
  81575. this.plane.flip();
  81576. }
  81577. if (this.front) {
  81578. this.front.invert();
  81579. }
  81580. if (this.back) {
  81581. this.back.invert();
  81582. }
  81583. var temp = this.front;
  81584. this.front = this.back;
  81585. this.back = temp;
  81586. };
  81587. // Recursively remove all polygons in `polygons` that are inside this BSP
  81588. // tree.
  81589. Node.prototype.clipPolygons = function (polygons) {
  81590. if (!this.plane)
  81591. return polygons.slice();
  81592. var front = new Array(), back = new Array();
  81593. for (var i = 0; i < polygons.length; i++) {
  81594. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81595. }
  81596. if (this.front) {
  81597. front = this.front.clipPolygons(front);
  81598. }
  81599. if (this.back) {
  81600. back = this.back.clipPolygons(back);
  81601. }
  81602. else {
  81603. back = [];
  81604. }
  81605. return front.concat(back);
  81606. };
  81607. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81608. // `bsp`.
  81609. Node.prototype.clipTo = function (bsp) {
  81610. this.polygons = bsp.clipPolygons(this.polygons);
  81611. if (this.front)
  81612. this.front.clipTo(bsp);
  81613. if (this.back)
  81614. this.back.clipTo(bsp);
  81615. };
  81616. // Return a list of all polygons in this BSP tree.
  81617. Node.prototype.allPolygons = function () {
  81618. var polygons = this.polygons.slice();
  81619. if (this.front)
  81620. polygons = polygons.concat(this.front.allPolygons());
  81621. if (this.back)
  81622. polygons = polygons.concat(this.back.allPolygons());
  81623. return polygons;
  81624. };
  81625. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81626. // new polygons are filtered down to the bottom of the tree and become new
  81627. // nodes there. Each set of polygons is partitioned using the first polygon
  81628. // (no heuristic is used to pick a good split).
  81629. Node.prototype.build = function (polygons) {
  81630. if (!polygons.length)
  81631. return;
  81632. if (!this.plane)
  81633. this.plane = polygons[0].plane.clone();
  81634. var front = new Array(), back = new Array();
  81635. for (var i = 0; i < polygons.length; i++) {
  81636. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81637. }
  81638. if (front.length) {
  81639. if (!this.front)
  81640. this.front = new Node();
  81641. this.front.build(front);
  81642. }
  81643. if (back.length) {
  81644. if (!this.back)
  81645. this.back = new Node();
  81646. this.back.build(back);
  81647. }
  81648. };
  81649. return Node;
  81650. }());
  81651. var CSG = /** @class */ (function () {
  81652. function CSG() {
  81653. this.polygons = new Array();
  81654. }
  81655. // Convert BABYLON.Mesh to BABYLON.CSG
  81656. CSG.FromMesh = function (mesh) {
  81657. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81658. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81659. if (mesh instanceof BABYLON.Mesh) {
  81660. mesh.computeWorldMatrix(true);
  81661. matrix = mesh.getWorldMatrix();
  81662. meshPosition = mesh.position.clone();
  81663. meshRotation = mesh.rotation.clone();
  81664. if (mesh.rotationQuaternion) {
  81665. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81666. }
  81667. meshScaling = mesh.scaling.clone();
  81668. }
  81669. else {
  81670. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81671. }
  81672. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81673. var subMeshes = mesh.subMeshes;
  81674. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81675. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81676. vertices = [];
  81677. for (var j = 0; j < 3; j++) {
  81678. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81679. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81680. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81681. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81682. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81683. vertex = new Vertex(position, normal, uv);
  81684. vertices.push(vertex);
  81685. }
  81686. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81687. // To handle the case of degenerated triangle
  81688. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81689. if (polygon.plane)
  81690. polygons.push(polygon);
  81691. }
  81692. }
  81693. var csg = CSG.FromPolygons(polygons);
  81694. csg.matrix = matrix;
  81695. csg.position = meshPosition;
  81696. csg.rotation = meshRotation;
  81697. csg.scaling = meshScaling;
  81698. csg.rotationQuaternion = meshRotationQuaternion;
  81699. currentCSGMeshId++;
  81700. return csg;
  81701. };
  81702. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81703. CSG.FromPolygons = function (polygons) {
  81704. var csg = new CSG();
  81705. csg.polygons = polygons;
  81706. return csg;
  81707. };
  81708. CSG.prototype.clone = function () {
  81709. var csg = new CSG();
  81710. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81711. csg.copyTransformAttributes(this);
  81712. return csg;
  81713. };
  81714. CSG.prototype.union = function (csg) {
  81715. var a = new Node(this.clone().polygons);
  81716. var b = new Node(csg.clone().polygons);
  81717. a.clipTo(b);
  81718. b.clipTo(a);
  81719. b.invert();
  81720. b.clipTo(a);
  81721. b.invert();
  81722. a.build(b.allPolygons());
  81723. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81724. };
  81725. CSG.prototype.unionInPlace = function (csg) {
  81726. var a = new Node(this.polygons);
  81727. var b = new Node(csg.polygons);
  81728. a.clipTo(b);
  81729. b.clipTo(a);
  81730. b.invert();
  81731. b.clipTo(a);
  81732. b.invert();
  81733. a.build(b.allPolygons());
  81734. this.polygons = a.allPolygons();
  81735. };
  81736. CSG.prototype.subtract = function (csg) {
  81737. var a = new Node(this.clone().polygons);
  81738. var b = new Node(csg.clone().polygons);
  81739. a.invert();
  81740. a.clipTo(b);
  81741. b.clipTo(a);
  81742. b.invert();
  81743. b.clipTo(a);
  81744. b.invert();
  81745. a.build(b.allPolygons());
  81746. a.invert();
  81747. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81748. };
  81749. CSG.prototype.subtractInPlace = function (csg) {
  81750. var a = new Node(this.polygons);
  81751. var b = new Node(csg.polygons);
  81752. a.invert();
  81753. a.clipTo(b);
  81754. b.clipTo(a);
  81755. b.invert();
  81756. b.clipTo(a);
  81757. b.invert();
  81758. a.build(b.allPolygons());
  81759. a.invert();
  81760. this.polygons = a.allPolygons();
  81761. };
  81762. CSG.prototype.intersect = function (csg) {
  81763. var a = new Node(this.clone().polygons);
  81764. var b = new Node(csg.clone().polygons);
  81765. a.invert();
  81766. b.clipTo(a);
  81767. b.invert();
  81768. a.clipTo(b);
  81769. b.clipTo(a);
  81770. a.build(b.allPolygons());
  81771. a.invert();
  81772. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81773. };
  81774. CSG.prototype.intersectInPlace = function (csg) {
  81775. var a = new Node(this.polygons);
  81776. var b = new Node(csg.polygons);
  81777. a.invert();
  81778. b.clipTo(a);
  81779. b.invert();
  81780. a.clipTo(b);
  81781. b.clipTo(a);
  81782. a.build(b.allPolygons());
  81783. a.invert();
  81784. this.polygons = a.allPolygons();
  81785. };
  81786. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81787. // not modified.
  81788. CSG.prototype.inverse = function () {
  81789. var csg = this.clone();
  81790. csg.inverseInPlace();
  81791. return csg;
  81792. };
  81793. CSG.prototype.inverseInPlace = function () {
  81794. this.polygons.map(function (p) { p.flip(); });
  81795. };
  81796. // This is used to keep meshes transformations so they can be restored
  81797. // when we build back a Babylon Mesh
  81798. // NB : All CSG operations are performed in world coordinates
  81799. CSG.prototype.copyTransformAttributes = function (csg) {
  81800. this.matrix = csg.matrix;
  81801. this.position = csg.position;
  81802. this.rotation = csg.rotation;
  81803. this.scaling = csg.scaling;
  81804. this.rotationQuaternion = csg.rotationQuaternion;
  81805. return this;
  81806. };
  81807. // Build Raw mesh from CSG
  81808. // Coordinates here are in world space
  81809. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81810. var matrix = this.matrix.clone();
  81811. matrix.invert();
  81812. 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;
  81813. if (keepSubMeshes) {
  81814. // Sort Polygons, since subMeshes are indices range
  81815. polygons.sort(function (a, b) {
  81816. if (a.shared.meshId === b.shared.meshId) {
  81817. return a.shared.subMeshId - b.shared.subMeshId;
  81818. }
  81819. else {
  81820. return a.shared.meshId - b.shared.meshId;
  81821. }
  81822. });
  81823. }
  81824. for (var i = 0, il = polygons.length; i < il; i++) {
  81825. polygon = polygons[i];
  81826. // Building SubMeshes
  81827. if (!subMesh_dict[polygon.shared.meshId]) {
  81828. subMesh_dict[polygon.shared.meshId] = {};
  81829. }
  81830. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81831. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81832. indexStart: +Infinity,
  81833. indexEnd: -Infinity,
  81834. materialIndex: polygon.shared.materialIndex
  81835. };
  81836. }
  81837. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81838. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81839. polygonIndices[0] = 0;
  81840. polygonIndices[1] = j - 1;
  81841. polygonIndices[2] = j;
  81842. for (var k = 0; k < 3; k++) {
  81843. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81844. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81845. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81846. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81847. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81848. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81849. // Check if 2 points can be merged
  81850. if (!(typeof vertex_idx !== 'undefined' &&
  81851. normals[vertex_idx * 3] === localNormal.x &&
  81852. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81853. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81854. uvs[vertex_idx * 2] === uv.x &&
  81855. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81856. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81857. uvs.push(uv.x, uv.y);
  81858. normals.push(normal.x, normal.y, normal.z);
  81859. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81860. }
  81861. indices.push(vertex_idx);
  81862. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81863. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81864. currentIndex++;
  81865. }
  81866. }
  81867. }
  81868. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81869. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81870. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81871. mesh.setIndices(indices, null);
  81872. if (keepSubMeshes) {
  81873. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81874. var materialIndexOffset = 0, materialMaxIndex;
  81875. mesh.subMeshes = new Array();
  81876. for (var m in subMesh_dict) {
  81877. materialMaxIndex = -1;
  81878. for (var sm in subMesh_dict[m]) {
  81879. subMesh_obj = subMesh_dict[m][sm];
  81880. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81881. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81882. }
  81883. materialIndexOffset += ++materialMaxIndex;
  81884. }
  81885. }
  81886. return mesh;
  81887. };
  81888. // Build Mesh from CSG taking material and transforms into account
  81889. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81890. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81891. mesh.material = material;
  81892. mesh.position.copyFrom(this.position);
  81893. mesh.rotation.copyFrom(this.rotation);
  81894. if (this.rotationQuaternion) {
  81895. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81896. }
  81897. mesh.scaling.copyFrom(this.scaling);
  81898. mesh.computeWorldMatrix(true);
  81899. return mesh;
  81900. };
  81901. return CSG;
  81902. }());
  81903. BABYLON.CSG = CSG;
  81904. })(BABYLON || (BABYLON = {}));
  81905. //# sourceMappingURL=babylon.csg.js.map
  81906. var BABYLON;
  81907. (function (BABYLON) {
  81908. var LensFlare = /** @class */ (function () {
  81909. function LensFlare(size, position, color, imgUrl, system) {
  81910. this.size = size;
  81911. this.position = position;
  81912. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81913. this.color = color || new BABYLON.Color3(1, 1, 1);
  81914. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81915. this._system = system;
  81916. system.lensFlares.push(this);
  81917. }
  81918. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81919. return new LensFlare(size, position, color, imgUrl, system);
  81920. };
  81921. LensFlare.prototype.dispose = function () {
  81922. if (this.texture) {
  81923. this.texture.dispose();
  81924. }
  81925. // Remove from scene
  81926. var index = this._system.lensFlares.indexOf(this);
  81927. this._system.lensFlares.splice(index, 1);
  81928. };
  81929. ;
  81930. return LensFlare;
  81931. }());
  81932. BABYLON.LensFlare = LensFlare;
  81933. })(BABYLON || (BABYLON = {}));
  81934. //# sourceMappingURL=babylon.lensFlare.js.map
  81935. var BABYLON;
  81936. (function (BABYLON) {
  81937. var LensFlareSystem = /** @class */ (function () {
  81938. function LensFlareSystem(name, emitter, scene) {
  81939. this.name = name;
  81940. this.lensFlares = new Array();
  81941. this.borderLimit = 300;
  81942. this.viewportBorder = 0;
  81943. this.layerMask = 0x0FFFFFFF;
  81944. this._vertexBuffers = {};
  81945. this._isEnabled = true;
  81946. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81947. this._emitter = emitter;
  81948. this.id = name;
  81949. scene.lensFlareSystems.push(this);
  81950. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81951. var engine = scene.getEngine();
  81952. // VBO
  81953. var vertices = [];
  81954. vertices.push(1, 1);
  81955. vertices.push(-1, 1);
  81956. vertices.push(-1, -1);
  81957. vertices.push(1, -1);
  81958. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81959. // Indices
  81960. var indices = [];
  81961. indices.push(0);
  81962. indices.push(1);
  81963. indices.push(2);
  81964. indices.push(0);
  81965. indices.push(2);
  81966. indices.push(3);
  81967. this._indexBuffer = engine.createIndexBuffer(indices);
  81968. // Effects
  81969. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81970. }
  81971. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81972. get: function () {
  81973. return this._isEnabled;
  81974. },
  81975. set: function (value) {
  81976. this._isEnabled = value;
  81977. },
  81978. enumerable: true,
  81979. configurable: true
  81980. });
  81981. LensFlareSystem.prototype.getScene = function () {
  81982. return this._scene;
  81983. };
  81984. LensFlareSystem.prototype.getEmitter = function () {
  81985. return this._emitter;
  81986. };
  81987. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81988. this._emitter = newEmitter;
  81989. };
  81990. LensFlareSystem.prototype.getEmitterPosition = function () {
  81991. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81992. };
  81993. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81994. var position = this.getEmitterPosition();
  81995. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81996. this._positionX = position.x;
  81997. this._positionY = position.y;
  81998. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81999. if (this.viewportBorder > 0) {
  82000. globalViewport.x -= this.viewportBorder;
  82001. globalViewport.y -= this.viewportBorder;
  82002. globalViewport.width += this.viewportBorder * 2;
  82003. globalViewport.height += this.viewportBorder * 2;
  82004. position.x += this.viewportBorder;
  82005. position.y += this.viewportBorder;
  82006. this._positionX += this.viewportBorder;
  82007. this._positionY += this.viewportBorder;
  82008. }
  82009. if (position.z > 0) {
  82010. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82011. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82012. return true;
  82013. }
  82014. return true;
  82015. }
  82016. return false;
  82017. };
  82018. LensFlareSystem.prototype._isVisible = function () {
  82019. if (!this._isEnabled || !this._scene.activeCamera) {
  82020. return false;
  82021. }
  82022. var emitterPosition = this.getEmitterPosition();
  82023. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82024. var distance = direction.length();
  82025. direction.normalize();
  82026. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82027. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82028. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82029. };
  82030. LensFlareSystem.prototype.render = function () {
  82031. if (!this._effect.isReady() || !this._scene.activeCamera)
  82032. return false;
  82033. var engine = this._scene.getEngine();
  82034. var viewport = this._scene.activeCamera.viewport;
  82035. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82036. // Position
  82037. if (!this.computeEffectivePosition(globalViewport)) {
  82038. return false;
  82039. }
  82040. // Visibility
  82041. if (!this._isVisible()) {
  82042. return false;
  82043. }
  82044. // Intensity
  82045. var awayX;
  82046. var awayY;
  82047. if (this._positionX < this.borderLimit + globalViewport.x) {
  82048. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82049. }
  82050. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82051. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82052. }
  82053. else {
  82054. awayX = 0;
  82055. }
  82056. if (this._positionY < this.borderLimit + globalViewport.y) {
  82057. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82058. }
  82059. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82060. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82061. }
  82062. else {
  82063. awayY = 0;
  82064. }
  82065. var away = (awayX > awayY) ? awayX : awayY;
  82066. away -= this.viewportBorder;
  82067. if (away > this.borderLimit) {
  82068. away = this.borderLimit;
  82069. }
  82070. var intensity = 1.0 - (away / this.borderLimit);
  82071. if (intensity < 0) {
  82072. return false;
  82073. }
  82074. if (intensity > 1.0) {
  82075. intensity = 1.0;
  82076. }
  82077. if (this.viewportBorder > 0) {
  82078. globalViewport.x += this.viewportBorder;
  82079. globalViewport.y += this.viewportBorder;
  82080. globalViewport.width -= this.viewportBorder * 2;
  82081. globalViewport.height -= this.viewportBorder * 2;
  82082. this._positionX -= this.viewportBorder;
  82083. this._positionY -= this.viewportBorder;
  82084. }
  82085. // Position
  82086. var centerX = globalViewport.x + globalViewport.width / 2;
  82087. var centerY = globalViewport.y + globalViewport.height / 2;
  82088. var distX = centerX - this._positionX;
  82089. var distY = centerY - this._positionY;
  82090. // Effects
  82091. engine.enableEffect(this._effect);
  82092. engine.setState(false);
  82093. engine.setDepthBuffer(false);
  82094. // VBOs
  82095. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82096. // Flares
  82097. for (var index = 0; index < this.lensFlares.length; index++) {
  82098. var flare = this.lensFlares[index];
  82099. engine.setAlphaMode(flare.alphaMode);
  82100. var x = centerX - (distX * flare.position);
  82101. var y = centerY - (distY * flare.position);
  82102. var cw = flare.size;
  82103. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82104. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82105. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82106. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82107. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82108. // Texture
  82109. this._effect.setTexture("textureSampler", flare.texture);
  82110. // Color
  82111. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82112. // Draw order
  82113. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82114. }
  82115. engine.setDepthBuffer(true);
  82116. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82117. return true;
  82118. };
  82119. LensFlareSystem.prototype.dispose = function () {
  82120. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82121. if (vertexBuffer) {
  82122. vertexBuffer.dispose();
  82123. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82124. }
  82125. if (this._indexBuffer) {
  82126. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82127. this._indexBuffer = null;
  82128. }
  82129. while (this.lensFlares.length) {
  82130. this.lensFlares[0].dispose();
  82131. }
  82132. // Remove from scene
  82133. var index = this._scene.lensFlareSystems.indexOf(this);
  82134. this._scene.lensFlareSystems.splice(index, 1);
  82135. };
  82136. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82137. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82138. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82139. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82140. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82141. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82142. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82143. var parsedFlare = parsedLensFlareSystem.flares[index];
  82144. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82145. }
  82146. return lensFlareSystem;
  82147. };
  82148. LensFlareSystem.prototype.serialize = function () {
  82149. var serializationObject = {};
  82150. serializationObject.id = this.id;
  82151. serializationObject.name = this.name;
  82152. serializationObject.emitterId = this.getEmitter().id;
  82153. serializationObject.borderLimit = this.borderLimit;
  82154. serializationObject.flares = [];
  82155. for (var index = 0; index < this.lensFlares.length; index++) {
  82156. var flare = this.lensFlares[index];
  82157. serializationObject.flares.push({
  82158. size: flare.size,
  82159. position: flare.position,
  82160. color: flare.color.asArray(),
  82161. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82162. });
  82163. }
  82164. return serializationObject;
  82165. };
  82166. return LensFlareSystem;
  82167. }());
  82168. BABYLON.LensFlareSystem = LensFlareSystem;
  82169. })(BABYLON || (BABYLON = {}));
  82170. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82171. var BABYLON;
  82172. (function (BABYLON) {
  82173. /**
  82174. * This is a holder class for the physics joint created by the physics plugin.
  82175. * It holds a set of functions to control the underlying joint.
  82176. */
  82177. var PhysicsJoint = /** @class */ (function () {
  82178. function PhysicsJoint(type, jointData) {
  82179. this.type = type;
  82180. this.jointData = jointData;
  82181. jointData.nativeParams = jointData.nativeParams || {};
  82182. }
  82183. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82184. get: function () {
  82185. return this._physicsJoint;
  82186. },
  82187. set: function (newJoint) {
  82188. if (this._physicsJoint) {
  82189. //remove from the wolrd
  82190. }
  82191. this._physicsJoint = newJoint;
  82192. },
  82193. enumerable: true,
  82194. configurable: true
  82195. });
  82196. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82197. set: function (physicsPlugin) {
  82198. this._physicsPlugin = physicsPlugin;
  82199. },
  82200. enumerable: true,
  82201. configurable: true
  82202. });
  82203. /**
  82204. * Execute a function that is physics-plugin specific.
  82205. * @param {Function} func the function that will be executed.
  82206. * It accepts two parameters: the physics world and the physics joint.
  82207. */
  82208. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82209. func(this._physicsPlugin.world, this._physicsJoint);
  82210. };
  82211. //TODO check if the native joints are the same
  82212. //Joint Types
  82213. PhysicsJoint.DistanceJoint = 0;
  82214. PhysicsJoint.HingeJoint = 1;
  82215. PhysicsJoint.BallAndSocketJoint = 2;
  82216. PhysicsJoint.WheelJoint = 3;
  82217. PhysicsJoint.SliderJoint = 4;
  82218. //OIMO
  82219. PhysicsJoint.PrismaticJoint = 5;
  82220. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82221. PhysicsJoint.UniversalJoint = 6;
  82222. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82223. //Cannon
  82224. //Similar to a Ball-Joint. Different in params
  82225. PhysicsJoint.PointToPointJoint = 8;
  82226. //Cannon only at the moment
  82227. PhysicsJoint.SpringJoint = 9;
  82228. PhysicsJoint.LockJoint = 10;
  82229. return PhysicsJoint;
  82230. }());
  82231. BABYLON.PhysicsJoint = PhysicsJoint;
  82232. /**
  82233. * A class representing a physics distance joint.
  82234. */
  82235. var DistanceJoint = /** @class */ (function (_super) {
  82236. __extends(DistanceJoint, _super);
  82237. function DistanceJoint(jointData) {
  82238. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82239. }
  82240. /**
  82241. * Update the predefined distance.
  82242. */
  82243. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82244. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82245. };
  82246. return DistanceJoint;
  82247. }(PhysicsJoint));
  82248. BABYLON.DistanceJoint = DistanceJoint;
  82249. var MotorEnabledJoint = /** @class */ (function (_super) {
  82250. __extends(MotorEnabledJoint, _super);
  82251. function MotorEnabledJoint(type, jointData) {
  82252. return _super.call(this, type, jointData) || this;
  82253. }
  82254. /**
  82255. * Set the motor values.
  82256. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82257. * @param {number} force the force to apply
  82258. * @param {number} maxForce max force for this motor.
  82259. */
  82260. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82261. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82262. };
  82263. /**
  82264. * Set the motor's limits.
  82265. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82266. */
  82267. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82268. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82269. };
  82270. return MotorEnabledJoint;
  82271. }(PhysicsJoint));
  82272. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82273. /**
  82274. * This class represents a single hinge physics joint
  82275. */
  82276. var HingeJoint = /** @class */ (function (_super) {
  82277. __extends(HingeJoint, _super);
  82278. function HingeJoint(jointData) {
  82279. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82280. }
  82281. /**
  82282. * Set the motor values.
  82283. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82284. * @param {number} force the force to apply
  82285. * @param {number} maxForce max force for this motor.
  82286. */
  82287. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82288. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82289. };
  82290. /**
  82291. * Set the motor's limits.
  82292. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82293. */
  82294. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82295. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82296. };
  82297. return HingeJoint;
  82298. }(MotorEnabledJoint));
  82299. BABYLON.HingeJoint = HingeJoint;
  82300. /**
  82301. * This class represents a dual hinge physics joint (same as wheel joint)
  82302. */
  82303. var Hinge2Joint = /** @class */ (function (_super) {
  82304. __extends(Hinge2Joint, _super);
  82305. function Hinge2Joint(jointData) {
  82306. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82307. }
  82308. /**
  82309. * Set the motor values.
  82310. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82311. * @param {number} force the force to apply
  82312. * @param {number} maxForce max force for this motor.
  82313. * @param {motorIndex} the motor's index, 0 or 1.
  82314. */
  82315. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82316. if (motorIndex === void 0) { motorIndex = 0; }
  82317. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82318. };
  82319. /**
  82320. * Set the motor limits.
  82321. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82322. * @param {number} upperLimit the upper limit
  82323. * @param {number} lowerLimit lower limit
  82324. * @param {motorIndex} the motor's index, 0 or 1.
  82325. */
  82326. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82327. if (motorIndex === void 0) { motorIndex = 0; }
  82328. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82329. };
  82330. return Hinge2Joint;
  82331. }(MotorEnabledJoint));
  82332. BABYLON.Hinge2Joint = Hinge2Joint;
  82333. })(BABYLON || (BABYLON = {}));
  82334. //# sourceMappingURL=babylon.physicsJoint.js.map
  82335. var BABYLON;
  82336. (function (BABYLON) {
  82337. var PhysicsImpostor = /** @class */ (function () {
  82338. function PhysicsImpostor(object, type, _options, _scene) {
  82339. if (_options === void 0) { _options = { mass: 0 }; }
  82340. var _this = this;
  82341. this.object = object;
  82342. this.type = type;
  82343. this._options = _options;
  82344. this._scene = _scene;
  82345. this._bodyUpdateRequired = false;
  82346. this._onBeforePhysicsStepCallbacks = new Array();
  82347. this._onAfterPhysicsStepCallbacks = new Array();
  82348. this._onPhysicsCollideCallbacks = [];
  82349. this._deltaPosition = BABYLON.Vector3.Zero();
  82350. this._isDisposed = false;
  82351. //temp variables for parent rotation calculations
  82352. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82353. this._tmpQuat = new BABYLON.Quaternion();
  82354. this._tmpQuat2 = new BABYLON.Quaternion();
  82355. /**
  82356. * this function is executed by the physics engine.
  82357. */
  82358. this.beforeStep = function () {
  82359. if (!_this._physicsEngine) {
  82360. return;
  82361. }
  82362. _this.object.translate(_this._deltaPosition, -1);
  82363. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82364. _this.object.computeWorldMatrix(false);
  82365. if (_this.object.parent && _this.object.rotationQuaternion) {
  82366. _this.getParentsRotation();
  82367. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82368. }
  82369. else {
  82370. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82371. }
  82372. if (!_this._options.disableBidirectionalTransformation) {
  82373. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82374. }
  82375. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82376. func(_this);
  82377. });
  82378. };
  82379. /**
  82380. * this function is executed by the physics engine.
  82381. */
  82382. this.afterStep = function () {
  82383. if (!_this._physicsEngine) {
  82384. return;
  82385. }
  82386. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82387. func(_this);
  82388. });
  82389. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82390. // object has now its world rotation. needs to be converted to local.
  82391. if (_this.object.parent && _this.object.rotationQuaternion) {
  82392. _this.getParentsRotation();
  82393. _this._tmpQuat.conjugateInPlace();
  82394. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82395. }
  82396. // take the position set and make it the absolute position of this object.
  82397. _this.object.setAbsolutePosition(_this.object.position);
  82398. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82399. _this.object.translate(_this._deltaPosition, 1);
  82400. };
  82401. /**
  82402. * Legacy collision detection event support
  82403. */
  82404. this.onCollideEvent = null;
  82405. //event and body object due to cannon's event-based architecture.
  82406. this.onCollide = function (e) {
  82407. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82408. return;
  82409. }
  82410. if (!_this._physicsEngine) {
  82411. return;
  82412. }
  82413. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82414. if (otherImpostor) {
  82415. // Legacy collision detection event support
  82416. if (_this.onCollideEvent) {
  82417. _this.onCollideEvent(_this, otherImpostor);
  82418. }
  82419. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82420. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82421. }).forEach(function (obj) {
  82422. obj.callback(_this, otherImpostor);
  82423. });
  82424. }
  82425. };
  82426. //sanity check!
  82427. if (!this.object) {
  82428. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82429. return;
  82430. }
  82431. //legacy support for old syntax.
  82432. if (!this._scene && object.getScene) {
  82433. this._scene = object.getScene();
  82434. }
  82435. if (!this._scene) {
  82436. return;
  82437. }
  82438. this._physicsEngine = this._scene.getPhysicsEngine();
  82439. if (!this._physicsEngine) {
  82440. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82441. }
  82442. else {
  82443. //set the object's quaternion, if not set
  82444. if (!this.object.rotationQuaternion) {
  82445. if (this.object.rotation) {
  82446. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82447. }
  82448. else {
  82449. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82450. }
  82451. }
  82452. //default options params
  82453. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82454. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82455. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82456. this._joints = [];
  82457. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82458. if (!this.object.parent || this._options.ignoreParent) {
  82459. this._init();
  82460. }
  82461. else if (this.object.parent.physicsImpostor) {
  82462. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82463. }
  82464. }
  82465. }
  82466. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82467. get: function () {
  82468. return this._isDisposed;
  82469. },
  82470. enumerable: true,
  82471. configurable: true
  82472. });
  82473. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82474. get: function () {
  82475. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82476. },
  82477. set: function (value) {
  82478. this.setMass(value);
  82479. },
  82480. enumerable: true,
  82481. configurable: true
  82482. });
  82483. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82484. get: function () {
  82485. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82486. },
  82487. set: function (value) {
  82488. if (!this._physicsEngine) {
  82489. return;
  82490. }
  82491. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82492. },
  82493. enumerable: true,
  82494. configurable: true
  82495. });
  82496. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82497. get: function () {
  82498. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82499. },
  82500. set: function (value) {
  82501. if (!this._physicsEngine) {
  82502. return;
  82503. }
  82504. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82505. },
  82506. enumerable: true,
  82507. configurable: true
  82508. });
  82509. /**
  82510. * This function will completly initialize this impostor.
  82511. * It will create a new body - but only if this mesh has no parent.
  82512. * If it has, this impostor will not be used other than to define the impostor
  82513. * of the child mesh.
  82514. */
  82515. PhysicsImpostor.prototype._init = function () {
  82516. if (!this._physicsEngine) {
  82517. return;
  82518. }
  82519. this._physicsEngine.removeImpostor(this);
  82520. this.physicsBody = null;
  82521. this._parent = this._parent || this._getPhysicsParent();
  82522. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82523. this._physicsEngine.addImpostor(this);
  82524. }
  82525. };
  82526. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82527. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82528. var parentMesh = this.object.parent;
  82529. return parentMesh.physicsImpostor;
  82530. }
  82531. return null;
  82532. };
  82533. /**
  82534. * Should a new body be generated.
  82535. */
  82536. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82537. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82538. };
  82539. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82540. this.forceUpdate();
  82541. };
  82542. /**
  82543. * Force a regeneration of this or the parent's impostor's body.
  82544. * Use under cautious - This will remove all joints already implemented.
  82545. */
  82546. PhysicsImpostor.prototype.forceUpdate = function () {
  82547. this._init();
  82548. if (this.parent && !this._options.ignoreParent) {
  82549. this.parent.forceUpdate();
  82550. }
  82551. };
  82552. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82553. /*public get mesh(): AbstractMesh {
  82554. return this._mesh;
  82555. }*/
  82556. /**
  82557. * Gets the body that holds this impostor. Either its own, or its parent.
  82558. */
  82559. get: function () {
  82560. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82561. },
  82562. /**
  82563. * Set the physics body. Used mainly by the physics engine/plugin
  82564. */
  82565. set: function (physicsBody) {
  82566. if (this._physicsBody && this._physicsEngine) {
  82567. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82568. }
  82569. this._physicsBody = physicsBody;
  82570. this.resetUpdateFlags();
  82571. },
  82572. enumerable: true,
  82573. configurable: true
  82574. });
  82575. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82576. get: function () {
  82577. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82578. },
  82579. set: function (value) {
  82580. this._parent = value;
  82581. },
  82582. enumerable: true,
  82583. configurable: true
  82584. });
  82585. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82586. this._bodyUpdateRequired = false;
  82587. };
  82588. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82589. if (this.object.getBoundingInfo) {
  82590. var q = this.object.rotationQuaternion;
  82591. //reset rotation
  82592. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82593. //calculate the world matrix with no rotation
  82594. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82595. var boundingInfo = this.object.getBoundingInfo();
  82596. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82597. //bring back the rotation
  82598. this.object.rotationQuaternion = q;
  82599. //calculate the world matrix with the new rotation
  82600. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82601. return size;
  82602. }
  82603. else {
  82604. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82605. }
  82606. };
  82607. PhysicsImpostor.prototype.getObjectCenter = function () {
  82608. if (this.object.getBoundingInfo) {
  82609. var boundingInfo = this.object.getBoundingInfo();
  82610. return boundingInfo.boundingBox.centerWorld;
  82611. }
  82612. else {
  82613. return this.object.position;
  82614. }
  82615. };
  82616. /**
  82617. * Get a specific parametes from the options parameter.
  82618. */
  82619. PhysicsImpostor.prototype.getParam = function (paramName) {
  82620. return this._options[paramName];
  82621. };
  82622. /**
  82623. * Sets a specific parameter in the options given to the physics plugin
  82624. */
  82625. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82626. this._options[paramName] = value;
  82627. this._bodyUpdateRequired = true;
  82628. };
  82629. /**
  82630. * Specifically change the body's mass option. Won't recreate the physics body object
  82631. */
  82632. PhysicsImpostor.prototype.setMass = function (mass) {
  82633. if (this.getParam("mass") !== mass) {
  82634. this.setParam("mass", mass);
  82635. }
  82636. if (this._physicsEngine) {
  82637. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82638. }
  82639. };
  82640. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82641. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82642. };
  82643. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82644. if (this._physicsEngine) {
  82645. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82646. }
  82647. };
  82648. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82649. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82650. };
  82651. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82652. if (this._physicsEngine) {
  82653. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82654. }
  82655. };
  82656. /**
  82657. * Execute a function with the physics plugin native code.
  82658. * Provide a function the will have two variables - the world object and the physics body object.
  82659. */
  82660. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82661. if (this._physicsEngine) {
  82662. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82663. }
  82664. };
  82665. /**
  82666. * Register a function that will be executed before the physics world is stepping forward.
  82667. */
  82668. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82669. this._onBeforePhysicsStepCallbacks.push(func);
  82670. };
  82671. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82672. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82673. if (index > -1) {
  82674. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82675. }
  82676. else {
  82677. BABYLON.Tools.Warn("Function to remove was not found");
  82678. }
  82679. };
  82680. /**
  82681. * Register a function that will be executed after the physics step
  82682. */
  82683. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82684. this._onAfterPhysicsStepCallbacks.push(func);
  82685. };
  82686. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82687. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82688. if (index > -1) {
  82689. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82690. }
  82691. else {
  82692. BABYLON.Tools.Warn("Function to remove was not found");
  82693. }
  82694. };
  82695. /**
  82696. * register a function that will be executed when this impostor collides against a different body.
  82697. */
  82698. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82699. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82700. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82701. };
  82702. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82703. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82704. var index = -1;
  82705. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82706. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82707. // chcek the arrays match
  82708. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82709. return collidedAgainstList.indexOf(impostor) > -1;
  82710. });
  82711. if (sameList) {
  82712. index = idx;
  82713. }
  82714. return sameList;
  82715. }
  82716. return false;
  82717. });
  82718. if (found) {
  82719. this._onPhysicsCollideCallbacks.splice(index, 1);
  82720. }
  82721. else {
  82722. BABYLON.Tools.Warn("Function to remove was not found");
  82723. }
  82724. };
  82725. PhysicsImpostor.prototype.getParentsRotation = function () {
  82726. var parent = this.object.parent;
  82727. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82728. while (parent) {
  82729. if (parent.rotationQuaternion) {
  82730. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82731. }
  82732. else {
  82733. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82734. }
  82735. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82736. parent = parent.parent;
  82737. }
  82738. return this._tmpQuat;
  82739. };
  82740. /**
  82741. * Apply a force
  82742. */
  82743. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82744. if (this._physicsEngine) {
  82745. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82746. }
  82747. return this;
  82748. };
  82749. /**
  82750. * Apply an impulse
  82751. */
  82752. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82753. if (this._physicsEngine) {
  82754. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82755. }
  82756. return this;
  82757. };
  82758. /**
  82759. * A help function to create a joint.
  82760. */
  82761. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82762. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82763. this.addJoint(otherImpostor, joint);
  82764. return this;
  82765. };
  82766. /**
  82767. * Add a joint to this impostor with a different impostor.
  82768. */
  82769. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82770. this._joints.push({
  82771. otherImpostor: otherImpostor,
  82772. joint: joint
  82773. });
  82774. if (this._physicsEngine) {
  82775. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82776. }
  82777. return this;
  82778. };
  82779. /**
  82780. * Will keep this body still, in a sleep mode.
  82781. */
  82782. PhysicsImpostor.prototype.sleep = function () {
  82783. if (this._physicsEngine) {
  82784. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82785. }
  82786. return this;
  82787. };
  82788. /**
  82789. * Wake the body up.
  82790. */
  82791. PhysicsImpostor.prototype.wakeUp = function () {
  82792. if (this._physicsEngine) {
  82793. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82794. }
  82795. return this;
  82796. };
  82797. PhysicsImpostor.prototype.clone = function (newObject) {
  82798. if (!newObject)
  82799. return null;
  82800. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82801. };
  82802. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82803. var _this = this;
  82804. //no dispose if no physics engine is available.
  82805. if (!this._physicsEngine) {
  82806. return;
  82807. }
  82808. this._joints.forEach(function (j) {
  82809. if (_this._physicsEngine) {
  82810. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82811. }
  82812. });
  82813. //dispose the physics body
  82814. this._physicsEngine.removeImpostor(this);
  82815. if (this.parent) {
  82816. this.parent.forceUpdate();
  82817. }
  82818. else {
  82819. /*this._object.getChildMeshes().forEach(function(mesh) {
  82820. if (mesh.physicsImpostor) {
  82821. if (disposeChildren) {
  82822. mesh.physicsImpostor.dispose();
  82823. mesh.physicsImpostor = null;
  82824. }
  82825. }
  82826. })*/
  82827. }
  82828. this._isDisposed = true;
  82829. };
  82830. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82831. this._deltaPosition.copyFrom(position);
  82832. };
  82833. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82834. if (!this._deltaRotation) {
  82835. this._deltaRotation = new BABYLON.Quaternion();
  82836. }
  82837. this._deltaRotation.copyFrom(rotation);
  82838. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82839. };
  82840. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82841. if (this._physicsEngine) {
  82842. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82843. }
  82844. return this;
  82845. };
  82846. PhysicsImpostor.prototype.getRadius = function () {
  82847. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82848. };
  82849. /**
  82850. * Sync a bone with this impostor
  82851. * @param bone The bone to sync to the impostor.
  82852. * @param boneMesh The mesh that the bone is influencing.
  82853. * @param jointPivot The pivot of the joint / bone in local space.
  82854. * @param distToJoint Optional distance from the impostor to the joint.
  82855. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82856. */
  82857. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82858. var tempVec = PhysicsImpostor._tmpVecs[0];
  82859. var mesh = this.object;
  82860. if (mesh.rotationQuaternion) {
  82861. if (adjustRotation) {
  82862. var tempQuat = PhysicsImpostor._tmpQuat;
  82863. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82864. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82865. }
  82866. else {
  82867. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82868. }
  82869. }
  82870. tempVec.x = 0;
  82871. tempVec.y = 0;
  82872. tempVec.z = 0;
  82873. if (jointPivot) {
  82874. tempVec.x = jointPivot.x;
  82875. tempVec.y = jointPivot.y;
  82876. tempVec.z = jointPivot.z;
  82877. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82878. if (distToJoint === undefined || distToJoint === null) {
  82879. distToJoint = jointPivot.length();
  82880. }
  82881. tempVec.x *= distToJoint;
  82882. tempVec.y *= distToJoint;
  82883. tempVec.z *= distToJoint;
  82884. }
  82885. if (bone.getParent()) {
  82886. tempVec.addInPlace(mesh.getAbsolutePosition());
  82887. bone.setAbsolutePosition(tempVec, boneMesh);
  82888. }
  82889. else {
  82890. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82891. boneMesh.position.x -= tempVec.x;
  82892. boneMesh.position.y -= tempVec.y;
  82893. boneMesh.position.z -= tempVec.z;
  82894. }
  82895. };
  82896. /**
  82897. * Sync impostor to a bone
  82898. * @param bone The bone that the impostor will be synced to.
  82899. * @param boneMesh The mesh that the bone is influencing.
  82900. * @param jointPivot The pivot of the joint / bone in local space.
  82901. * @param distToJoint Optional distance from the impostor to the joint.
  82902. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82903. * @param boneAxis Optional vector3 axis the bone is aligned with
  82904. */
  82905. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82906. var mesh = this.object;
  82907. if (mesh.rotationQuaternion) {
  82908. if (adjustRotation) {
  82909. var tempQuat = PhysicsImpostor._tmpQuat;
  82910. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82911. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82912. }
  82913. else {
  82914. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82915. }
  82916. }
  82917. var pos = PhysicsImpostor._tmpVecs[0];
  82918. var boneDir = PhysicsImpostor._tmpVecs[1];
  82919. if (!boneAxis) {
  82920. boneAxis = PhysicsImpostor._tmpVecs[2];
  82921. boneAxis.x = 0;
  82922. boneAxis.y = 1;
  82923. boneAxis.z = 0;
  82924. }
  82925. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82926. bone.getAbsolutePositionToRef(boneMesh, pos);
  82927. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82928. distToJoint = jointPivot.length();
  82929. }
  82930. if (distToJoint !== undefined && distToJoint !== null) {
  82931. pos.x += boneDir.x * distToJoint;
  82932. pos.y += boneDir.y * distToJoint;
  82933. pos.z += boneDir.z * distToJoint;
  82934. }
  82935. mesh.setAbsolutePosition(pos);
  82936. };
  82937. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82938. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82939. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82940. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82941. //Impostor types
  82942. PhysicsImpostor.NoImpostor = 0;
  82943. PhysicsImpostor.SphereImpostor = 1;
  82944. PhysicsImpostor.BoxImpostor = 2;
  82945. PhysicsImpostor.PlaneImpostor = 3;
  82946. PhysicsImpostor.MeshImpostor = 4;
  82947. PhysicsImpostor.CylinderImpostor = 7;
  82948. PhysicsImpostor.ParticleImpostor = 8;
  82949. PhysicsImpostor.HeightmapImpostor = 9;
  82950. return PhysicsImpostor;
  82951. }());
  82952. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82953. })(BABYLON || (BABYLON = {}));
  82954. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82955. var BABYLON;
  82956. (function (BABYLON) {
  82957. var PhysicsEngine = /** @class */ (function () {
  82958. function PhysicsEngine(gravity, _physicsPlugin) {
  82959. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82960. this._physicsPlugin = _physicsPlugin;
  82961. //new methods and parameters
  82962. this._impostors = [];
  82963. this._joints = [];
  82964. if (!this._physicsPlugin.isSupported()) {
  82965. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82966. + "Please make sure it is included.");
  82967. }
  82968. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82969. this.setGravity(gravity);
  82970. this.setTimeStep();
  82971. }
  82972. PhysicsEngine.prototype.setGravity = function (gravity) {
  82973. this.gravity = gravity;
  82974. this._physicsPlugin.setGravity(this.gravity);
  82975. };
  82976. /**
  82977. * Set the time step of the physics engine.
  82978. * default is 1/60.
  82979. * To slow it down, enter 1/600 for example.
  82980. * To speed it up, 1/30
  82981. * @param {number} newTimeStep the new timestep to apply to this world.
  82982. */
  82983. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82984. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82985. this._physicsPlugin.setTimeStep(newTimeStep);
  82986. };
  82987. /**
  82988. * Get the time step of the physics engine.
  82989. */
  82990. PhysicsEngine.prototype.getTimeStep = function () {
  82991. return this._physicsPlugin.getTimeStep();
  82992. };
  82993. PhysicsEngine.prototype.dispose = function () {
  82994. this._impostors.forEach(function (impostor) {
  82995. impostor.dispose();
  82996. });
  82997. this._physicsPlugin.dispose();
  82998. };
  82999. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83000. return this._physicsPlugin.name;
  83001. };
  83002. /**
  83003. * Adding a new impostor for the impostor tracking.
  83004. * This will be done by the impostor itself.
  83005. * @param {PhysicsImpostor} impostor the impostor to add
  83006. */
  83007. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83008. impostor.uniqueId = this._impostors.push(impostor);
  83009. //if no parent, generate the body
  83010. if (!impostor.parent) {
  83011. this._physicsPlugin.generatePhysicsBody(impostor);
  83012. }
  83013. };
  83014. /**
  83015. * Remove an impostor from the engine.
  83016. * This impostor and its mesh will not longer be updated by the physics engine.
  83017. * @param {PhysicsImpostor} impostor the impostor to remove
  83018. */
  83019. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83020. var index = this._impostors.indexOf(impostor);
  83021. if (index > -1) {
  83022. var removed = this._impostors.splice(index, 1);
  83023. //Is it needed?
  83024. if (removed.length) {
  83025. //this will also remove it from the world.
  83026. removed[0].physicsBody = null;
  83027. }
  83028. }
  83029. };
  83030. /**
  83031. * Add a joint to the physics engine
  83032. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83033. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83034. * @param {PhysicsJoint} the joint that will connect both impostors.
  83035. */
  83036. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83037. var impostorJoint = {
  83038. mainImpostor: mainImpostor,
  83039. connectedImpostor: connectedImpostor,
  83040. joint: joint
  83041. };
  83042. joint.physicsPlugin = this._physicsPlugin;
  83043. this._joints.push(impostorJoint);
  83044. this._physicsPlugin.generateJoint(impostorJoint);
  83045. };
  83046. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83047. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83048. return (impostorJoint.connectedImpostor === connectedImpostor
  83049. && impostorJoint.joint === joint
  83050. && impostorJoint.mainImpostor === mainImpostor);
  83051. });
  83052. if (matchingJoints.length) {
  83053. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83054. //TODO remove it from the list as well
  83055. }
  83056. };
  83057. /**
  83058. * Called by the scene. no need to call it.
  83059. */
  83060. PhysicsEngine.prototype._step = function (delta) {
  83061. var _this = this;
  83062. //check if any mesh has no body / requires an update
  83063. this._impostors.forEach(function (impostor) {
  83064. if (impostor.isBodyInitRequired()) {
  83065. _this._physicsPlugin.generatePhysicsBody(impostor);
  83066. }
  83067. });
  83068. if (delta > 0.1) {
  83069. delta = 0.1;
  83070. }
  83071. else if (delta <= 0) {
  83072. delta = 1.0 / 60.0;
  83073. }
  83074. this._physicsPlugin.executeStep(delta, this._impostors);
  83075. };
  83076. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83077. return this._physicsPlugin;
  83078. };
  83079. PhysicsEngine.prototype.getImpostors = function () {
  83080. return this._impostors;
  83081. };
  83082. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83083. for (var i = 0; i < this._impostors.length; ++i) {
  83084. if (this._impostors[i].object === object) {
  83085. return this._impostors[i];
  83086. }
  83087. }
  83088. return null;
  83089. };
  83090. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83091. for (var i = 0; i < this._impostors.length; ++i) {
  83092. if (this._impostors[i].physicsBody === body) {
  83093. return this._impostors[i];
  83094. }
  83095. }
  83096. return null;
  83097. };
  83098. // Statics
  83099. PhysicsEngine.Epsilon = 0.001;
  83100. return PhysicsEngine;
  83101. }());
  83102. BABYLON.PhysicsEngine = PhysicsEngine;
  83103. })(BABYLON || (BABYLON = {}));
  83104. //# sourceMappingURL=babylon.physicsEngine.js.map
  83105. var BABYLON;
  83106. (function (BABYLON) {
  83107. var PhysicsHelper = /** @class */ (function () {
  83108. function PhysicsHelper(scene) {
  83109. this._scene = scene;
  83110. this._physicsEngine = this._scene.getPhysicsEngine();
  83111. if (!this._physicsEngine) {
  83112. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83113. }
  83114. }
  83115. /**
  83116. * @param {Vector3} origin the origin of the explosion
  83117. * @param {number} radius the explosion radius
  83118. * @param {number} strength the explosion strength
  83119. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83120. */
  83121. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83122. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83123. if (!this._physicsEngine) {
  83124. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83125. return null;
  83126. }
  83127. var impostors = this._physicsEngine.getImpostors();
  83128. if (impostors.length === 0) {
  83129. return null;
  83130. }
  83131. var event = new PhysicsRadialExplosionEvent(this._scene);
  83132. impostors.forEach(function (impostor) {
  83133. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83134. if (!impostorForceAndContactPoint) {
  83135. return;
  83136. }
  83137. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83138. });
  83139. event.dispose(false);
  83140. return event;
  83141. };
  83142. /**
  83143. * @param {Vector3} origin the origin of the explosion
  83144. * @param {number} radius the explosion radius
  83145. * @param {number} strength the explosion strength
  83146. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83147. */
  83148. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83149. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83150. if (!this._physicsEngine) {
  83151. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83152. return null;
  83153. }
  83154. var impostors = this._physicsEngine.getImpostors();
  83155. if (impostors.length === 0) {
  83156. return null;
  83157. }
  83158. var event = new PhysicsRadialExplosionEvent(this._scene);
  83159. impostors.forEach(function (impostor) {
  83160. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83161. if (!impostorForceAndContactPoint) {
  83162. return;
  83163. }
  83164. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83165. });
  83166. event.dispose(false);
  83167. return event;
  83168. };
  83169. /**
  83170. * @param {Vector3} origin the origin of the explosion
  83171. * @param {number} radius the explosion radius
  83172. * @param {number} strength the explosion strength
  83173. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83174. */
  83175. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83176. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83177. if (!this._physicsEngine) {
  83178. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83179. return null;
  83180. }
  83181. var impostors = this._physicsEngine.getImpostors();
  83182. if (impostors.length === 0) {
  83183. return null;
  83184. }
  83185. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83186. event.dispose(false);
  83187. return event;
  83188. };
  83189. /**
  83190. * @param {Vector3} origin the origin of the updraft
  83191. * @param {number} radius the radius of the updraft
  83192. * @param {number} strength the strength of the updraft
  83193. * @param {number} height the height of the updraft
  83194. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83195. */
  83196. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83197. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83198. if (!this._physicsEngine) {
  83199. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83200. return null;
  83201. }
  83202. if (this._physicsEngine.getImpostors().length === 0) {
  83203. return null;
  83204. }
  83205. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83206. event.dispose(false);
  83207. return event;
  83208. };
  83209. /**
  83210. * @param {Vector3} origin the of the vortex
  83211. * @param {number} radius the radius of the vortex
  83212. * @param {number} strength the strength of the vortex
  83213. * @param {number} height the height of the vortex
  83214. */
  83215. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83216. if (!this._physicsEngine) {
  83217. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83218. return null;
  83219. }
  83220. if (this._physicsEngine.getImpostors().length === 0) {
  83221. return null;
  83222. }
  83223. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83224. event.dispose(false);
  83225. return event;
  83226. };
  83227. return PhysicsHelper;
  83228. }());
  83229. BABYLON.PhysicsHelper = PhysicsHelper;
  83230. /***** Radial explosion *****/
  83231. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83232. function PhysicsRadialExplosionEvent(scene) {
  83233. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83234. this._rays = [];
  83235. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83236. this._scene = scene;
  83237. }
  83238. /**
  83239. * Returns the data related to the radial explosion event (sphere & rays).
  83240. * @returns {PhysicsRadialExplosionEventData}
  83241. */
  83242. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83243. this._dataFetched = true;
  83244. return {
  83245. sphere: this._sphere,
  83246. rays: this._rays,
  83247. };
  83248. };
  83249. /**
  83250. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83251. * @param impostor
  83252. * @param {Vector3} origin the origin of the explosion
  83253. * @param {number} radius the explosion radius
  83254. * @param {number} strength the explosion strength
  83255. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83256. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83257. */
  83258. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83259. if (impostor.mass === 0) {
  83260. return null;
  83261. }
  83262. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83263. return null;
  83264. }
  83265. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83266. return null;
  83267. }
  83268. var impostorObjectCenter = impostor.getObjectCenter();
  83269. var direction = impostorObjectCenter.subtract(origin);
  83270. var ray = new BABYLON.Ray(origin, direction, radius);
  83271. this._rays.push(ray);
  83272. var hit = ray.intersectsMesh(impostor.object);
  83273. var contactPoint = hit.pickedPoint;
  83274. if (!contactPoint) {
  83275. return null;
  83276. }
  83277. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83278. if (distanceFromOrigin > radius) {
  83279. return null;
  83280. }
  83281. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83282. ? strength
  83283. : strength * (1 - (distanceFromOrigin / radius));
  83284. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83285. return { force: force, contactPoint: contactPoint };
  83286. };
  83287. /**
  83288. * Disposes the sphere.
  83289. * @param {bolean} force
  83290. */
  83291. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83292. var _this = this;
  83293. if (force === void 0) { force = true; }
  83294. if (force) {
  83295. this._sphere.dispose();
  83296. }
  83297. else {
  83298. setTimeout(function () {
  83299. if (!_this._dataFetched) {
  83300. _this._sphere.dispose();
  83301. }
  83302. }, 0);
  83303. }
  83304. };
  83305. /*** Helpers ***/
  83306. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83307. if (!this._sphere) {
  83308. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83309. this._sphere.isVisible = false;
  83310. }
  83311. };
  83312. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83313. var impostorObject = impostor.object;
  83314. this._prepareSphere();
  83315. this._sphere.position = origin;
  83316. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83317. this._sphere._updateBoundingInfo();
  83318. this._sphere.computeWorldMatrix(true);
  83319. return this._sphere.intersectsMesh(impostorObject, true);
  83320. };
  83321. return PhysicsRadialExplosionEvent;
  83322. }());
  83323. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83324. /***** Gravitational Field *****/
  83325. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83326. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83327. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83328. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83329. this._physicsHelper = physicsHelper;
  83330. this._scene = scene;
  83331. this._origin = origin;
  83332. this._radius = radius;
  83333. this._strength = strength;
  83334. this._falloff = falloff;
  83335. this._tickCallback = this._tick.bind(this);
  83336. }
  83337. /**
  83338. * Returns the data related to the gravitational field event (sphere).
  83339. * @returns {PhysicsGravitationalFieldEventData}
  83340. */
  83341. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83342. this._dataFetched = true;
  83343. return {
  83344. sphere: this._sphere,
  83345. };
  83346. };
  83347. /**
  83348. * Enables the gravitational field.
  83349. */
  83350. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83351. this._tickCallback.call(this);
  83352. this._scene.registerBeforeRender(this._tickCallback);
  83353. };
  83354. /**
  83355. * Disables the gravitational field.
  83356. */
  83357. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83358. this._scene.unregisterBeforeRender(this._tickCallback);
  83359. };
  83360. /**
  83361. * Disposes the sphere.
  83362. * @param {bolean} force
  83363. */
  83364. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83365. var _this = this;
  83366. if (force === void 0) { force = true; }
  83367. if (force) {
  83368. this._sphere.dispose();
  83369. }
  83370. else {
  83371. setTimeout(function () {
  83372. if (!_this._dataFetched) {
  83373. _this._sphere.dispose();
  83374. }
  83375. }, 0);
  83376. }
  83377. };
  83378. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83379. // Since the params won't change, we fetch the event only once
  83380. if (this._sphere) {
  83381. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83382. }
  83383. else {
  83384. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83385. if (radialExplosionEvent) {
  83386. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83387. }
  83388. }
  83389. };
  83390. return PhysicsGravitationalFieldEvent;
  83391. }());
  83392. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83393. /***** Updraft *****/
  83394. var PhysicsUpdraftEvent = /** @class */ (function () {
  83395. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83396. this._scene = _scene;
  83397. this._origin = _origin;
  83398. this._radius = _radius;
  83399. this._strength = _strength;
  83400. this._height = _height;
  83401. this._updraftMode = _updraftMode;
  83402. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83403. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83404. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83405. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83406. this._physicsEngine = this._scene.getPhysicsEngine();
  83407. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83408. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83409. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83410. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83411. }
  83412. this._tickCallback = this._tick.bind(this);
  83413. }
  83414. /**
  83415. * Returns the data related to the updraft event (cylinder).
  83416. * @returns {PhysicsUpdraftEventData}
  83417. */
  83418. PhysicsUpdraftEvent.prototype.getData = function () {
  83419. this._dataFetched = true;
  83420. return {
  83421. cylinder: this._cylinder,
  83422. };
  83423. };
  83424. /**
  83425. * Enables the updraft.
  83426. */
  83427. PhysicsUpdraftEvent.prototype.enable = function () {
  83428. this._tickCallback.call(this);
  83429. this._scene.registerBeforeRender(this._tickCallback);
  83430. };
  83431. /**
  83432. * Disables the cortex.
  83433. */
  83434. PhysicsUpdraftEvent.prototype.disable = function () {
  83435. this._scene.unregisterBeforeRender(this._tickCallback);
  83436. };
  83437. /**
  83438. * Disposes the sphere.
  83439. * @param {bolean} force
  83440. */
  83441. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83442. var _this = this;
  83443. if (force === void 0) { force = true; }
  83444. if (force) {
  83445. this._cylinder.dispose();
  83446. }
  83447. else {
  83448. setTimeout(function () {
  83449. if (!_this._dataFetched) {
  83450. _this._cylinder.dispose();
  83451. }
  83452. }, 0);
  83453. }
  83454. };
  83455. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83456. if (impostor.mass === 0) {
  83457. return null;
  83458. }
  83459. if (!this._intersectsWithCylinder(impostor)) {
  83460. return null;
  83461. }
  83462. var impostorObjectCenter = impostor.getObjectCenter();
  83463. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83464. var direction = this._originDirection;
  83465. }
  83466. else {
  83467. var direction = impostorObjectCenter.subtract(this._originTop);
  83468. }
  83469. var multiplier = this._strength * -1;
  83470. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83471. return { force: force, contactPoint: impostorObjectCenter };
  83472. };
  83473. PhysicsUpdraftEvent.prototype._tick = function () {
  83474. var _this = this;
  83475. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83476. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83477. if (!impostorForceAndContactPoint) {
  83478. return;
  83479. }
  83480. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83481. });
  83482. };
  83483. /*** Helpers ***/
  83484. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83485. if (!this._cylinder) {
  83486. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83487. height: this._height,
  83488. diameter: this._radius * 2,
  83489. }, this._scene);
  83490. this._cylinder.isVisible = false;
  83491. }
  83492. };
  83493. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83494. var impostorObject = impostor.object;
  83495. this._prepareCylinder();
  83496. this._cylinder.position = this._cylinderPosition;
  83497. return this._cylinder.intersectsMesh(impostorObject, true);
  83498. };
  83499. return PhysicsUpdraftEvent;
  83500. }());
  83501. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83502. /***** Vortex *****/
  83503. var PhysicsVortexEvent = /** @class */ (function () {
  83504. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83505. this._scene = _scene;
  83506. this._origin = _origin;
  83507. this._radius = _radius;
  83508. this._strength = _strength;
  83509. this._height = _height;
  83510. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83511. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83512. this._updraftMultiplier = 0.02;
  83513. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83514. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83515. this._physicsEngine = this._scene.getPhysicsEngine();
  83516. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83517. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83518. this._tickCallback = this._tick.bind(this);
  83519. }
  83520. /**
  83521. * Returns the data related to the vortex event (cylinder).
  83522. * @returns {PhysicsVortexEventData}
  83523. */
  83524. PhysicsVortexEvent.prototype.getData = function () {
  83525. this._dataFetched = true;
  83526. return {
  83527. cylinder: this._cylinder,
  83528. };
  83529. };
  83530. /**
  83531. * Enables the vortex.
  83532. */
  83533. PhysicsVortexEvent.prototype.enable = function () {
  83534. this._tickCallback.call(this);
  83535. this._scene.registerBeforeRender(this._tickCallback);
  83536. };
  83537. /**
  83538. * Disables the cortex.
  83539. */
  83540. PhysicsVortexEvent.prototype.disable = function () {
  83541. this._scene.unregisterBeforeRender(this._tickCallback);
  83542. };
  83543. /**
  83544. * Disposes the sphere.
  83545. * @param {bolean} force
  83546. */
  83547. PhysicsVortexEvent.prototype.dispose = function (force) {
  83548. var _this = this;
  83549. if (force === void 0) { force = true; }
  83550. if (force) {
  83551. this._cylinder.dispose();
  83552. }
  83553. else {
  83554. setTimeout(function () {
  83555. if (!_this._dataFetched) {
  83556. _this._cylinder.dispose();
  83557. }
  83558. }, 0);
  83559. }
  83560. };
  83561. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83562. if (impostor.mass === 0) {
  83563. return null;
  83564. }
  83565. if (!this._intersectsWithCylinder(impostor)) {
  83566. return null;
  83567. }
  83568. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83569. return null;
  83570. }
  83571. var impostorObjectCenter = impostor.getObjectCenter();
  83572. 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)
  83573. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83574. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83575. var hit = ray.intersectsMesh(impostor.object);
  83576. var contactPoint = hit.pickedPoint;
  83577. if (!contactPoint) {
  83578. return null;
  83579. }
  83580. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83581. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83582. var directionToOrigin = contactPoint.normalize();
  83583. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83584. directionToOrigin = directionToOrigin.negate();
  83585. }
  83586. // TODO: find a more physically based solution
  83587. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83588. var forceX = directionToOrigin.x * this._strength / 8;
  83589. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83590. var forceZ = directionToOrigin.z * this._strength / 8;
  83591. }
  83592. else {
  83593. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83594. var forceY = this._originTop.y * this._updraftMultiplier;
  83595. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83596. }
  83597. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83598. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83599. return { force: force, contactPoint: impostorObjectCenter };
  83600. };
  83601. PhysicsVortexEvent.prototype._tick = function () {
  83602. var _this = this;
  83603. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83604. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83605. if (!impostorForceAndContactPoint) {
  83606. return;
  83607. }
  83608. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83609. });
  83610. };
  83611. /*** Helpers ***/
  83612. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83613. if (!this._cylinder) {
  83614. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83615. height: this._height,
  83616. diameter: this._radius * 2,
  83617. }, this._scene);
  83618. this._cylinder.isVisible = false;
  83619. }
  83620. };
  83621. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83622. var impostorObject = impostor.object;
  83623. this._prepareCylinder();
  83624. this._cylinder.position = this._cylinderPosition;
  83625. return this._cylinder.intersectsMesh(impostorObject, true);
  83626. };
  83627. return PhysicsVortexEvent;
  83628. }());
  83629. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83630. /***** Enums *****/
  83631. /**
  83632. * The strenght of the force in correspondence to the distance of the affected object
  83633. */
  83634. var PhysicsRadialImpulseFalloff;
  83635. (function (PhysicsRadialImpulseFalloff) {
  83636. /** Defines that impulse is constant in strength across it's whole radius */
  83637. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83638. /** DEfines that impulse gets weaker if it's further from the origin */
  83639. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83640. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83641. /**
  83642. * The strenght of the force in correspondence to the distance of the affected object
  83643. */
  83644. var PhysicsUpdraftMode;
  83645. (function (PhysicsUpdraftMode) {
  83646. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83647. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83648. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83649. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83650. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83651. })(BABYLON || (BABYLON = {}));
  83652. //# sourceMappingURL=babylon.physicsHelper.js.map
  83653. var BABYLON;
  83654. (function (BABYLON) {
  83655. var CannonJSPlugin = /** @class */ (function () {
  83656. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83657. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83658. if (iterations === void 0) { iterations = 10; }
  83659. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83660. this.name = "CannonJSPlugin";
  83661. this._physicsMaterials = new Array();
  83662. this._fixedTimeStep = 1 / 60;
  83663. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83664. this.BJSCANNON = CANNON;
  83665. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83666. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83667. this._tmpPosition = BABYLON.Vector3.Zero();
  83668. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83669. this._tmpUnityRotation = new BABYLON.Quaternion();
  83670. if (!this.isSupported()) {
  83671. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83672. return;
  83673. }
  83674. this._extendNamespace();
  83675. this.world = new this.BJSCANNON.World();
  83676. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83677. this.world.solver.iterations = iterations;
  83678. }
  83679. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83680. this.world.gravity.copy(gravity);
  83681. };
  83682. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83683. this._fixedTimeStep = timeStep;
  83684. };
  83685. CannonJSPlugin.prototype.getTimeStep = function () {
  83686. return this._fixedTimeStep;
  83687. };
  83688. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83689. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83690. };
  83691. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83692. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83693. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83694. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83695. };
  83696. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83697. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83698. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83699. impostor.physicsBody.applyForce(impulse, worldPoint);
  83700. };
  83701. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83702. //parent-child relationship. Does this impostor has a parent impostor?
  83703. if (impostor.parent) {
  83704. if (impostor.physicsBody) {
  83705. this.removePhysicsBody(impostor);
  83706. //TODO is that needed?
  83707. impostor.forceUpdate();
  83708. }
  83709. return;
  83710. }
  83711. //should a new body be created for this impostor?
  83712. if (impostor.isBodyInitRequired()) {
  83713. var shape = this._createShape(impostor);
  83714. //unregister events, if body is being changed
  83715. var oldBody = impostor.physicsBody;
  83716. if (oldBody) {
  83717. this.removePhysicsBody(impostor);
  83718. }
  83719. //create the body and material
  83720. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83721. var bodyCreationObject = {
  83722. mass: impostor.getParam("mass"),
  83723. material: material
  83724. };
  83725. // A simple extend, in case native options were used.
  83726. var nativeOptions = impostor.getParam("nativeOptions");
  83727. for (var key in nativeOptions) {
  83728. if (nativeOptions.hasOwnProperty(key)) {
  83729. bodyCreationObject[key] = nativeOptions[key];
  83730. }
  83731. }
  83732. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83733. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83734. this.world.addEventListener("preStep", impostor.beforeStep);
  83735. this.world.addEventListener("postStep", impostor.afterStep);
  83736. impostor.physicsBody.addShape(shape);
  83737. this.world.add(impostor.physicsBody);
  83738. //try to keep the body moving in the right direction by taking old properties.
  83739. //Should be tested!
  83740. if (oldBody) {
  83741. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83742. impostor.physicsBody[param].copy(oldBody[param]);
  83743. });
  83744. }
  83745. this._processChildMeshes(impostor);
  83746. }
  83747. //now update the body's transformation
  83748. this._updatePhysicsBodyTransformation(impostor);
  83749. };
  83750. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83751. var _this = this;
  83752. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83753. var currentRotation = mainImpostor.object.rotationQuaternion;
  83754. if (meshChildren.length) {
  83755. var processMesh = function (localPosition, mesh) {
  83756. if (!currentRotation || !mesh.rotationQuaternion) {
  83757. return;
  83758. }
  83759. var childImpostor = mesh.getPhysicsImpostor();
  83760. if (childImpostor) {
  83761. var parent = childImpostor.parent;
  83762. if (parent !== mainImpostor) {
  83763. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83764. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83765. if (childImpostor.physicsBody) {
  83766. _this.removePhysicsBody(childImpostor);
  83767. childImpostor.physicsBody = null;
  83768. }
  83769. childImpostor.parent = mainImpostor;
  83770. childImpostor.resetUpdateFlags();
  83771. 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));
  83772. //Add the mass of the children.
  83773. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83774. }
  83775. }
  83776. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83777. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83778. };
  83779. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83780. }
  83781. };
  83782. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83783. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83784. this.world.removeEventListener("preStep", impostor.beforeStep);
  83785. this.world.removeEventListener("postStep", impostor.afterStep);
  83786. this.world.remove(impostor.physicsBody);
  83787. };
  83788. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83789. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83790. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83791. if (!mainBody || !connectedBody) {
  83792. return;
  83793. }
  83794. var constraint;
  83795. var jointData = impostorJoint.joint.jointData;
  83796. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83797. var constraintData = {
  83798. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83799. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83800. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83801. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83802. maxForce: jointData.nativeParams.maxForce,
  83803. collideConnected: !!jointData.collision
  83804. };
  83805. switch (impostorJoint.joint.type) {
  83806. case BABYLON.PhysicsJoint.HingeJoint:
  83807. case BABYLON.PhysicsJoint.Hinge2Joint:
  83808. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83809. break;
  83810. case BABYLON.PhysicsJoint.DistanceJoint:
  83811. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83812. break;
  83813. case BABYLON.PhysicsJoint.SpringJoint:
  83814. var springData = jointData;
  83815. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83816. restLength: springData.length,
  83817. stiffness: springData.stiffness,
  83818. damping: springData.damping,
  83819. localAnchorA: constraintData.pivotA,
  83820. localAnchorB: constraintData.pivotB
  83821. });
  83822. break;
  83823. case BABYLON.PhysicsJoint.LockJoint:
  83824. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83825. break;
  83826. case BABYLON.PhysicsJoint.PointToPointJoint:
  83827. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83828. default:
  83829. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83830. break;
  83831. }
  83832. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83833. constraint.collideConnected = !!jointData.collision;
  83834. impostorJoint.joint.physicsJoint = constraint;
  83835. //don't add spring as constraint, as it is not one.
  83836. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83837. this.world.addConstraint(constraint);
  83838. }
  83839. else {
  83840. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83841. constraint.applyForce();
  83842. });
  83843. }
  83844. };
  83845. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83846. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83847. };
  83848. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83849. var index;
  83850. var mat;
  83851. for (index = 0; index < this._physicsMaterials.length; index++) {
  83852. mat = this._physicsMaterials[index];
  83853. if (mat.friction === friction && mat.restitution === restitution) {
  83854. return mat;
  83855. }
  83856. }
  83857. var currentMat = new this.BJSCANNON.Material(name);
  83858. currentMat.friction = friction;
  83859. currentMat.restitution = restitution;
  83860. this._physicsMaterials.push(currentMat);
  83861. return currentMat;
  83862. };
  83863. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83864. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83865. };
  83866. CannonJSPlugin.prototype._createShape = function (impostor) {
  83867. var object = impostor.object;
  83868. var returnValue;
  83869. var extendSize = impostor.getObjectExtendSize();
  83870. switch (impostor.type) {
  83871. case BABYLON.PhysicsImpostor.SphereImpostor:
  83872. var radiusX = extendSize.x;
  83873. var radiusY = extendSize.y;
  83874. var radiusZ = extendSize.z;
  83875. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83876. break;
  83877. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83878. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83879. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83880. break;
  83881. case BABYLON.PhysicsImpostor.BoxImpostor:
  83882. var box = extendSize.scale(0.5);
  83883. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83884. break;
  83885. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83886. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83887. returnValue = new this.BJSCANNON.Plane();
  83888. break;
  83889. case BABYLON.PhysicsImpostor.MeshImpostor:
  83890. // should transform the vertex data to world coordinates!!
  83891. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83892. var rawFaces = object.getIndices ? object.getIndices() : [];
  83893. if (!rawVerts)
  83894. return;
  83895. // get only scale! so the object could transform correctly.
  83896. var oldPosition = object.position.clone();
  83897. var oldRotation = object.rotation && object.rotation.clone();
  83898. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83899. object.position.copyFromFloats(0, 0, 0);
  83900. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83901. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83902. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83903. var transform = object.computeWorldMatrix(true);
  83904. // convert rawVerts to object space
  83905. var temp = new Array();
  83906. var index;
  83907. for (index = 0; index < rawVerts.length; index += 3) {
  83908. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83909. }
  83910. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83911. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83912. //now set back the transformation!
  83913. object.position.copyFrom(oldPosition);
  83914. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83915. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83916. break;
  83917. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83918. var oldPosition2 = object.position.clone();
  83919. var oldRotation2 = object.rotation && object.rotation.clone();
  83920. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83921. object.position.copyFromFloats(0, 0, 0);
  83922. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83923. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83924. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83925. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83926. returnValue = this._createHeightmap(object);
  83927. object.position.copyFrom(oldPosition2);
  83928. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83929. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83930. object.computeWorldMatrix(true);
  83931. break;
  83932. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83933. returnValue = new this.BJSCANNON.Particle();
  83934. break;
  83935. }
  83936. return returnValue;
  83937. };
  83938. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83939. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83940. var transform = object.computeWorldMatrix(true);
  83941. // convert rawVerts to object space
  83942. var temp = new Array();
  83943. var index;
  83944. for (index = 0; index < pos.length; index += 3) {
  83945. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83946. }
  83947. pos = temp;
  83948. var matrix = new Array();
  83949. //For now pointDepth will not be used and will be automatically calculated.
  83950. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83951. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83952. var boundingInfo = object.getBoundingInfo();
  83953. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83954. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83955. var elementSize = dim * 2 / arraySize;
  83956. for (var i = 0; i < pos.length; i = i + 3) {
  83957. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83958. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83959. var y = -pos[i + 2] + minY;
  83960. if (!matrix[x]) {
  83961. matrix[x] = [];
  83962. }
  83963. if (!matrix[x][z]) {
  83964. matrix[x][z] = y;
  83965. }
  83966. matrix[x][z] = Math.max(y, matrix[x][z]);
  83967. }
  83968. for (var x = 0; x <= arraySize; ++x) {
  83969. if (!matrix[x]) {
  83970. var loc = 1;
  83971. while (!matrix[(x + loc) % arraySize]) {
  83972. loc++;
  83973. }
  83974. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83975. //console.log("missing x", x);
  83976. }
  83977. for (var z = 0; z <= arraySize; ++z) {
  83978. if (!matrix[x][z]) {
  83979. var loc = 1;
  83980. var newValue;
  83981. while (newValue === undefined) {
  83982. newValue = matrix[x][(z + loc++) % arraySize];
  83983. }
  83984. matrix[x][z] = newValue;
  83985. }
  83986. }
  83987. }
  83988. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83989. elementSize: elementSize
  83990. });
  83991. //For future reference, needed for body transformation
  83992. shape.minY = minY;
  83993. return shape;
  83994. };
  83995. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83996. var object = impostor.object;
  83997. //make sure it is updated...
  83998. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83999. // The delta between the mesh position and the mesh bounding box center
  84000. var bInfo = object.getBoundingInfo();
  84001. if (!bInfo)
  84002. return;
  84003. var center = impostor.getObjectCenter();
  84004. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84005. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84006. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84007. this._tmpPosition.copyFrom(center);
  84008. var quaternion = object.rotationQuaternion;
  84009. if (!quaternion) {
  84010. return;
  84011. }
  84012. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84013. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84014. //-90 DEG in X, precalculated
  84015. quaternion = quaternion.multiply(this._minus90X);
  84016. //Invert! (Precalculated, 90 deg in X)
  84017. //No need to clone. this will never change.
  84018. impostor.setDeltaRotation(this._plus90X);
  84019. }
  84020. //If it is a heightfield, if should be centered.
  84021. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84022. var mesh = object;
  84023. var boundingInfo = mesh.getBoundingInfo();
  84024. //calculate the correct body position:
  84025. var rotationQuaternion = mesh.rotationQuaternion;
  84026. mesh.rotationQuaternion = this._tmpUnityRotation;
  84027. mesh.computeWorldMatrix(true);
  84028. //get original center with no rotation
  84029. var c = center.clone();
  84030. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84031. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84032. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84033. mesh.setPreTransformMatrix(p);
  84034. mesh.computeWorldMatrix(true);
  84035. //calculate the translation
  84036. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84037. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84038. //add it inverted to the delta
  84039. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84040. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84041. //rotation is back
  84042. mesh.rotationQuaternion = rotationQuaternion;
  84043. mesh.setPreTransformMatrix(oldPivot);
  84044. mesh.computeWorldMatrix(true);
  84045. }
  84046. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84047. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84048. //this._tmpPosition.copyFrom(object.position);
  84049. }
  84050. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84051. //Now update the impostor object
  84052. impostor.physicsBody.position.copy(this._tmpPosition);
  84053. impostor.physicsBody.quaternion.copy(quaternion);
  84054. };
  84055. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84056. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84057. if (impostor.object.rotationQuaternion) {
  84058. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84059. }
  84060. };
  84061. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84062. impostor.physicsBody.position.copy(newPosition);
  84063. impostor.physicsBody.quaternion.copy(newRotation);
  84064. };
  84065. CannonJSPlugin.prototype.isSupported = function () {
  84066. return this.BJSCANNON !== undefined;
  84067. };
  84068. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84069. impostor.physicsBody.velocity.copy(velocity);
  84070. };
  84071. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84072. impostor.physicsBody.angularVelocity.copy(velocity);
  84073. };
  84074. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84075. var v = impostor.physicsBody.velocity;
  84076. if (!v) {
  84077. return null;
  84078. }
  84079. return new BABYLON.Vector3(v.x, v.y, v.z);
  84080. };
  84081. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84082. var v = impostor.physicsBody.angularVelocity;
  84083. if (!v) {
  84084. return null;
  84085. }
  84086. return new BABYLON.Vector3(v.x, v.y, v.z);
  84087. };
  84088. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84089. impostor.physicsBody.mass = mass;
  84090. impostor.physicsBody.updateMassProperties();
  84091. };
  84092. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84093. return impostor.physicsBody.mass;
  84094. };
  84095. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84096. return impostor.physicsBody.material.friction;
  84097. };
  84098. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84099. impostor.physicsBody.material.friction = friction;
  84100. };
  84101. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84102. return impostor.physicsBody.material.restitution;
  84103. };
  84104. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84105. impostor.physicsBody.material.restitution = restitution;
  84106. };
  84107. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84108. impostor.physicsBody.sleep();
  84109. };
  84110. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84111. impostor.physicsBody.wakeUp();
  84112. };
  84113. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84114. joint.physicsJoint.distance = maxDistance;
  84115. };
  84116. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84117. // if (!motorIndex) {
  84118. // joint.physicsJoint.enableMotor();
  84119. // }
  84120. // }
  84121. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84122. // if (!motorIndex) {
  84123. // joint.physicsJoint.disableMotor();
  84124. // }
  84125. // }
  84126. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84127. if (!motorIndex) {
  84128. joint.physicsJoint.enableMotor();
  84129. joint.physicsJoint.setMotorSpeed(speed);
  84130. if (maxForce) {
  84131. this.setLimit(joint, maxForce);
  84132. }
  84133. }
  84134. };
  84135. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84136. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84137. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84138. };
  84139. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84140. var body = impostor.physicsBody;
  84141. mesh.position.x = body.position.x;
  84142. mesh.position.y = body.position.y;
  84143. mesh.position.z = body.position.z;
  84144. if (mesh.rotationQuaternion) {
  84145. mesh.rotationQuaternion.x = body.quaternion.x;
  84146. mesh.rotationQuaternion.y = body.quaternion.y;
  84147. mesh.rotationQuaternion.z = body.quaternion.z;
  84148. mesh.rotationQuaternion.w = body.quaternion.w;
  84149. }
  84150. };
  84151. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84152. var shape = impostor.physicsBody.shapes[0];
  84153. return shape.boundingSphereRadius;
  84154. };
  84155. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84156. var shape = impostor.physicsBody.shapes[0];
  84157. result.x = shape.halfExtents.x * 2;
  84158. result.y = shape.halfExtents.y * 2;
  84159. result.z = shape.halfExtents.z * 2;
  84160. };
  84161. CannonJSPlugin.prototype.dispose = function () {
  84162. };
  84163. CannonJSPlugin.prototype._extendNamespace = function () {
  84164. //this will force cannon to execute at least one step when using interpolation
  84165. var step_tmp1 = new this.BJSCANNON.Vec3();
  84166. var Engine = this.BJSCANNON;
  84167. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84168. maxSubSteps = maxSubSteps || 10;
  84169. timeSinceLastCalled = timeSinceLastCalled || 0;
  84170. if (timeSinceLastCalled === 0) {
  84171. this.internalStep(dt);
  84172. this.time += dt;
  84173. }
  84174. else {
  84175. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84176. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84177. var t0 = performance.now();
  84178. for (var i = 0; i !== internalSteps; i++) {
  84179. this.internalStep(dt);
  84180. if (performance.now() - t0 > dt * 1000) {
  84181. break;
  84182. }
  84183. }
  84184. this.time += timeSinceLastCalled;
  84185. var h = this.time % dt;
  84186. var h_div_dt = h / dt;
  84187. var interpvelo = step_tmp1;
  84188. var bodies = this.bodies;
  84189. for (var j = 0; j !== bodies.length; j++) {
  84190. var b = bodies[j];
  84191. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84192. b.position.vsub(b.previousPosition, interpvelo);
  84193. interpvelo.scale(h_div_dt, interpvelo);
  84194. b.position.vadd(interpvelo, b.interpolatedPosition);
  84195. }
  84196. else {
  84197. b.interpolatedPosition.copy(b.position);
  84198. b.interpolatedQuaternion.copy(b.quaternion);
  84199. }
  84200. }
  84201. }
  84202. };
  84203. };
  84204. return CannonJSPlugin;
  84205. }());
  84206. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84207. })(BABYLON || (BABYLON = {}));
  84208. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84209. var BABYLON;
  84210. (function (BABYLON) {
  84211. var OimoJSPlugin = /** @class */ (function () {
  84212. function OimoJSPlugin(iterations) {
  84213. this.name = "OimoJSPlugin";
  84214. this._tmpImpostorsArray = [];
  84215. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84216. this.BJSOIMO = OIMO;
  84217. this.world = new this.BJSOIMO.World({
  84218. iterations: iterations
  84219. });
  84220. this.world.clear();
  84221. }
  84222. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84223. this.world.gravity.copy(gravity);
  84224. };
  84225. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84226. this.world.timeStep = timeStep;
  84227. };
  84228. OimoJSPlugin.prototype.getTimeStep = function () {
  84229. return this.world.timeStep;
  84230. };
  84231. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84232. var _this = this;
  84233. impostors.forEach(function (impostor) {
  84234. impostor.beforeStep();
  84235. });
  84236. this.world.step();
  84237. impostors.forEach(function (impostor) {
  84238. impostor.afterStep();
  84239. //update the ordered impostors array
  84240. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84241. });
  84242. //check for collisions
  84243. var contact = this.world.contacts;
  84244. while (contact !== null) {
  84245. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84246. contact = contact.next;
  84247. continue;
  84248. }
  84249. //is this body colliding with any other? get the impostor
  84250. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84251. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84252. if (!mainImpostor || !collidingImpostor) {
  84253. contact = contact.next;
  84254. continue;
  84255. }
  84256. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84257. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84258. contact = contact.next;
  84259. }
  84260. };
  84261. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84262. var mass = impostor.physicsBody.mass;
  84263. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84264. };
  84265. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84266. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84267. this.applyImpulse(impostor, force, contactPoint);
  84268. };
  84269. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84270. var _this = this;
  84271. //parent-child relationship. Does this impostor has a parent impostor?
  84272. if (impostor.parent) {
  84273. if (impostor.physicsBody) {
  84274. this.removePhysicsBody(impostor);
  84275. //TODO is that needed?
  84276. impostor.forceUpdate();
  84277. }
  84278. return;
  84279. }
  84280. if (impostor.isBodyInitRequired()) {
  84281. var bodyConfig = {
  84282. name: impostor.uniqueId,
  84283. //Oimo must have mass, also for static objects.
  84284. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84285. size: [],
  84286. type: [],
  84287. pos: [],
  84288. posShape: [],
  84289. rot: [],
  84290. rotShape: [],
  84291. move: impostor.getParam("mass") !== 0,
  84292. density: impostor.getParam("mass"),
  84293. friction: impostor.getParam("friction"),
  84294. restitution: impostor.getParam("restitution"),
  84295. //Supporting older versions of Oimo
  84296. world: this.world
  84297. };
  84298. var impostors = [impostor];
  84299. var addToArray = function (parent) {
  84300. if (!parent.getChildMeshes)
  84301. return;
  84302. parent.getChildMeshes().forEach(function (m) {
  84303. if (m.physicsImpostor) {
  84304. impostors.push(m.physicsImpostor);
  84305. //m.physicsImpostor._init();
  84306. }
  84307. });
  84308. };
  84309. addToArray(impostor.object);
  84310. var checkWithEpsilon_1 = function (value) {
  84311. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84312. };
  84313. impostors.forEach(function (i) {
  84314. if (!i.object.rotationQuaternion) {
  84315. return;
  84316. }
  84317. //get the correct bounding box
  84318. var oldQuaternion = i.object.rotationQuaternion;
  84319. var rot = oldQuaternion.toEulerAngles();
  84320. var extendSize = i.getObjectExtendSize();
  84321. var radToDeg = 57.295779513082320876;
  84322. if (i === impostor) {
  84323. var center = impostor.getObjectCenter();
  84324. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84325. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84326. //Can also use Array.prototype.push.apply
  84327. bodyConfig.pos.push(center.x);
  84328. bodyConfig.pos.push(center.y);
  84329. bodyConfig.pos.push(center.z);
  84330. bodyConfig.posShape.push(0, 0, 0);
  84331. //tmp solution
  84332. bodyConfig.rot.push(rot.x * radToDeg);
  84333. bodyConfig.rot.push(rot.y * radToDeg);
  84334. bodyConfig.rot.push(rot.z * radToDeg);
  84335. bodyConfig.rotShape.push(0, 0, 0);
  84336. }
  84337. else {
  84338. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84339. bodyConfig.posShape.push(localPosition.x);
  84340. bodyConfig.posShape.push(localPosition.y);
  84341. bodyConfig.posShape.push(localPosition.z);
  84342. bodyConfig.pos.push(0, 0, 0);
  84343. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84344. bodyConfig.rot.push(0);
  84345. bodyConfig.rot.push(0);
  84346. bodyConfig.rot.push(0);
  84347. bodyConfig.rotShape.push(rot.x * radToDeg);
  84348. bodyConfig.rotShape.push(rot.y * radToDeg);
  84349. bodyConfig.rotShape.push(rot.z * radToDeg);
  84350. }
  84351. // register mesh
  84352. switch (i.type) {
  84353. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84354. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84355. case BABYLON.PhysicsImpostor.SphereImpostor:
  84356. var radiusX = extendSize.x;
  84357. var radiusY = extendSize.y;
  84358. var radiusZ = extendSize.z;
  84359. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84360. bodyConfig.type.push('sphere');
  84361. //due to the way oimo works with compounds, add 3 times
  84362. bodyConfig.size.push(size);
  84363. bodyConfig.size.push(size);
  84364. bodyConfig.size.push(size);
  84365. break;
  84366. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84367. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84368. var sizeY = checkWithEpsilon_1(extendSize.y);
  84369. bodyConfig.type.push('cylinder');
  84370. bodyConfig.size.push(sizeX);
  84371. bodyConfig.size.push(sizeY);
  84372. //due to the way oimo works with compounds, add one more value.
  84373. bodyConfig.size.push(sizeY);
  84374. break;
  84375. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84376. case BABYLON.PhysicsImpostor.BoxImpostor:
  84377. default:
  84378. var sizeX = checkWithEpsilon_1(extendSize.x);
  84379. var sizeY = checkWithEpsilon_1(extendSize.y);
  84380. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84381. bodyConfig.type.push('box');
  84382. //if (i === impostor) {
  84383. bodyConfig.size.push(sizeX);
  84384. bodyConfig.size.push(sizeY);
  84385. bodyConfig.size.push(sizeZ);
  84386. //} else {
  84387. // bodyConfig.size.push(0,0,0);
  84388. //}
  84389. break;
  84390. }
  84391. //actually not needed, but hey...
  84392. i.object.rotationQuaternion = oldQuaternion;
  84393. });
  84394. impostor.physicsBody = this.world.add(bodyConfig);
  84395. }
  84396. else {
  84397. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84398. }
  84399. impostor.setDeltaPosition(this._tmpPositionVector);
  84400. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84401. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84402. };
  84403. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84404. //impostor.physicsBody.dispose();
  84405. //Same as : (older oimo versions)
  84406. this.world.removeRigidBody(impostor.physicsBody);
  84407. };
  84408. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84409. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84410. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84411. if (!mainBody || !connectedBody) {
  84412. return;
  84413. }
  84414. var jointData = impostorJoint.joint.jointData;
  84415. var options = jointData.nativeParams || {};
  84416. var type;
  84417. var nativeJointData = {
  84418. body1: mainBody,
  84419. body2: connectedBody,
  84420. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84421. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84422. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84423. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84424. min: options.min,
  84425. max: options.max,
  84426. collision: options.collision || jointData.collision,
  84427. spring: options.spring,
  84428. //supporting older version of Oimo
  84429. world: this.world
  84430. };
  84431. switch (impostorJoint.joint.type) {
  84432. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84433. type = "jointBall";
  84434. break;
  84435. case BABYLON.PhysicsJoint.SpringJoint:
  84436. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84437. var springData = jointData;
  84438. nativeJointData.min = springData.length || nativeJointData.min;
  84439. //Max should also be set, just make sure it is at least min
  84440. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84441. case BABYLON.PhysicsJoint.DistanceJoint:
  84442. type = "jointDistance";
  84443. nativeJointData.max = jointData.maxDistance;
  84444. break;
  84445. case BABYLON.PhysicsJoint.PrismaticJoint:
  84446. type = "jointPrisme";
  84447. break;
  84448. case BABYLON.PhysicsJoint.SliderJoint:
  84449. type = "jointSlide";
  84450. break;
  84451. case BABYLON.PhysicsJoint.WheelJoint:
  84452. type = "jointWheel";
  84453. break;
  84454. case BABYLON.PhysicsJoint.HingeJoint:
  84455. default:
  84456. type = "jointHinge";
  84457. break;
  84458. }
  84459. nativeJointData.type = type;
  84460. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84461. };
  84462. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84463. //Bug in Oimo prevents us from disposing a joint in the playground
  84464. //joint.joint.physicsJoint.dispose();
  84465. //So we will bruteforce it!
  84466. try {
  84467. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84468. }
  84469. catch (e) {
  84470. BABYLON.Tools.Warn(e);
  84471. }
  84472. };
  84473. OimoJSPlugin.prototype.isSupported = function () {
  84474. return this.BJSOIMO !== undefined;
  84475. };
  84476. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84477. if (!impostor.physicsBody.sleeping) {
  84478. //TODO check that
  84479. /*if (impostor.physicsBody.shapes.next) {
  84480. var parentShape = this._getLastShape(impostor.physicsBody);
  84481. impostor.object.position.copyFrom(parentShape.position);
  84482. console.log(parentShape.position);
  84483. } else {*/
  84484. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84485. //}
  84486. if (impostor.object.rotationQuaternion) {
  84487. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84488. }
  84489. }
  84490. };
  84491. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84492. var body = impostor.physicsBody;
  84493. body.position.copy(newPosition);
  84494. body.orientation.copy(newRotation);
  84495. body.syncShapes();
  84496. body.awake();
  84497. };
  84498. /*private _getLastShape(body: any): any {
  84499. var lastShape = body.shapes;
  84500. while (lastShape.next) {
  84501. lastShape = lastShape.next;
  84502. }
  84503. return lastShape;
  84504. }*/
  84505. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84506. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84507. };
  84508. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84509. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84510. };
  84511. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84512. var v = impostor.physicsBody.linearVelocity;
  84513. if (!v) {
  84514. return null;
  84515. }
  84516. return new BABYLON.Vector3(v.x, v.y, v.z);
  84517. };
  84518. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84519. var v = impostor.physicsBody.angularVelocity;
  84520. if (!v) {
  84521. return null;
  84522. }
  84523. return new BABYLON.Vector3(v.x, v.y, v.z);
  84524. };
  84525. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84526. var staticBody = mass === 0;
  84527. //this will actually set the body's density and not its mass.
  84528. //But this is how oimo treats the mass variable.
  84529. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84530. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84531. };
  84532. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84533. return impostor.physicsBody.shapes.density;
  84534. };
  84535. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84536. return impostor.physicsBody.shapes.friction;
  84537. };
  84538. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84539. impostor.physicsBody.shapes.friction = friction;
  84540. };
  84541. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84542. return impostor.physicsBody.shapes.restitution;
  84543. };
  84544. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84545. impostor.physicsBody.shapes.restitution = restitution;
  84546. };
  84547. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84548. impostor.physicsBody.sleep();
  84549. };
  84550. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84551. impostor.physicsBody.awake();
  84552. };
  84553. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84554. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84555. if (minDistance !== void 0) {
  84556. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84557. }
  84558. };
  84559. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84560. //TODO separate rotational and transational motors.
  84561. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84562. if (motor) {
  84563. motor.setMotor(speed, maxForce);
  84564. }
  84565. };
  84566. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84567. //TODO separate rotational and transational motors.
  84568. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84569. if (motor) {
  84570. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84571. }
  84572. };
  84573. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84574. var body = impostor.physicsBody;
  84575. mesh.position.x = body.position.x;
  84576. mesh.position.y = body.position.y;
  84577. mesh.position.z = body.position.z;
  84578. if (mesh.rotationQuaternion) {
  84579. mesh.rotationQuaternion.x = body.orientation.x;
  84580. mesh.rotationQuaternion.y = body.orientation.y;
  84581. mesh.rotationQuaternion.z = body.orientation.z;
  84582. mesh.rotationQuaternion.w = body.orientation.s;
  84583. }
  84584. };
  84585. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84586. return impostor.physicsBody.shapes.radius;
  84587. };
  84588. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84589. var shape = impostor.physicsBody.shapes;
  84590. result.x = shape.halfWidth * 2;
  84591. result.y = shape.halfHeight * 2;
  84592. result.z = shape.halfDepth * 2;
  84593. };
  84594. OimoJSPlugin.prototype.dispose = function () {
  84595. this.world.clear();
  84596. };
  84597. return OimoJSPlugin;
  84598. }());
  84599. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84600. })(BABYLON || (BABYLON = {}));
  84601. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84602. var BABYLON;
  84603. (function (BABYLON) {
  84604. /*
  84605. * Based on jsTGALoader - Javascript loader for TGA file
  84606. * By Vincent Thibault
  84607. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84608. */
  84609. var TGATools = /** @class */ (function () {
  84610. function TGATools() {
  84611. }
  84612. TGATools.GetTGAHeader = function (data) {
  84613. var offset = 0;
  84614. var header = {
  84615. id_length: data[offset++],
  84616. colormap_type: data[offset++],
  84617. image_type: data[offset++],
  84618. colormap_index: data[offset++] | data[offset++] << 8,
  84619. colormap_length: data[offset++] | data[offset++] << 8,
  84620. colormap_size: data[offset++],
  84621. origin: [
  84622. data[offset++] | data[offset++] << 8,
  84623. data[offset++] | data[offset++] << 8
  84624. ],
  84625. width: data[offset++] | data[offset++] << 8,
  84626. height: data[offset++] | data[offset++] << 8,
  84627. pixel_size: data[offset++],
  84628. flags: data[offset++]
  84629. };
  84630. return header;
  84631. };
  84632. TGATools.UploadContent = function (gl, data) {
  84633. // Not enough data to contain header ?
  84634. if (data.length < 19) {
  84635. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84636. return;
  84637. }
  84638. // Read Header
  84639. var offset = 18;
  84640. var header = TGATools.GetTGAHeader(data);
  84641. // Assume it's a valid Targa file.
  84642. if (header.id_length + offset > data.length) {
  84643. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84644. return;
  84645. }
  84646. // Skip not needed data
  84647. offset += header.id_length;
  84648. var use_rle = false;
  84649. var use_pal = false;
  84650. var use_grey = false;
  84651. // Get some informations.
  84652. switch (header.image_type) {
  84653. case TGATools._TYPE_RLE_INDEXED:
  84654. use_rle = true;
  84655. case TGATools._TYPE_INDEXED:
  84656. use_pal = true;
  84657. break;
  84658. case TGATools._TYPE_RLE_RGB:
  84659. use_rle = true;
  84660. case TGATools._TYPE_RGB:
  84661. // use_rgb = true;
  84662. break;
  84663. case TGATools._TYPE_RLE_GREY:
  84664. use_rle = true;
  84665. case TGATools._TYPE_GREY:
  84666. use_grey = true;
  84667. break;
  84668. }
  84669. var pixel_data;
  84670. // var numAlphaBits = header.flags & 0xf;
  84671. var pixel_size = header.pixel_size >> 3;
  84672. var pixel_total = header.width * header.height * pixel_size;
  84673. // Read palettes
  84674. var palettes;
  84675. if (use_pal) {
  84676. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84677. }
  84678. // Read LRE
  84679. if (use_rle) {
  84680. pixel_data = new Uint8Array(pixel_total);
  84681. var c, count, i;
  84682. var localOffset = 0;
  84683. var pixels = new Uint8Array(pixel_size);
  84684. while (offset < pixel_total && localOffset < pixel_total) {
  84685. c = data[offset++];
  84686. count = (c & 0x7f) + 1;
  84687. // RLE pixels
  84688. if (c & 0x80) {
  84689. // Bind pixel tmp array
  84690. for (i = 0; i < pixel_size; ++i) {
  84691. pixels[i] = data[offset++];
  84692. }
  84693. // Copy pixel array
  84694. for (i = 0; i < count; ++i) {
  84695. pixel_data.set(pixels, localOffset + i * pixel_size);
  84696. }
  84697. localOffset += pixel_size * count;
  84698. }
  84699. // Raw pixels
  84700. else {
  84701. count *= pixel_size;
  84702. for (i = 0; i < count; ++i) {
  84703. pixel_data[localOffset + i] = data[offset++];
  84704. }
  84705. localOffset += count;
  84706. }
  84707. }
  84708. }
  84709. // RAW Pixels
  84710. else {
  84711. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84712. }
  84713. // Load to texture
  84714. var x_start, y_start, x_step, y_step, y_end, x_end;
  84715. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84716. default:
  84717. case TGATools._ORIGIN_UL:
  84718. x_start = 0;
  84719. x_step = 1;
  84720. x_end = header.width;
  84721. y_start = 0;
  84722. y_step = 1;
  84723. y_end = header.height;
  84724. break;
  84725. case TGATools._ORIGIN_BL:
  84726. x_start = 0;
  84727. x_step = 1;
  84728. x_end = header.width;
  84729. y_start = header.height - 1;
  84730. y_step = -1;
  84731. y_end = -1;
  84732. break;
  84733. case TGATools._ORIGIN_UR:
  84734. x_start = header.width - 1;
  84735. x_step = -1;
  84736. x_end = -1;
  84737. y_start = 0;
  84738. y_step = 1;
  84739. y_end = header.height;
  84740. break;
  84741. case TGATools._ORIGIN_BR:
  84742. x_start = header.width - 1;
  84743. x_step = -1;
  84744. x_end = -1;
  84745. y_start = header.height - 1;
  84746. y_step = -1;
  84747. y_end = -1;
  84748. break;
  84749. }
  84750. // Load the specify method
  84751. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84752. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84753. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84754. };
  84755. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84756. var image = pixel_data, colormap = palettes;
  84757. var width = header.width, height = header.height;
  84758. var color, i = 0, x, y;
  84759. var imageData = new Uint8Array(width * height * 4);
  84760. for (y = y_start; y !== y_end; y += y_step) {
  84761. for (x = x_start; x !== x_end; x += x_step, i++) {
  84762. color = image[i];
  84763. imageData[(x + width * y) * 4 + 3] = 255;
  84764. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84765. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84766. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84767. }
  84768. }
  84769. return imageData;
  84770. };
  84771. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84772. var image = pixel_data;
  84773. var width = header.width, height = header.height;
  84774. var color, i = 0, x, y;
  84775. var imageData = new Uint8Array(width * height * 4);
  84776. for (y = y_start; y !== y_end; y += y_step) {
  84777. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84778. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84779. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84780. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84781. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84782. imageData[(x + width * y) * 4 + 0] = r;
  84783. imageData[(x + width * y) * 4 + 1] = g;
  84784. imageData[(x + width * y) * 4 + 2] = b;
  84785. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84786. }
  84787. }
  84788. return imageData;
  84789. };
  84790. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84791. var image = pixel_data;
  84792. var width = header.width, height = header.height;
  84793. var i = 0, x, y;
  84794. var imageData = new Uint8Array(width * height * 4);
  84795. for (y = y_start; y !== y_end; y += y_step) {
  84796. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84797. imageData[(x + width * y) * 4 + 3] = 255;
  84798. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84799. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84800. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84801. }
  84802. }
  84803. return imageData;
  84804. };
  84805. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84806. var image = pixel_data;
  84807. var width = header.width, height = header.height;
  84808. var i = 0, x, y;
  84809. var imageData = new Uint8Array(width * height * 4);
  84810. for (y = y_start; y !== y_end; y += y_step) {
  84811. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84812. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84813. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84814. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84815. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84816. }
  84817. }
  84818. return imageData;
  84819. };
  84820. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84821. var image = pixel_data;
  84822. var width = header.width, height = header.height;
  84823. var color, i = 0, x, y;
  84824. var imageData = new Uint8Array(width * height * 4);
  84825. for (y = y_start; y !== y_end; y += y_step) {
  84826. for (x = x_start; x !== x_end; x += x_step, i++) {
  84827. color = image[i];
  84828. imageData[(x + width * y) * 4 + 0] = color;
  84829. imageData[(x + width * y) * 4 + 1] = color;
  84830. imageData[(x + width * y) * 4 + 2] = color;
  84831. imageData[(x + width * y) * 4 + 3] = 255;
  84832. }
  84833. }
  84834. return imageData;
  84835. };
  84836. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84837. var image = pixel_data;
  84838. var width = header.width, height = header.height;
  84839. var i = 0, x, y;
  84840. var imageData = new Uint8Array(width * height * 4);
  84841. for (y = y_start; y !== y_end; y += y_step) {
  84842. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84843. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84844. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84845. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84846. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84847. }
  84848. }
  84849. return imageData;
  84850. };
  84851. //private static _TYPE_NO_DATA = 0;
  84852. TGATools._TYPE_INDEXED = 1;
  84853. TGATools._TYPE_RGB = 2;
  84854. TGATools._TYPE_GREY = 3;
  84855. TGATools._TYPE_RLE_INDEXED = 9;
  84856. TGATools._TYPE_RLE_RGB = 10;
  84857. TGATools._TYPE_RLE_GREY = 11;
  84858. TGATools._ORIGIN_MASK = 0x30;
  84859. TGATools._ORIGIN_SHIFT = 0x04;
  84860. TGATools._ORIGIN_BL = 0x00;
  84861. TGATools._ORIGIN_BR = 0x01;
  84862. TGATools._ORIGIN_UL = 0x02;
  84863. TGATools._ORIGIN_UR = 0x03;
  84864. return TGATools;
  84865. }());
  84866. BABYLON.TGATools = TGATools;
  84867. })(BABYLON || (BABYLON = {}));
  84868. //# sourceMappingURL=babylon.tga.js.map
  84869. var BABYLON;
  84870. (function (BABYLON) {
  84871. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84872. // All values and structures referenced from:
  84873. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84874. var DDS_MAGIC = 0x20534444;
  84875. var
  84876. //DDSD_CAPS = 0x1,
  84877. //DDSD_HEIGHT = 0x2,
  84878. //DDSD_WIDTH = 0x4,
  84879. //DDSD_PITCH = 0x8,
  84880. //DDSD_PIXELFORMAT = 0x1000,
  84881. DDSD_MIPMAPCOUNT = 0x20000;
  84882. //DDSD_LINEARSIZE = 0x80000,
  84883. //DDSD_DEPTH = 0x800000;
  84884. // var DDSCAPS_COMPLEX = 0x8,
  84885. // DDSCAPS_MIPMAP = 0x400000,
  84886. // DDSCAPS_TEXTURE = 0x1000;
  84887. var DDSCAPS2_CUBEMAP = 0x200;
  84888. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84889. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84890. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84891. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84892. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84893. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84894. // DDSCAPS2_VOLUME = 0x200000;
  84895. var
  84896. //DDPF_ALPHAPIXELS = 0x1,
  84897. //DDPF_ALPHA = 0x2,
  84898. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84899. //DDPF_YUV = 0x200,
  84900. DDPF_LUMINANCE = 0x20000;
  84901. function FourCCToInt32(value) {
  84902. return value.charCodeAt(0) +
  84903. (value.charCodeAt(1) << 8) +
  84904. (value.charCodeAt(2) << 16) +
  84905. (value.charCodeAt(3) << 24);
  84906. }
  84907. function Int32ToFourCC(value) {
  84908. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84909. }
  84910. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84911. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84912. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84913. var FOURCC_DX10 = FourCCToInt32("DX10");
  84914. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84915. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84916. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84917. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84918. var headerLengthInt = 31; // The header length in 32 bit ints
  84919. // Offsets into the header array
  84920. var off_magic = 0;
  84921. var off_size = 1;
  84922. var off_flags = 2;
  84923. var off_height = 3;
  84924. var off_width = 4;
  84925. var off_mipmapCount = 7;
  84926. var off_pfFlags = 20;
  84927. var off_pfFourCC = 21;
  84928. var off_RGBbpp = 22;
  84929. var off_RMask = 23;
  84930. var off_GMask = 24;
  84931. var off_BMask = 25;
  84932. var off_AMask = 26;
  84933. // var off_caps1 = 27;
  84934. var off_caps2 = 28;
  84935. // var off_caps3 = 29;
  84936. // var off_caps4 = 30;
  84937. var off_dxgiFormat = 32;
  84938. ;
  84939. var DDSTools = /** @class */ (function () {
  84940. function DDSTools() {
  84941. }
  84942. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84943. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84944. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84945. var mipmapCount = 1;
  84946. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84947. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84948. }
  84949. var fourCC = header[off_pfFourCC];
  84950. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84951. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84952. switch (fourCC) {
  84953. case FOURCC_D3DFMT_R16G16B16A16F:
  84954. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84955. break;
  84956. case FOURCC_D3DFMT_R32G32B32A32F:
  84957. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84958. break;
  84959. case FOURCC_DX10:
  84960. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84961. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84962. break;
  84963. }
  84964. }
  84965. return {
  84966. width: header[off_width],
  84967. height: header[off_height],
  84968. mipmapCount: mipmapCount,
  84969. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84970. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84971. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84972. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84973. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84974. dxgiFormat: dxgiFormat,
  84975. textureType: textureType
  84976. };
  84977. };
  84978. DDSTools._ToHalfFloat = function (value) {
  84979. if (!DDSTools._FloatView) {
  84980. DDSTools._FloatView = new Float32Array(1);
  84981. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84982. }
  84983. DDSTools._FloatView[0] = value;
  84984. var x = DDSTools._Int32View[0];
  84985. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84986. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84987. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84988. /* If zero, or denormal, or exponent underflows too much for a denormal
  84989. * half, return signed zero. */
  84990. if (e < 103) {
  84991. return bits;
  84992. }
  84993. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84994. if (e > 142) {
  84995. bits |= 0x7c00;
  84996. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84997. * not Inf, so make sure we set one mantissa bit too. */
  84998. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84999. return bits;
  85000. }
  85001. /* If exponent underflows but not too much, return a denormal */
  85002. if (e < 113) {
  85003. m |= 0x0800;
  85004. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85005. * to 1, which is OK. */
  85006. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85007. return bits;
  85008. }
  85009. bits |= ((e - 112) << 10) | (m >> 1);
  85010. bits += m & 1;
  85011. return bits;
  85012. };
  85013. DDSTools._FromHalfFloat = function (value) {
  85014. var s = (value & 0x8000) >> 15;
  85015. var e = (value & 0x7C00) >> 10;
  85016. var f = value & 0x03FF;
  85017. if (e === 0) {
  85018. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85019. }
  85020. else if (e == 0x1F) {
  85021. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85022. }
  85023. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85024. };
  85025. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85026. var destArray = new Float32Array(dataLength);
  85027. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85028. var index = 0;
  85029. for (var y = 0; y < height; y++) {
  85030. for (var x = 0; x < width; x++) {
  85031. var srcPos = (x + y * width) * 4;
  85032. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85033. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85034. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85035. if (DDSTools.StoreLODInAlphaChannel) {
  85036. destArray[index + 3] = lod;
  85037. }
  85038. else {
  85039. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85040. }
  85041. index += 4;
  85042. }
  85043. }
  85044. return destArray;
  85045. };
  85046. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85047. if (DDSTools.StoreLODInAlphaChannel) {
  85048. var destArray = new Uint16Array(dataLength);
  85049. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85050. var index = 0;
  85051. for (var y = 0; y < height; y++) {
  85052. for (var x = 0; x < width; x++) {
  85053. var srcPos = (x + y * width) * 4;
  85054. destArray[index] = srcData[srcPos];
  85055. destArray[index + 1] = srcData[srcPos + 1];
  85056. destArray[index + 2] = srcData[srcPos + 2];
  85057. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85058. index += 4;
  85059. }
  85060. }
  85061. return destArray;
  85062. }
  85063. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85064. };
  85065. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85066. if (DDSTools.StoreLODInAlphaChannel) {
  85067. var destArray = new Float32Array(dataLength);
  85068. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85069. var index = 0;
  85070. for (var y = 0; y < height; y++) {
  85071. for (var x = 0; x < width; x++) {
  85072. var srcPos = (x + y * width) * 4;
  85073. destArray[index] = srcData[srcPos];
  85074. destArray[index + 1] = srcData[srcPos + 1];
  85075. destArray[index + 2] = srcData[srcPos + 2];
  85076. destArray[index + 3] = lod;
  85077. index += 4;
  85078. }
  85079. }
  85080. return destArray;
  85081. }
  85082. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85083. };
  85084. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85085. var destArray = new Uint8Array(dataLength);
  85086. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85087. var index = 0;
  85088. for (var y = 0; y < height; y++) {
  85089. for (var x = 0; x < width; x++) {
  85090. var srcPos = (x + y * width) * 4;
  85091. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85092. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85093. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85094. if (DDSTools.StoreLODInAlphaChannel) {
  85095. destArray[index + 3] = lod;
  85096. }
  85097. else {
  85098. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85099. }
  85100. index += 4;
  85101. }
  85102. }
  85103. return destArray;
  85104. };
  85105. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85106. var destArray = new Uint8Array(dataLength);
  85107. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85108. var index = 0;
  85109. for (var y = 0; y < height; y++) {
  85110. for (var x = 0; x < width; x++) {
  85111. var srcPos = (x + y * width) * 4;
  85112. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85113. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85114. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85115. if (DDSTools.StoreLODInAlphaChannel) {
  85116. destArray[index + 3] = lod;
  85117. }
  85118. else {
  85119. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85120. }
  85121. index += 4;
  85122. }
  85123. }
  85124. return destArray;
  85125. };
  85126. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85127. var byteArray = new Uint8Array(dataLength);
  85128. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85129. var index = 0;
  85130. for (var y = 0; y < height; y++) {
  85131. for (var x = 0; x < width; x++) {
  85132. var srcPos = (x + y * width) * 4;
  85133. byteArray[index] = srcData[srcPos + rOffset];
  85134. byteArray[index + 1] = srcData[srcPos + gOffset];
  85135. byteArray[index + 2] = srcData[srcPos + bOffset];
  85136. byteArray[index + 3] = srcData[srcPos + aOffset];
  85137. index += 4;
  85138. }
  85139. }
  85140. return byteArray;
  85141. };
  85142. DDSTools._ExtractLongWordOrder = function (value) {
  85143. if (value === 0 || value === 255 || value === -16777216) {
  85144. return 0;
  85145. }
  85146. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85147. };
  85148. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85149. var byteArray = new Uint8Array(dataLength);
  85150. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85151. var index = 0;
  85152. for (var y = 0; y < height; y++) {
  85153. for (var x = 0; x < width; x++) {
  85154. var srcPos = (x + y * width) * 3;
  85155. byteArray[index] = srcData[srcPos + rOffset];
  85156. byteArray[index + 1] = srcData[srcPos + gOffset];
  85157. byteArray[index + 2] = srcData[srcPos + bOffset];
  85158. index += 3;
  85159. }
  85160. }
  85161. return byteArray;
  85162. };
  85163. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85164. var byteArray = new Uint8Array(dataLength);
  85165. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85166. var index = 0;
  85167. for (var y = 0; y < height; y++) {
  85168. for (var x = 0; x < width; x++) {
  85169. var srcPos = (x + y * width);
  85170. byteArray[index] = srcData[srcPos];
  85171. index++;
  85172. }
  85173. }
  85174. return byteArray;
  85175. };
  85176. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85177. if (lodIndex === void 0) { lodIndex = -1; }
  85178. var sphericalPolynomialFaces = null;
  85179. if (info.sphericalPolynomial) {
  85180. sphericalPolynomialFaces = new Array();
  85181. }
  85182. var ext = engine.getCaps().s3tc;
  85183. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85184. var fourCC, width, height, dataLength = 0, dataOffset;
  85185. var byteArray, mipmapCount, mip;
  85186. var internalFormat = 0;
  85187. var format = 0;
  85188. var blockBytes = 1;
  85189. if (header[off_magic] !== DDS_MAGIC) {
  85190. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85191. return;
  85192. }
  85193. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85194. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85195. return;
  85196. }
  85197. if (info.isCompressed && !ext) {
  85198. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85199. return;
  85200. }
  85201. var bpp = header[off_RGBbpp];
  85202. dataOffset = header[off_size] + 4;
  85203. var computeFormats = false;
  85204. if (info.isFourCC) {
  85205. fourCC = header[off_pfFourCC];
  85206. switch (fourCC) {
  85207. case FOURCC_DXT1:
  85208. blockBytes = 8;
  85209. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85210. break;
  85211. case FOURCC_DXT3:
  85212. blockBytes = 16;
  85213. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85214. break;
  85215. case FOURCC_DXT5:
  85216. blockBytes = 16;
  85217. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85218. break;
  85219. case FOURCC_D3DFMT_R16G16B16A16F:
  85220. computeFormats = true;
  85221. break;
  85222. case FOURCC_D3DFMT_R32G32B32A32F:
  85223. computeFormats = true;
  85224. break;
  85225. case FOURCC_DX10:
  85226. // There is an additionnal header so dataOffset need to be changed
  85227. dataOffset += 5 * 4; // 5 uints
  85228. var supported = false;
  85229. switch (info.dxgiFormat) {
  85230. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85231. computeFormats = true;
  85232. supported = true;
  85233. break;
  85234. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85235. info.isRGB = true;
  85236. info.isFourCC = false;
  85237. bpp = 32;
  85238. supported = true;
  85239. break;
  85240. }
  85241. if (supported) {
  85242. break;
  85243. }
  85244. default:
  85245. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85246. return;
  85247. }
  85248. }
  85249. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85250. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85251. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85252. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85253. if (computeFormats) {
  85254. format = engine._getWebGLTextureType(info.textureType);
  85255. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85256. }
  85257. mipmapCount = 1;
  85258. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85259. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85260. }
  85261. for (var face = 0; face < faces; face++) {
  85262. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85263. width = header[off_width];
  85264. height = header[off_height];
  85265. for (mip = 0; mip < mipmapCount; ++mip) {
  85266. if (lodIndex === -1 || lodIndex === mip) {
  85267. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85268. var i = (lodIndex === -1) ? mip : 0;
  85269. if (!info.isCompressed && info.isFourCC) {
  85270. dataLength = width * height * 4;
  85271. var floatArray = null;
  85272. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85273. if (bpp === 128) {
  85274. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85275. if (sphericalPolynomialFaces && i == 0) {
  85276. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85277. }
  85278. }
  85279. else if (bpp === 64) {
  85280. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85281. if (sphericalPolynomialFaces && i == 0) {
  85282. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85283. }
  85284. }
  85285. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85286. format = engine._getWebGLTextureType(info.textureType);
  85287. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85288. }
  85289. else {
  85290. if (bpp === 128) {
  85291. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85292. if (sphericalPolynomialFaces && i == 0) {
  85293. sphericalPolynomialFaces.push(floatArray);
  85294. }
  85295. }
  85296. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85297. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85298. if (sphericalPolynomialFaces && i == 0) {
  85299. sphericalPolynomialFaces.push(floatArray);
  85300. }
  85301. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85302. format = engine._getWebGLTextureType(info.textureType);
  85303. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85304. }
  85305. else { // 64
  85306. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85307. if (sphericalPolynomialFaces && i == 0) {
  85308. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85309. }
  85310. }
  85311. }
  85312. if (floatArray) {
  85313. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85314. }
  85315. }
  85316. else if (info.isRGB) {
  85317. if (bpp === 24) {
  85318. dataLength = width * height * 3;
  85319. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85320. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85321. }
  85322. else { // 32
  85323. dataLength = width * height * 4;
  85324. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85325. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85326. }
  85327. }
  85328. else if (info.isLuminance) {
  85329. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85330. var unpaddedRowSize = width;
  85331. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85332. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85333. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85334. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85335. }
  85336. else {
  85337. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85338. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85339. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85340. }
  85341. }
  85342. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85343. width *= 0.5;
  85344. height *= 0.5;
  85345. width = Math.max(1.0, width);
  85346. height = Math.max(1.0, height);
  85347. }
  85348. if (currentFace !== undefined) {
  85349. // Loading a single face
  85350. break;
  85351. }
  85352. }
  85353. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85354. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85355. size: header[off_width],
  85356. right: sphericalPolynomialFaces[0],
  85357. left: sphericalPolynomialFaces[1],
  85358. up: sphericalPolynomialFaces[2],
  85359. down: sphericalPolynomialFaces[3],
  85360. front: sphericalPolynomialFaces[4],
  85361. back: sphericalPolynomialFaces[5],
  85362. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85363. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85364. gammaSpace: false,
  85365. });
  85366. }
  85367. else {
  85368. info.sphericalPolynomial = undefined;
  85369. }
  85370. };
  85371. DDSTools.StoreLODInAlphaChannel = false;
  85372. return DDSTools;
  85373. }());
  85374. BABYLON.DDSTools = DDSTools;
  85375. })(BABYLON || (BABYLON = {}));
  85376. //# sourceMappingURL=babylon.dds.js.map
  85377. var BABYLON;
  85378. (function (BABYLON) {
  85379. /**
  85380. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85381. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85382. */
  85383. var KhronosTextureContainer = /** @class */ (function () {
  85384. /**
  85385. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85386. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85387. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85388. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85389. */
  85390. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85391. this.arrayBuffer = arrayBuffer;
  85392. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85393. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85394. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85395. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85396. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85397. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85398. BABYLON.Tools.Error("texture missing KTX identifier");
  85399. return;
  85400. }
  85401. // load the reset of the header in native 32 bit int
  85402. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85403. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85404. var oppositeEndianess = header[0] === 0x01020304;
  85405. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85406. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85407. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85408. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85409. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85410. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85411. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85412. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85413. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85414. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85415. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85416. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85417. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85418. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85419. if (this.glType !== 0) {
  85420. BABYLON.Tools.Error("only compressed formats currently supported");
  85421. return;
  85422. }
  85423. else {
  85424. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85425. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85426. }
  85427. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85428. BABYLON.Tools.Error("only 2D textures currently supported");
  85429. return;
  85430. }
  85431. if (this.numberOfArrayElements !== 0) {
  85432. BABYLON.Tools.Error("texture arrays not currently supported");
  85433. return;
  85434. }
  85435. if (this.numberOfFaces !== facesExpected) {
  85436. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85437. return;
  85438. }
  85439. // we now have a completely validated file, so could use existence of loadType as success
  85440. // would need to make this more elaborate & adjust checks above to support more than one load type
  85441. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85442. }
  85443. // not as fast hardware based, but will probably never need to use
  85444. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85445. return ((val & 0xFF) << 24)
  85446. | ((val & 0xFF00) << 8)
  85447. | ((val >> 8) & 0xFF00)
  85448. | ((val >> 24) & 0xFF);
  85449. };
  85450. /**
  85451. * It is assumed that the texture has already been created & is currently bound
  85452. */
  85453. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85454. switch (this.loadType) {
  85455. case KhronosTextureContainer.COMPRESSED_2D:
  85456. this._upload2DCompressedLevels(gl, loadMipmaps);
  85457. break;
  85458. case KhronosTextureContainer.TEX_2D:
  85459. case KhronosTextureContainer.COMPRESSED_3D:
  85460. case KhronosTextureContainer.TEX_3D:
  85461. }
  85462. };
  85463. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85464. // initialize width & height for level 1
  85465. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85466. var width = this.pixelWidth;
  85467. var height = this.pixelHeight;
  85468. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85469. for (var level = 0; level < mipmapCount; level++) {
  85470. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85471. for (var face = 0; face < this.numberOfFaces; face++) {
  85472. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85473. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85474. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85475. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85476. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85477. }
  85478. width = Math.max(1.0, width * 0.5);
  85479. height = Math.max(1.0, height * 0.5);
  85480. }
  85481. };
  85482. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85483. // load types
  85484. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85485. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85486. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85487. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85488. return KhronosTextureContainer;
  85489. }());
  85490. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85491. })(BABYLON || (BABYLON = {}));
  85492. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85493. var BABYLON;
  85494. (function (BABYLON) {
  85495. var Debug;
  85496. (function (Debug) {
  85497. /**
  85498. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85499. */
  85500. var SkeletonViewer = /** @class */ (function () {
  85501. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85502. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85503. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85504. this.skeleton = skeleton;
  85505. this.mesh = mesh;
  85506. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85507. this.renderingGroupId = renderingGroupId;
  85508. this.color = BABYLON.Color3.White();
  85509. this._debugLines = new Array();
  85510. this._isEnabled = false;
  85511. this._scene = scene;
  85512. this.update();
  85513. this._renderFunction = this.update.bind(this);
  85514. }
  85515. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85516. get: function () {
  85517. return this._isEnabled;
  85518. },
  85519. set: function (value) {
  85520. if (this._isEnabled === value) {
  85521. return;
  85522. }
  85523. this._isEnabled = value;
  85524. if (value) {
  85525. this._scene.registerBeforeRender(this._renderFunction);
  85526. }
  85527. else {
  85528. this._scene.unregisterBeforeRender(this._renderFunction);
  85529. }
  85530. },
  85531. enumerable: true,
  85532. configurable: true
  85533. });
  85534. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85535. if (x === void 0) { x = 0; }
  85536. if (y === void 0) { y = 0; }
  85537. if (z === void 0) { z = 0; }
  85538. var tmat = BABYLON.Tmp.Matrix[0];
  85539. var parentBone = bone.getParent();
  85540. tmat.copyFrom(bone.getLocalMatrix());
  85541. if (x !== 0 || y !== 0 || z !== 0) {
  85542. var tmat2 = BABYLON.Tmp.Matrix[1];
  85543. BABYLON.Matrix.IdentityToRef(tmat2);
  85544. tmat2.m[12] = x;
  85545. tmat2.m[13] = y;
  85546. tmat2.m[14] = z;
  85547. tmat2.multiplyToRef(tmat, tmat);
  85548. }
  85549. if (parentBone) {
  85550. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85551. }
  85552. tmat.multiplyToRef(meshMat, tmat);
  85553. position.x = tmat.m[12];
  85554. position.y = tmat.m[13];
  85555. position.z = tmat.m[14];
  85556. };
  85557. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85558. var len = bones.length;
  85559. var meshPos = this.mesh.position;
  85560. for (var i = 0; i < len; i++) {
  85561. var bone = bones[i];
  85562. var points = this._debugLines[i];
  85563. if (!points) {
  85564. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85565. this._debugLines[i] = points;
  85566. }
  85567. this._getBonePosition(points[0], bone, meshMat);
  85568. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85569. points[0].subtractInPlace(meshPos);
  85570. points[1].subtractInPlace(meshPos);
  85571. }
  85572. };
  85573. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85574. var len = bones.length;
  85575. var boneNum = 0;
  85576. var meshPos = this.mesh.position;
  85577. for (var i = len - 1; i >= 0; i--) {
  85578. var childBone = bones[i];
  85579. var parentBone = childBone.getParent();
  85580. if (!parentBone) {
  85581. continue;
  85582. }
  85583. var points = this._debugLines[boneNum];
  85584. if (!points) {
  85585. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85586. this._debugLines[boneNum] = points;
  85587. }
  85588. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85589. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85590. points[0].subtractInPlace(meshPos);
  85591. points[1].subtractInPlace(meshPos);
  85592. boneNum++;
  85593. }
  85594. };
  85595. SkeletonViewer.prototype.update = function () {
  85596. if (this.autoUpdateBonesMatrices) {
  85597. this.skeleton.computeAbsoluteTransforms();
  85598. }
  85599. if (this.skeleton.bones[0].length === undefined) {
  85600. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85601. }
  85602. else {
  85603. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85604. }
  85605. if (!this._debugMesh) {
  85606. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85607. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85608. }
  85609. else {
  85610. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85611. }
  85612. this._debugMesh.position.copyFrom(this.mesh.position);
  85613. this._debugMesh.color = this.color;
  85614. };
  85615. SkeletonViewer.prototype.dispose = function () {
  85616. if (this._debugMesh) {
  85617. this.isEnabled = false;
  85618. this._debugMesh.dispose();
  85619. this._debugMesh = null;
  85620. }
  85621. };
  85622. return SkeletonViewer;
  85623. }());
  85624. Debug.SkeletonViewer = SkeletonViewer;
  85625. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85626. })(BABYLON || (BABYLON = {}));
  85627. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85628. /**
  85629. * Module Debug contains the (visual) components to debug a scene correctly
  85630. */
  85631. var BABYLON;
  85632. (function (BABYLON) {
  85633. var Debug;
  85634. (function (Debug) {
  85635. /**
  85636. * The Axes viewer will show 3 axes in a specific point in space
  85637. */
  85638. var AxesViewer = /** @class */ (function () {
  85639. function AxesViewer(scene, scaleLines) {
  85640. if (scaleLines === void 0) { scaleLines = 1; }
  85641. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85642. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85643. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85644. this.scaleLines = 1;
  85645. this.scaleLines = scaleLines;
  85646. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85647. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85648. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85649. this._xmesh.renderingGroupId = 2;
  85650. this._ymesh.renderingGroupId = 2;
  85651. this._zmesh.renderingGroupId = 2;
  85652. this._xmesh.material.checkReadyOnlyOnce = true;
  85653. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85654. this._ymesh.material.checkReadyOnlyOnce = true;
  85655. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85656. this._zmesh.material.checkReadyOnlyOnce = true;
  85657. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85658. this.scene = scene;
  85659. }
  85660. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85661. var scaleLines = this.scaleLines;
  85662. if (this._xmesh) {
  85663. this._xmesh.position.copyFrom(position);
  85664. }
  85665. if (this._ymesh) {
  85666. this._ymesh.position.copyFrom(position);
  85667. }
  85668. if (this._zmesh) {
  85669. this._zmesh.position.copyFrom(position);
  85670. }
  85671. var point2 = this._xline[1];
  85672. point2.x = xaxis.x * scaleLines;
  85673. point2.y = xaxis.y * scaleLines;
  85674. point2.z = xaxis.z * scaleLines;
  85675. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85676. point2 = this._yline[1];
  85677. point2.x = yaxis.x * scaleLines;
  85678. point2.y = yaxis.y * scaleLines;
  85679. point2.z = yaxis.z * scaleLines;
  85680. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85681. point2 = this._zline[1];
  85682. point2.x = zaxis.x * scaleLines;
  85683. point2.y = zaxis.y * scaleLines;
  85684. point2.z = zaxis.z * scaleLines;
  85685. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85686. };
  85687. AxesViewer.prototype.dispose = function () {
  85688. if (this._xmesh) {
  85689. this._xmesh.dispose();
  85690. }
  85691. if (this._ymesh) {
  85692. this._ymesh.dispose();
  85693. }
  85694. if (this._zmesh) {
  85695. this._zmesh.dispose();
  85696. }
  85697. this._xmesh = null;
  85698. this._ymesh = null;
  85699. this._zmesh = null;
  85700. this.scene = null;
  85701. };
  85702. return AxesViewer;
  85703. }());
  85704. Debug.AxesViewer = AxesViewer;
  85705. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85706. })(BABYLON || (BABYLON = {}));
  85707. //# sourceMappingURL=babylon.axesViewer.js.map
  85708. var BABYLON;
  85709. (function (BABYLON) {
  85710. var Debug;
  85711. (function (Debug) {
  85712. /**
  85713. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85714. */
  85715. var BoneAxesViewer = /** @class */ (function (_super) {
  85716. __extends(BoneAxesViewer, _super);
  85717. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85718. if (scaleLines === void 0) { scaleLines = 1; }
  85719. var _this = _super.call(this, scene, scaleLines) || this;
  85720. _this.pos = BABYLON.Vector3.Zero();
  85721. _this.xaxis = BABYLON.Vector3.Zero();
  85722. _this.yaxis = BABYLON.Vector3.Zero();
  85723. _this.zaxis = BABYLON.Vector3.Zero();
  85724. _this.mesh = mesh;
  85725. _this.bone = bone;
  85726. return _this;
  85727. }
  85728. BoneAxesViewer.prototype.update = function () {
  85729. if (!this.mesh || !this.bone) {
  85730. return;
  85731. }
  85732. var bone = this.bone;
  85733. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85734. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85735. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85736. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85737. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85738. };
  85739. BoneAxesViewer.prototype.dispose = function () {
  85740. if (this.mesh) {
  85741. this.mesh = null;
  85742. this.bone = null;
  85743. _super.prototype.dispose.call(this);
  85744. }
  85745. };
  85746. return BoneAxesViewer;
  85747. }(Debug.AxesViewer));
  85748. Debug.BoneAxesViewer = BoneAxesViewer;
  85749. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85750. })(BABYLON || (BABYLON = {}));
  85751. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85752. var BABYLON;
  85753. (function (BABYLON) {
  85754. var RayHelper = /** @class */ (function () {
  85755. function RayHelper(ray) {
  85756. this.ray = ray;
  85757. }
  85758. RayHelper.CreateAndShow = function (ray, scene, color) {
  85759. var helper = new RayHelper(ray);
  85760. helper.show(scene, color);
  85761. return helper;
  85762. };
  85763. RayHelper.prototype.show = function (scene, color) {
  85764. if (!this._renderFunction && this.ray) {
  85765. var ray = this.ray;
  85766. this._renderFunction = this._render.bind(this);
  85767. this._scene = scene;
  85768. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85769. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85770. if (this._renderFunction) {
  85771. this._scene.registerBeforeRender(this._renderFunction);
  85772. }
  85773. }
  85774. if (color && this._renderLine) {
  85775. this._renderLine.color.copyFrom(color);
  85776. }
  85777. };
  85778. RayHelper.prototype.hide = function () {
  85779. if (this._renderFunction && this._scene) {
  85780. this._scene.unregisterBeforeRender(this._renderFunction);
  85781. this._scene = null;
  85782. this._renderFunction = null;
  85783. if (this._renderLine) {
  85784. this._renderLine.dispose();
  85785. this._renderLine = null;
  85786. }
  85787. this._renderPoints = [];
  85788. }
  85789. };
  85790. RayHelper.prototype._render = function () {
  85791. var ray = this.ray;
  85792. if (!ray) {
  85793. return;
  85794. }
  85795. var point = this._renderPoints[1];
  85796. var len = Math.min(ray.length, 1000000);
  85797. point.copyFrom(ray.direction);
  85798. point.scaleInPlace(len);
  85799. point.addInPlace(ray.origin);
  85800. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85801. };
  85802. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85803. this._attachedToMesh = mesh;
  85804. var ray = this.ray;
  85805. if (!ray) {
  85806. return;
  85807. }
  85808. if (!ray.direction) {
  85809. ray.direction = BABYLON.Vector3.Zero();
  85810. }
  85811. if (!ray.origin) {
  85812. ray.origin = BABYLON.Vector3.Zero();
  85813. }
  85814. if (length) {
  85815. ray.length = length;
  85816. }
  85817. if (!meshSpaceOrigin) {
  85818. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85819. }
  85820. if (!meshSpaceDirection) {
  85821. // -1 so that this will work with Mesh.lookAt
  85822. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85823. }
  85824. if (!this._meshSpaceDirection) {
  85825. this._meshSpaceDirection = meshSpaceDirection.clone();
  85826. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85827. }
  85828. else {
  85829. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85830. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85831. }
  85832. if (!this._updateToMeshFunction) {
  85833. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85834. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85835. }
  85836. this._updateToMesh();
  85837. };
  85838. RayHelper.prototype.detachFromMesh = function () {
  85839. if (this._attachedToMesh) {
  85840. if (this._updateToMeshFunction) {
  85841. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85842. }
  85843. this._attachedToMesh = null;
  85844. this._updateToMeshFunction = null;
  85845. }
  85846. };
  85847. RayHelper.prototype._updateToMesh = function () {
  85848. var ray = this.ray;
  85849. if (!this._attachedToMesh || !ray) {
  85850. return;
  85851. }
  85852. if (this._attachedToMesh._isDisposed) {
  85853. this.detachFromMesh();
  85854. return;
  85855. }
  85856. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85857. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85858. };
  85859. RayHelper.prototype.dispose = function () {
  85860. this.hide();
  85861. this.detachFromMesh();
  85862. this.ray = null;
  85863. };
  85864. return RayHelper;
  85865. }());
  85866. BABYLON.RayHelper = RayHelper;
  85867. })(BABYLON || (BABYLON = {}));
  85868. //# sourceMappingURL=babylon.rayHelper.js.map
  85869. var BABYLON;
  85870. (function (BABYLON) {
  85871. // load the inspector using require, if not present in the global namespace.
  85872. var DebugLayer = /** @class */ (function () {
  85873. function DebugLayer(scene) {
  85874. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85875. this._scene = scene;
  85876. // load inspector using require, if it doesn't exist on the global namespace.
  85877. }
  85878. /** Creates the inspector window. */
  85879. DebugLayer.prototype._createInspector = function (config) {
  85880. if (config === void 0) { config = {}; }
  85881. var popup = config.popup || false;
  85882. var initialTab = config.initialTab || 0;
  85883. var parentElement = config.parentElement || null;
  85884. if (!this._inspector) {
  85885. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85886. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85887. } // else nothing to do,; instance is already existing
  85888. };
  85889. DebugLayer.prototype.isVisible = function () {
  85890. if (!this._inspector) {
  85891. return false;
  85892. }
  85893. return true;
  85894. };
  85895. DebugLayer.prototype.hide = function () {
  85896. if (this._inspector) {
  85897. try {
  85898. this._inspector.dispose();
  85899. }
  85900. catch (e) {
  85901. // If the inspector has been removed directly from the inspector tool
  85902. }
  85903. this._inspector = null;
  85904. }
  85905. };
  85906. DebugLayer.prototype.show = function (config) {
  85907. if (config === void 0) { config = {}; }
  85908. if (typeof this.BJSINSPECTOR == 'undefined') {
  85909. // Load inspector and add it to the DOM
  85910. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85911. }
  85912. else {
  85913. // Otherwise creates the inspector
  85914. this._createInspector(config);
  85915. }
  85916. };
  85917. /**
  85918. * Gets the active tab
  85919. * @return the index of the active tab or -1 if the inspector is hidden
  85920. */
  85921. DebugLayer.prototype.getActiveTab = function () {
  85922. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  85923. };
  85924. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85925. return DebugLayer;
  85926. }());
  85927. BABYLON.DebugLayer = DebugLayer;
  85928. })(BABYLON || (BABYLON = {}));
  85929. //# sourceMappingURL=babylon.debugLayer.js.map
  85930. var BABYLON;
  85931. (function (BABYLON) {
  85932. var Debug;
  85933. (function (Debug) {
  85934. /**
  85935. * Used to show the physics impostor around the specific mesh.
  85936. */
  85937. var PhysicsViewer = /** @class */ (function () {
  85938. function PhysicsViewer(scene) {
  85939. this._impostors = [];
  85940. this._meshes = [];
  85941. this._numMeshes = 0;
  85942. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85943. var physicEngine = this._scene.getPhysicsEngine();
  85944. if (physicEngine) {
  85945. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85946. }
  85947. }
  85948. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85949. var plugin = this._physicsEnginePlugin;
  85950. for (var i = 0; i < this._numMeshes; i++) {
  85951. var impostor = this._impostors[i];
  85952. if (!impostor) {
  85953. continue;
  85954. }
  85955. if (impostor.isDisposed) {
  85956. this.hideImpostor(this._impostors[i--]);
  85957. }
  85958. else {
  85959. var mesh = this._meshes[i];
  85960. if (mesh && plugin) {
  85961. plugin.syncMeshWithImpostor(mesh, impostor);
  85962. }
  85963. }
  85964. }
  85965. };
  85966. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85967. if (!this._scene) {
  85968. return;
  85969. }
  85970. for (var i = 0; i < this._numMeshes; i++) {
  85971. if (this._impostors[i] == impostor) {
  85972. return;
  85973. }
  85974. }
  85975. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85976. if (debugMesh) {
  85977. this._impostors[this._numMeshes] = impostor;
  85978. this._meshes[this._numMeshes] = debugMesh;
  85979. if (this._numMeshes === 0) {
  85980. this._renderFunction = this._updateDebugMeshes.bind(this);
  85981. this._scene.registerBeforeRender(this._renderFunction);
  85982. }
  85983. this._numMeshes++;
  85984. }
  85985. };
  85986. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85987. if (!impostor || !this._scene) {
  85988. return;
  85989. }
  85990. var removed = false;
  85991. for (var i = 0; i < this._numMeshes; i++) {
  85992. if (this._impostors[i] == impostor) {
  85993. var mesh = this._meshes[i];
  85994. if (!mesh) {
  85995. continue;
  85996. }
  85997. this._scene.removeMesh(mesh);
  85998. mesh.dispose();
  85999. this._numMeshes--;
  86000. if (this._numMeshes > 0) {
  86001. this._meshes[i] = this._meshes[this._numMeshes];
  86002. this._impostors[i] = this._impostors[this._numMeshes];
  86003. this._meshes[this._numMeshes] = null;
  86004. this._impostors[this._numMeshes] = null;
  86005. }
  86006. else {
  86007. this._meshes[0] = null;
  86008. this._impostors[0] = null;
  86009. }
  86010. removed = true;
  86011. break;
  86012. }
  86013. }
  86014. if (removed && this._numMeshes === 0) {
  86015. this._scene.unregisterBeforeRender(this._renderFunction);
  86016. }
  86017. };
  86018. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86019. if (!this._debugMaterial) {
  86020. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86021. this._debugMaterial.wireframe = true;
  86022. }
  86023. return this._debugMaterial;
  86024. };
  86025. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86026. if (!this._debugBoxMesh) {
  86027. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86028. this._debugBoxMesh.renderingGroupId = 1;
  86029. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86030. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86031. scene.removeMesh(this._debugBoxMesh);
  86032. }
  86033. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86034. };
  86035. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86036. if (!this._debugSphereMesh) {
  86037. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86038. this._debugSphereMesh.renderingGroupId = 1;
  86039. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86040. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86041. scene.removeMesh(this._debugSphereMesh);
  86042. }
  86043. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86044. };
  86045. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86046. var mesh = null;
  86047. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86048. mesh = this._getDebugBoxMesh(scene);
  86049. impostor.getBoxSizeToRef(mesh.scaling);
  86050. }
  86051. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86052. mesh = this._getDebugSphereMesh(scene);
  86053. var radius = impostor.getRadius();
  86054. mesh.scaling.x = radius * 2;
  86055. mesh.scaling.y = radius * 2;
  86056. mesh.scaling.z = radius * 2;
  86057. }
  86058. return mesh;
  86059. };
  86060. PhysicsViewer.prototype.dispose = function () {
  86061. for (var i = 0; i < this._numMeshes; i++) {
  86062. this.hideImpostor(this._impostors[i]);
  86063. }
  86064. if (this._debugBoxMesh) {
  86065. this._debugBoxMesh.dispose();
  86066. }
  86067. if (this._debugSphereMesh) {
  86068. this._debugSphereMesh.dispose();
  86069. }
  86070. if (this._debugMaterial) {
  86071. this._debugMaterial.dispose();
  86072. }
  86073. this._impostors.length = 0;
  86074. this._scene = null;
  86075. this._physicsEnginePlugin = null;
  86076. };
  86077. return PhysicsViewer;
  86078. }());
  86079. Debug.PhysicsViewer = PhysicsViewer;
  86080. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86081. })(BABYLON || (BABYLON = {}));
  86082. //# sourceMappingURL=babylon.physicsViewer.js.map
  86083. var BABYLON;
  86084. (function (BABYLON) {
  86085. var BoundingBoxRenderer = /** @class */ (function () {
  86086. function BoundingBoxRenderer(scene) {
  86087. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86088. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86089. this.showBackLines = true;
  86090. this.renderList = new BABYLON.SmartArray(32);
  86091. this._vertexBuffers = {};
  86092. this._scene = scene;
  86093. }
  86094. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86095. if (this._colorShader) {
  86096. return;
  86097. }
  86098. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86099. attributes: [BABYLON.VertexBuffer.PositionKind],
  86100. uniforms: ["world", "viewProjection", "color"]
  86101. });
  86102. var engine = this._scene.getEngine();
  86103. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86104. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86105. this._createIndexBuffer();
  86106. };
  86107. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86108. var engine = this._scene.getEngine();
  86109. 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]);
  86110. };
  86111. BoundingBoxRenderer.prototype._rebuild = function () {
  86112. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86113. if (vb) {
  86114. vb._rebuild();
  86115. }
  86116. this._createIndexBuffer();
  86117. };
  86118. BoundingBoxRenderer.prototype.reset = function () {
  86119. this.renderList.reset();
  86120. };
  86121. BoundingBoxRenderer.prototype.render = function () {
  86122. if (this.renderList.length === 0) {
  86123. return;
  86124. }
  86125. this._prepareRessources();
  86126. if (!this._colorShader.isReady()) {
  86127. return;
  86128. }
  86129. var engine = this._scene.getEngine();
  86130. engine.setDepthWrite(false);
  86131. this._colorShader._preBind();
  86132. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86133. var boundingBox = this.renderList.data[boundingBoxIndex];
  86134. var min = boundingBox.minimum;
  86135. var max = boundingBox.maximum;
  86136. var diff = max.subtract(min);
  86137. var median = min.add(diff.scale(0.5));
  86138. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86139. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86140. .multiply(boundingBox.getWorldMatrix());
  86141. // VBOs
  86142. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86143. if (this.showBackLines) {
  86144. // Back
  86145. engine.setDepthFunctionToGreaterOrEqual();
  86146. this._scene.resetCachedMaterial();
  86147. this._colorShader.setColor4("color", this.backColor.toColor4());
  86148. this._colorShader.bind(worldMatrix);
  86149. // Draw order
  86150. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86151. }
  86152. // Front
  86153. engine.setDepthFunctionToLess();
  86154. this._scene.resetCachedMaterial();
  86155. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86156. this._colorShader.bind(worldMatrix);
  86157. // Draw order
  86158. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86159. }
  86160. this._colorShader.unbind();
  86161. engine.setDepthFunctionToLessOrEqual();
  86162. engine.setDepthWrite(true);
  86163. };
  86164. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86165. this._prepareRessources();
  86166. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86167. return;
  86168. }
  86169. var engine = this._scene.getEngine();
  86170. engine.setDepthWrite(false);
  86171. engine.setColorWrite(false);
  86172. this._colorShader._preBind();
  86173. var boundingBox = mesh._boundingInfo.boundingBox;
  86174. var min = boundingBox.minimum;
  86175. var max = boundingBox.maximum;
  86176. var diff = max.subtract(min);
  86177. var median = min.add(diff.scale(0.5));
  86178. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86179. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86180. .multiply(boundingBox.getWorldMatrix());
  86181. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86182. engine.setDepthFunctionToLess();
  86183. this._scene.resetCachedMaterial();
  86184. this._colorShader.bind(worldMatrix);
  86185. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86186. this._colorShader.unbind();
  86187. engine.setDepthFunctionToLessOrEqual();
  86188. engine.setDepthWrite(true);
  86189. engine.setColorWrite(true);
  86190. };
  86191. BoundingBoxRenderer.prototype.dispose = function () {
  86192. if (!this._colorShader) {
  86193. return;
  86194. }
  86195. this.renderList.dispose();
  86196. this._colorShader.dispose();
  86197. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86198. if (buffer) {
  86199. buffer.dispose();
  86200. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86201. }
  86202. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86203. };
  86204. return BoundingBoxRenderer;
  86205. }());
  86206. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86207. })(BABYLON || (BABYLON = {}));
  86208. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86209. var BABYLON;
  86210. (function (BABYLON) {
  86211. /**
  86212. * Renders a layer on top of an existing scene
  86213. */
  86214. var UtilityLayerRenderer = /** @class */ (function () {
  86215. /**
  86216. * Instantiates a UtilityLayerRenderer
  86217. * @param originalScene the original scene that will be rendered on top of
  86218. */
  86219. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86220. var _this = this;
  86221. this.originalScene = originalScene;
  86222. /**
  86223. * If the utility layer should automatically be rendered on top of existing scene
  86224. */
  86225. this.shouldRender = true;
  86226. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86227. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86228. originalScene.getEngine().scenes.pop();
  86229. // Render directly on top of existing scene without clearing
  86230. this.utilityLayerScene.autoClear = false;
  86231. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  86232. if (_this.shouldRender) {
  86233. _this.render();
  86234. }
  86235. });
  86236. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  86237. _this.dispose();
  86238. });
  86239. }
  86240. /**
  86241. * Renders the utility layers scene on top of the original scene
  86242. */
  86243. UtilityLayerRenderer.prototype.render = function () {
  86244. this._updateCamera();
  86245. this.utilityLayerScene.render(false);
  86246. };
  86247. /**
  86248. * Disposes of the renderer
  86249. */
  86250. UtilityLayerRenderer.prototype.dispose = function () {
  86251. if (this._afterRenderObserver) {
  86252. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  86253. }
  86254. if (this._sceneDisposeObserver) {
  86255. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86256. }
  86257. this.utilityLayerScene.dispose();
  86258. };
  86259. UtilityLayerRenderer.prototype._updateCamera = function () {
  86260. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  86261. };
  86262. return UtilityLayerRenderer;
  86263. }());
  86264. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  86265. })(BABYLON || (BABYLON = {}));
  86266. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  86267. var BABYLON;
  86268. (function (BABYLON) {
  86269. /**
  86270. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  86271. */
  86272. var Gizmo = /** @class */ (function () {
  86273. /**
  86274. * Creates a gizmo
  86275. * @param gizmoLayer The utility layer the gizmo will be added to
  86276. */
  86277. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  86278. var _this = this;
  86279. this.gizmoLayer = gizmoLayer;
  86280. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  86281. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  86282. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  86283. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 5;
  86284. _this._rootMesh.scaling.set(dist, dist, dist);
  86285. }
  86286. if (_this.attachedMesh) {
  86287. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  86288. }
  86289. });
  86290. }
  86291. /**
  86292. * Disposes of the gizmo
  86293. */
  86294. Gizmo.prototype.dispose = function () {
  86295. this._rootMesh.dispose();
  86296. if (this._beforeRenderObserver) {
  86297. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  86298. }
  86299. };
  86300. return Gizmo;
  86301. }());
  86302. BABYLON.Gizmo = Gizmo;
  86303. })(BABYLON || (BABYLON = {}));
  86304. //# sourceMappingURL=babylon.gizmo.js.map
  86305. var BABYLON;
  86306. (function (BABYLON) {
  86307. /**
  86308. * Single axis drag gizmo
  86309. */
  86310. var AxisDragGizmo = /** @class */ (function (_super) {
  86311. __extends(AxisDragGizmo, _super);
  86312. /**
  86313. * Creates an AxisDragGizmo
  86314. * @param gizmoLayer The utility layer the gizmo will be added to
  86315. * @param dragAxis The axis which the gizmo will be able to drag on
  86316. * @param color The color of the gizmo
  86317. */
  86318. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  86319. var _this = _super.call(this, gizmoLayer) || this;
  86320. // Create Material
  86321. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86322. coloredMaterial.disableLighting = true;
  86323. coloredMaterial.emissiveColor = color;
  86324. // Build mesh on root node
  86325. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86326. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86327. _this._rootMesh.addChild(arrowMesh);
  86328. _this._rootMesh.addChild(arrowTail);
  86329. // Position arrow pointing in its drag axis
  86330. arrowMesh.scaling.scaleInPlace(0.1);
  86331. arrowMesh.material = coloredMaterial;
  86332. arrowMesh.rotation.x = Math.PI / 2;
  86333. arrowMesh.position.z += 0.3;
  86334. arrowTail.rotation.x = Math.PI / 2;
  86335. arrowTail.material = coloredMaterial;
  86336. arrowTail.position.z += 0.2;
  86337. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  86338. // Add drag behavior to handle events when the gizmo is dragged
  86339. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis, pointerObservableScene: gizmoLayer.originalScene });
  86340. _this._dragBehavior.moveAttached = false;
  86341. _this._rootMesh.addBehavior(_this._dragBehavior);
  86342. _this._dragBehavior.onDragObservable.add(function (event) {
  86343. if (_this.attachedMesh) {
  86344. _this.attachedMesh.position.addInPlace(event.delta);
  86345. }
  86346. });
  86347. return _this;
  86348. }
  86349. /**
  86350. * Disposes of the gizmo
  86351. */
  86352. AxisDragGizmo.prototype.dispose = function () {
  86353. this._dragBehavior.detach();
  86354. _super.prototype.dispose.call(this);
  86355. };
  86356. return AxisDragGizmo;
  86357. }(BABYLON.Gizmo));
  86358. BABYLON.AxisDragGizmo = AxisDragGizmo;
  86359. })(BABYLON || (BABYLON = {}));
  86360. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  86361. var BABYLON;
  86362. (function (BABYLON) {
  86363. /**
  86364. * Gizmo that enables dragging a mesh along 3 axis
  86365. */
  86366. var PositionGizmo = /** @class */ (function (_super) {
  86367. __extends(PositionGizmo, _super);
  86368. /**
  86369. * Creates a PositionGizmo
  86370. * @param gizmoLayer The utility layer the gizmo will be added to
  86371. */
  86372. function PositionGizmo(gizmoLayer) {
  86373. var _this = _super.call(this, gizmoLayer) || this;
  86374. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86375. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86376. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86377. return _this;
  86378. }
  86379. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  86380. set: function (mesh) {
  86381. this._xDrag.attachedMesh = mesh;
  86382. this._yDrag.attachedMesh = mesh;
  86383. this._zDrag.attachedMesh = mesh;
  86384. },
  86385. enumerable: true,
  86386. configurable: true
  86387. });
  86388. /**
  86389. * Disposes of the gizmo
  86390. */
  86391. PositionGizmo.prototype.dispose = function () {
  86392. this._xDrag.dispose();
  86393. this._yDrag.dispose();
  86394. this._zDrag.dispose();
  86395. };
  86396. return PositionGizmo;
  86397. }(BABYLON.Gizmo));
  86398. BABYLON.PositionGizmo = PositionGizmo;
  86399. })(BABYLON || (BABYLON = {}));
  86400. //# sourceMappingURL=babylon.positionGizmo.js.map
  86401. var BABYLON;
  86402. (function (BABYLON) {
  86403. /**
  86404. * Defines a target to use with MorphTargetManager
  86405. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86406. */
  86407. var MorphTarget = /** @class */ (function () {
  86408. /**
  86409. * Creates a new MorphTarget
  86410. * @param name defines the name of the target
  86411. * @param influence defines the influence to use
  86412. */
  86413. function MorphTarget(
  86414. /** defines the name of the target */
  86415. name, influence, scene) {
  86416. if (influence === void 0) { influence = 0; }
  86417. if (scene === void 0) { scene = null; }
  86418. this.name = name;
  86419. /**
  86420. * Gets or sets the list of animations
  86421. */
  86422. this.animations = new Array();
  86423. this._positions = null;
  86424. this._normals = null;
  86425. this._tangents = null;
  86426. /**
  86427. * Observable raised when the influence changes
  86428. */
  86429. this.onInfluenceChanged = new BABYLON.Observable();
  86430. this._animationPropertiesOverride = null;
  86431. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86432. this.influence = influence;
  86433. }
  86434. Object.defineProperty(MorphTarget.prototype, "influence", {
  86435. /**
  86436. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  86437. */
  86438. get: function () {
  86439. return this._influence;
  86440. },
  86441. set: function (influence) {
  86442. if (this._influence === influence) {
  86443. return;
  86444. }
  86445. var previous = this._influence;
  86446. this._influence = influence;
  86447. if (this.onInfluenceChanged.hasObservers) {
  86448. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  86449. }
  86450. },
  86451. enumerable: true,
  86452. configurable: true
  86453. });
  86454. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  86455. /**
  86456. * Gets or sets the animation properties override
  86457. */
  86458. get: function () {
  86459. if (!this._animationPropertiesOverride && this._scene) {
  86460. return this._scene.animationPropertiesOverride;
  86461. }
  86462. return this._animationPropertiesOverride;
  86463. },
  86464. set: function (value) {
  86465. this._animationPropertiesOverride = value;
  86466. },
  86467. enumerable: true,
  86468. configurable: true
  86469. });
  86470. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  86471. /**
  86472. * Gets a boolean defining if the target contains position data
  86473. */
  86474. get: function () {
  86475. return !!this._positions;
  86476. },
  86477. enumerable: true,
  86478. configurable: true
  86479. });
  86480. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  86481. /**
  86482. * Gets a boolean defining if the target contains normal data
  86483. */
  86484. get: function () {
  86485. return !!this._normals;
  86486. },
  86487. enumerable: true,
  86488. configurable: true
  86489. });
  86490. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  86491. /**
  86492. * Gets a boolean defining if the target contains tangent data
  86493. */
  86494. get: function () {
  86495. return !!this._tangents;
  86496. },
  86497. enumerable: true,
  86498. configurable: true
  86499. });
  86500. /**
  86501. * Affects position data to this target
  86502. * @param data defines the position data to use
  86503. */
  86504. MorphTarget.prototype.setPositions = function (data) {
  86505. this._positions = data;
  86506. };
  86507. /**
  86508. * Gets the position data stored in this target
  86509. * @returns a FloatArray containing the position data (or null if not present)
  86510. */
  86511. MorphTarget.prototype.getPositions = function () {
  86512. return this._positions;
  86513. };
  86514. /**
  86515. * Affects normal data to this target
  86516. * @param data defines the normal data to use
  86517. */
  86518. MorphTarget.prototype.setNormals = function (data) {
  86519. this._normals = data;
  86520. };
  86521. /**
  86522. * Gets the normal data stored in this target
  86523. * @returns a FloatArray containing the normal data (or null if not present)
  86524. */
  86525. MorphTarget.prototype.getNormals = function () {
  86526. return this._normals;
  86527. };
  86528. /**
  86529. * Affects tangent data to this target
  86530. * @param data defines the tangent data to use
  86531. */
  86532. MorphTarget.prototype.setTangents = function (data) {
  86533. this._tangents = data;
  86534. };
  86535. /**
  86536. * Gets the tangent data stored in this target
  86537. * @returns a FloatArray containing the tangent data (or null if not present)
  86538. */
  86539. MorphTarget.prototype.getTangents = function () {
  86540. return this._tangents;
  86541. };
  86542. /**
  86543. * Serializes the current target into a Serialization object
  86544. * @returns the serialized object
  86545. */
  86546. MorphTarget.prototype.serialize = function () {
  86547. var serializationObject = {};
  86548. serializationObject.name = this.name;
  86549. serializationObject.influence = this.influence;
  86550. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  86551. if (this.hasNormals) {
  86552. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  86553. }
  86554. if (this.hasTangents) {
  86555. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  86556. }
  86557. // Animations
  86558. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  86559. return serializationObject;
  86560. };
  86561. // Statics
  86562. /**
  86563. * Creates a new target from serialized data
  86564. * @param serializationObject defines the serialized data to use
  86565. * @returns a new MorphTarget
  86566. */
  86567. MorphTarget.Parse = function (serializationObject) {
  86568. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  86569. result.setPositions(serializationObject.positions);
  86570. if (serializationObject.normals) {
  86571. result.setNormals(serializationObject.normals);
  86572. }
  86573. if (serializationObject.tangents) {
  86574. result.setTangents(serializationObject.tangents);
  86575. }
  86576. // Animations
  86577. if (serializationObject.animations) {
  86578. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  86579. var parsedAnimation = serializationObject.animations[animationIndex];
  86580. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  86581. }
  86582. }
  86583. return result;
  86584. };
  86585. /**
  86586. * Creates a MorphTarget from mesh data
  86587. * @param mesh defines the source mesh
  86588. * @param name defines the name to use for the new target
  86589. * @param influence defines the influence to attach to the target
  86590. * @returns a new MorphTarget
  86591. */
  86592. MorphTarget.FromMesh = function (mesh, name, influence) {
  86593. if (!name) {
  86594. name = mesh.name;
  86595. }
  86596. var result = new MorphTarget(name, influence, mesh.getScene());
  86597. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86599. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86600. }
  86601. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86602. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86603. }
  86604. return result;
  86605. };
  86606. return MorphTarget;
  86607. }());
  86608. BABYLON.MorphTarget = MorphTarget;
  86609. })(BABYLON || (BABYLON = {}));
  86610. //# sourceMappingURL=babylon.morphTarget.js.map
  86611. var BABYLON;
  86612. (function (BABYLON) {
  86613. /**
  86614. * This class is used to deform meshes using morphing between different targets
  86615. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86616. */
  86617. var MorphTargetManager = /** @class */ (function () {
  86618. /**
  86619. * Creates a new MorphTargetManager
  86620. * @param scene defines the current scene
  86621. */
  86622. function MorphTargetManager(scene) {
  86623. if (scene === void 0) { scene = null; }
  86624. this._targets = new Array();
  86625. this._targetObservable = new Array();
  86626. this._activeTargets = new BABYLON.SmartArray(16);
  86627. this._supportsNormals = false;
  86628. this._supportsTangents = false;
  86629. this._vertexCount = 0;
  86630. this._uniqueId = 0;
  86631. this._tempInfluences = new Array();
  86632. if (!scene) {
  86633. scene = BABYLON.Engine.LastCreatedScene;
  86634. }
  86635. this._scene = scene;
  86636. if (this._scene) {
  86637. this._scene.morphTargetManagers.push(this);
  86638. this._uniqueId = this._scene.getUniqueId();
  86639. }
  86640. }
  86641. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86642. /**
  86643. * Gets the unique ID of this manager
  86644. */
  86645. get: function () {
  86646. return this._uniqueId;
  86647. },
  86648. enumerable: true,
  86649. configurable: true
  86650. });
  86651. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86652. /**
  86653. * Gets the number of vertices handled by this manager
  86654. */
  86655. get: function () {
  86656. return this._vertexCount;
  86657. },
  86658. enumerable: true,
  86659. configurable: true
  86660. });
  86661. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86662. /**
  86663. * Gets a boolean indicating if this manager supports morphing of normals
  86664. */
  86665. get: function () {
  86666. return this._supportsNormals;
  86667. },
  86668. enumerable: true,
  86669. configurable: true
  86670. });
  86671. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86672. /**
  86673. * Gets a boolean indicating if this manager supports morphing of tangents
  86674. */
  86675. get: function () {
  86676. return this._supportsTangents;
  86677. },
  86678. enumerable: true,
  86679. configurable: true
  86680. });
  86681. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86682. /**
  86683. * Gets the number of targets stored in this manager
  86684. */
  86685. get: function () {
  86686. return this._targets.length;
  86687. },
  86688. enumerable: true,
  86689. configurable: true
  86690. });
  86691. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86692. /**
  86693. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86694. */
  86695. get: function () {
  86696. return this._activeTargets.length;
  86697. },
  86698. enumerable: true,
  86699. configurable: true
  86700. });
  86701. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86702. /**
  86703. * Gets the list of influences (one per target)
  86704. */
  86705. get: function () {
  86706. return this._influences;
  86707. },
  86708. enumerable: true,
  86709. configurable: true
  86710. });
  86711. /**
  86712. * Gets the active target at specified index. An active target is a target with an influence > 0
  86713. * @param index defines the index to check
  86714. * @returns the requested target
  86715. */
  86716. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86717. return this._activeTargets.data[index];
  86718. };
  86719. /**
  86720. * Gets the target at specified index
  86721. * @param index defines the index to check
  86722. * @returns the requested target
  86723. */
  86724. MorphTargetManager.prototype.getTarget = function (index) {
  86725. return this._targets[index];
  86726. };
  86727. /**
  86728. * Add a new target to this manager
  86729. * @param target defines the target to add
  86730. */
  86731. MorphTargetManager.prototype.addTarget = function (target) {
  86732. var _this = this;
  86733. this._targets.push(target);
  86734. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86735. _this._syncActiveTargets(needUpdate);
  86736. }));
  86737. this._syncActiveTargets(true);
  86738. };
  86739. /**
  86740. * Removes a target from the manager
  86741. * @param target defines the target to remove
  86742. */
  86743. MorphTargetManager.prototype.removeTarget = function (target) {
  86744. var index = this._targets.indexOf(target);
  86745. if (index >= 0) {
  86746. this._targets.splice(index, 1);
  86747. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86748. this._syncActiveTargets(true);
  86749. }
  86750. };
  86751. /**
  86752. * Serializes the current manager into a Serialization object
  86753. * @returns the serialized object
  86754. */
  86755. MorphTargetManager.prototype.serialize = function () {
  86756. var serializationObject = {};
  86757. serializationObject.id = this.uniqueId;
  86758. serializationObject.targets = [];
  86759. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86760. var target = _a[_i];
  86761. serializationObject.targets.push(target.serialize());
  86762. }
  86763. return serializationObject;
  86764. };
  86765. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86766. var influenceCount = 0;
  86767. this._activeTargets.reset();
  86768. this._supportsNormals = true;
  86769. this._supportsTangents = true;
  86770. this._vertexCount = 0;
  86771. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86772. var target = _a[_i];
  86773. this._activeTargets.push(target);
  86774. this._tempInfluences[influenceCount++] = target.influence;
  86775. var positions = target.getPositions();
  86776. if (positions) {
  86777. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86778. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86779. var vertexCount = positions.length / 3;
  86780. if (this._vertexCount === 0) {
  86781. this._vertexCount = vertexCount;
  86782. }
  86783. else if (this._vertexCount !== vertexCount) {
  86784. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86785. return;
  86786. }
  86787. }
  86788. }
  86789. if (!this._influences || this._influences.length !== influenceCount) {
  86790. this._influences = new Float32Array(influenceCount);
  86791. }
  86792. for (var index = 0; index < influenceCount; index++) {
  86793. this._influences[index] = this._tempInfluences[index];
  86794. }
  86795. if (needUpdate) {
  86796. this.synchronize();
  86797. }
  86798. };
  86799. /**
  86800. * Syncrhonize the targets with all the meshes using this morph target manager
  86801. */
  86802. MorphTargetManager.prototype.synchronize = function () {
  86803. if (!this._scene) {
  86804. return;
  86805. }
  86806. // Flag meshes as dirty to resync with the active targets
  86807. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86808. var mesh = _a[_i];
  86809. if (mesh.morphTargetManager === this) {
  86810. mesh._syncGeometryWithMorphTargetManager();
  86811. }
  86812. }
  86813. };
  86814. // Statics
  86815. /**
  86816. * Creates a new MorphTargetManager from serialized data
  86817. * @param serializationObject defines the serialized data
  86818. * @param scene defines the hosting scene
  86819. * @returns the new MorphTargetManager
  86820. */
  86821. MorphTargetManager.Parse = function (serializationObject, scene) {
  86822. var result = new MorphTargetManager(scene);
  86823. result._uniqueId = serializationObject.id;
  86824. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86825. var targetData = _a[_i];
  86826. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86827. }
  86828. return result;
  86829. };
  86830. return MorphTargetManager;
  86831. }());
  86832. BABYLON.MorphTargetManager = MorphTargetManager;
  86833. })(BABYLON || (BABYLON = {}));
  86834. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86835. var BABYLON;
  86836. (function (BABYLON) {
  86837. var Octree = /** @class */ (function () {
  86838. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86839. if (maxDepth === void 0) { maxDepth = 2; }
  86840. this.maxDepth = maxDepth;
  86841. this.dynamicContent = new Array();
  86842. this._maxBlockCapacity = maxBlockCapacity || 64;
  86843. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86844. this._creationFunc = creationFunc;
  86845. }
  86846. // Methods
  86847. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86848. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86849. };
  86850. Octree.prototype.addMesh = function (entry) {
  86851. for (var index = 0; index < this.blocks.length; index++) {
  86852. var block = this.blocks[index];
  86853. block.addEntry(entry);
  86854. }
  86855. };
  86856. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86857. this._selectionContent.reset();
  86858. for (var index = 0; index < this.blocks.length; index++) {
  86859. var block = this.blocks[index];
  86860. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86861. }
  86862. if (allowDuplicate) {
  86863. this._selectionContent.concat(this.dynamicContent);
  86864. }
  86865. else {
  86866. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86867. }
  86868. return this._selectionContent;
  86869. };
  86870. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86871. this._selectionContent.reset();
  86872. for (var index = 0; index < this.blocks.length; index++) {
  86873. var block = this.blocks[index];
  86874. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86875. }
  86876. if (allowDuplicate) {
  86877. this._selectionContent.concat(this.dynamicContent);
  86878. }
  86879. else {
  86880. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86881. }
  86882. return this._selectionContent;
  86883. };
  86884. Octree.prototype.intersectsRay = function (ray) {
  86885. this._selectionContent.reset();
  86886. for (var index = 0; index < this.blocks.length; index++) {
  86887. var block = this.blocks[index];
  86888. block.intersectsRay(ray, this._selectionContent);
  86889. }
  86890. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86891. return this._selectionContent;
  86892. };
  86893. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86894. target.blocks = new Array();
  86895. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86896. // Segmenting space
  86897. for (var x = 0; x < 2; x++) {
  86898. for (var y = 0; y < 2; y++) {
  86899. for (var z = 0; z < 2; z++) {
  86900. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86901. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86902. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86903. block.addEntries(entries);
  86904. target.blocks.push(block);
  86905. }
  86906. }
  86907. }
  86908. };
  86909. Octree.CreationFuncForMeshes = function (entry, block) {
  86910. var boundingInfo = entry.getBoundingInfo();
  86911. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86912. block.entries.push(entry);
  86913. }
  86914. };
  86915. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86916. var boundingInfo = entry.getBoundingInfo();
  86917. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86918. block.entries.push(entry);
  86919. }
  86920. };
  86921. return Octree;
  86922. }());
  86923. BABYLON.Octree = Octree;
  86924. })(BABYLON || (BABYLON = {}));
  86925. //# sourceMappingURL=babylon.octree.js.map
  86926. var BABYLON;
  86927. (function (BABYLON) {
  86928. var OctreeBlock = /** @class */ (function () {
  86929. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86930. this.entries = new Array();
  86931. this._boundingVectors = new Array();
  86932. this._capacity = capacity;
  86933. this._depth = depth;
  86934. this._maxDepth = maxDepth;
  86935. this._creationFunc = creationFunc;
  86936. this._minPoint = minPoint;
  86937. this._maxPoint = maxPoint;
  86938. this._boundingVectors.push(minPoint.clone());
  86939. this._boundingVectors.push(maxPoint.clone());
  86940. this._boundingVectors.push(minPoint.clone());
  86941. this._boundingVectors[2].x = maxPoint.x;
  86942. this._boundingVectors.push(minPoint.clone());
  86943. this._boundingVectors[3].y = maxPoint.y;
  86944. this._boundingVectors.push(minPoint.clone());
  86945. this._boundingVectors[4].z = maxPoint.z;
  86946. this._boundingVectors.push(maxPoint.clone());
  86947. this._boundingVectors[5].z = minPoint.z;
  86948. this._boundingVectors.push(maxPoint.clone());
  86949. this._boundingVectors[6].x = minPoint.x;
  86950. this._boundingVectors.push(maxPoint.clone());
  86951. this._boundingVectors[7].y = minPoint.y;
  86952. }
  86953. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86954. // Property
  86955. get: function () {
  86956. return this._capacity;
  86957. },
  86958. enumerable: true,
  86959. configurable: true
  86960. });
  86961. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86962. get: function () {
  86963. return this._minPoint;
  86964. },
  86965. enumerable: true,
  86966. configurable: true
  86967. });
  86968. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86969. get: function () {
  86970. return this._maxPoint;
  86971. },
  86972. enumerable: true,
  86973. configurable: true
  86974. });
  86975. // Methods
  86976. OctreeBlock.prototype.addEntry = function (entry) {
  86977. if (this.blocks) {
  86978. for (var index = 0; index < this.blocks.length; index++) {
  86979. var block = this.blocks[index];
  86980. block.addEntry(entry);
  86981. }
  86982. return;
  86983. }
  86984. this._creationFunc(entry, this);
  86985. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86986. this.createInnerBlocks();
  86987. }
  86988. };
  86989. OctreeBlock.prototype.addEntries = function (entries) {
  86990. for (var index = 0; index < entries.length; index++) {
  86991. var mesh = entries[index];
  86992. this.addEntry(mesh);
  86993. }
  86994. };
  86995. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86996. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86997. if (this.blocks) {
  86998. for (var index = 0; index < this.blocks.length; index++) {
  86999. var block = this.blocks[index];
  87000. block.select(frustumPlanes, selection, allowDuplicate);
  87001. }
  87002. return;
  87003. }
  87004. if (allowDuplicate) {
  87005. selection.concat(this.entries);
  87006. }
  87007. else {
  87008. selection.concatWithNoDuplicate(this.entries);
  87009. }
  87010. }
  87011. };
  87012. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  87013. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  87014. if (this.blocks) {
  87015. for (var index = 0; index < this.blocks.length; index++) {
  87016. var block = this.blocks[index];
  87017. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  87018. }
  87019. return;
  87020. }
  87021. if (allowDuplicate) {
  87022. selection.concat(this.entries);
  87023. }
  87024. else {
  87025. selection.concatWithNoDuplicate(this.entries);
  87026. }
  87027. }
  87028. };
  87029. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  87030. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  87031. if (this.blocks) {
  87032. for (var index = 0; index < this.blocks.length; index++) {
  87033. var block = this.blocks[index];
  87034. block.intersectsRay(ray, selection);
  87035. }
  87036. return;
  87037. }
  87038. selection.concatWithNoDuplicate(this.entries);
  87039. }
  87040. };
  87041. OctreeBlock.prototype.createInnerBlocks = function () {
  87042. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  87043. };
  87044. return OctreeBlock;
  87045. }());
  87046. BABYLON.OctreeBlock = OctreeBlock;
  87047. })(BABYLON || (BABYLON = {}));
  87048. //# sourceMappingURL=babylon.octreeBlock.js.map
  87049. var BABYLON;
  87050. (function (BABYLON) {
  87051. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  87052. __extends(VRDistortionCorrectionPostProcess, _super);
  87053. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  87054. var _this = _super.call(this, name, "vrDistortionCorrection", [
  87055. 'LensCenter',
  87056. 'Scale',
  87057. 'ScaleIn',
  87058. 'HmdWarpParam'
  87059. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  87060. _this._isRightEye = isRightEye;
  87061. _this._distortionFactors = vrMetrics.distortionK;
  87062. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  87063. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  87064. _this.adaptScaleToCurrentViewport = true;
  87065. _this.onSizeChangedObservable.add(function () {
  87066. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  87067. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  87068. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  87069. });
  87070. _this.onApplyObservable.add(function (effect) {
  87071. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  87072. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  87073. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  87074. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  87075. });
  87076. return _this;
  87077. }
  87078. return VRDistortionCorrectionPostProcess;
  87079. }(BABYLON.PostProcess));
  87080. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  87081. })(BABYLON || (BABYLON = {}));
  87082. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  87083. var BABYLON;
  87084. (function (BABYLON) {
  87085. /**
  87086. * Postprocess used to generate anaglyphic rendering
  87087. */
  87088. var AnaglyphPostProcess = /** @class */ (function (_super) {
  87089. __extends(AnaglyphPostProcess, _super);
  87090. /**
  87091. * Creates a new AnaglyphPostProcess
  87092. * @param name defines postprocess name
  87093. * @param options defines creation options or target ratio scale
  87094. * @param rigCameras defines cameras using this postprocess
  87095. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  87096. * @param engine defines hosting engine
  87097. * @param reusable defines if the postprocess will be reused multiple times per frame
  87098. */
  87099. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  87100. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  87101. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87102. _this.onApplyObservable.add(function (effect) {
  87103. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  87104. });
  87105. return _this;
  87106. }
  87107. return AnaglyphPostProcess;
  87108. }(BABYLON.PostProcess));
  87109. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  87110. })(BABYLON || (BABYLON = {}));
  87111. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  87112. var BABYLON;
  87113. (function (BABYLON) {
  87114. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  87115. __extends(StereoscopicInterlacePostProcess, _super);
  87116. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  87117. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  87118. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87119. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87120. _this.onSizeChangedObservable.add(function () {
  87121. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87122. });
  87123. _this.onApplyObservable.add(function (effect) {
  87124. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  87125. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  87126. });
  87127. return _this;
  87128. }
  87129. return StereoscopicInterlacePostProcess;
  87130. }(BABYLON.PostProcess));
  87131. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  87132. })(BABYLON || (BABYLON = {}));
  87133. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  87134. var BABYLON;
  87135. (function (BABYLON) {
  87136. /**
  87137. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  87138. * Screen rotation is taken into account.
  87139. */
  87140. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  87141. function FreeCameraDeviceOrientationInput() {
  87142. var _this = this;
  87143. this._screenOrientationAngle = 0;
  87144. this._screenQuaternion = new BABYLON.Quaternion();
  87145. this._alpha = 0;
  87146. this._beta = 0;
  87147. this._gamma = 0;
  87148. this._orientationChanged = function () {
  87149. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  87150. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  87151. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  87152. };
  87153. this._deviceOrientation = function (evt) {
  87154. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  87155. _this._beta = evt.beta !== null ? evt.beta : 0;
  87156. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  87157. };
  87158. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  87159. this._orientationChanged();
  87160. }
  87161. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  87162. get: function () {
  87163. return this._camera;
  87164. },
  87165. set: function (camera) {
  87166. this._camera = camera;
  87167. if (this._camera != null && !this._camera.rotationQuaternion) {
  87168. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  87169. }
  87170. },
  87171. enumerable: true,
  87172. configurable: true
  87173. });
  87174. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87175. window.addEventListener("orientationchange", this._orientationChanged);
  87176. window.addEventListener("deviceorientation", this._deviceOrientation);
  87177. //In certain cases, the attach control is called AFTER orientation was changed,
  87178. //So this is needed.
  87179. this._orientationChanged();
  87180. };
  87181. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  87182. window.removeEventListener("orientationchange", this._orientationChanged);
  87183. window.removeEventListener("deviceorientation", this._deviceOrientation);
  87184. };
  87185. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  87186. //if no device orientation provided, don't update the rotation.
  87187. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  87188. if (!this._alpha)
  87189. return;
  87190. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  87191. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  87192. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  87193. //Mirror on XY Plane
  87194. this._camera.rotationQuaternion.z *= -1;
  87195. this._camera.rotationQuaternion.w *= -1;
  87196. };
  87197. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  87198. return "FreeCameraDeviceOrientationInput";
  87199. };
  87200. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  87201. return "deviceOrientation";
  87202. };
  87203. return FreeCameraDeviceOrientationInput;
  87204. }());
  87205. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  87206. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  87207. })(BABYLON || (BABYLON = {}));
  87208. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  87209. var BABYLON;
  87210. (function (BABYLON) {
  87211. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  87212. function ArcRotateCameraVRDeviceOrientationInput() {
  87213. this.alphaCorrection = 1;
  87214. this.betaCorrection = 1;
  87215. this.gammaCorrection = 1;
  87216. this._alpha = 0;
  87217. this._gamma = 0;
  87218. this._dirty = false;
  87219. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  87220. }
  87221. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87222. this.camera.attachControl(element, noPreventDefault);
  87223. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  87224. };
  87225. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  87226. if (evt.alpha !== null) {
  87227. this._alpha = +evt.alpha | 0;
  87228. }
  87229. if (evt.gamma !== null) {
  87230. this._gamma = +evt.gamma | 0;
  87231. }
  87232. this._dirty = true;
  87233. };
  87234. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  87235. if (this._dirty) {
  87236. this._dirty = false;
  87237. if (this._gamma < 0) {
  87238. this._gamma = 180 + this._gamma;
  87239. }
  87240. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  87241. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  87242. }
  87243. };
  87244. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  87245. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  87246. };
  87247. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  87248. return "ArcRotateCameraVRDeviceOrientationInput";
  87249. };
  87250. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  87251. return "VRDeviceOrientation";
  87252. };
  87253. return ArcRotateCameraVRDeviceOrientationInput;
  87254. }());
  87255. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  87256. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  87257. })(BABYLON || (BABYLON = {}));
  87258. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  87259. var BABYLON;
  87260. (function (BABYLON) {
  87261. var VRCameraMetrics = /** @class */ (function () {
  87262. function VRCameraMetrics() {
  87263. this.compensateDistortion = true;
  87264. }
  87265. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  87266. get: function () {
  87267. return this.hResolution / (2 * this.vResolution);
  87268. },
  87269. enumerable: true,
  87270. configurable: true
  87271. });
  87272. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  87273. get: function () {
  87274. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  87275. },
  87276. enumerable: true,
  87277. configurable: true
  87278. });
  87279. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  87280. get: function () {
  87281. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87282. var h = (4 * meters) / this.hScreenSize;
  87283. return BABYLON.Matrix.Translation(h, 0, 0);
  87284. },
  87285. enumerable: true,
  87286. configurable: true
  87287. });
  87288. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  87289. get: function () {
  87290. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87291. var h = (4 * meters) / this.hScreenSize;
  87292. return BABYLON.Matrix.Translation(-h, 0, 0);
  87293. },
  87294. enumerable: true,
  87295. configurable: true
  87296. });
  87297. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  87298. get: function () {
  87299. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  87300. },
  87301. enumerable: true,
  87302. configurable: true
  87303. });
  87304. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  87305. get: function () {
  87306. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  87307. },
  87308. enumerable: true,
  87309. configurable: true
  87310. });
  87311. VRCameraMetrics.GetDefault = function () {
  87312. var result = new VRCameraMetrics();
  87313. result.hResolution = 1280;
  87314. result.vResolution = 800;
  87315. result.hScreenSize = 0.149759993;
  87316. result.vScreenSize = 0.0935999975;
  87317. result.vScreenCenter = 0.0467999987;
  87318. result.eyeToScreenDistance = 0.0410000011;
  87319. result.lensSeparationDistance = 0.0635000020;
  87320. result.interpupillaryDistance = 0.0640000030;
  87321. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  87322. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  87323. result.postProcessScaleFactor = 1.714605507808412;
  87324. result.lensCenterOffset = 0.151976421;
  87325. return result;
  87326. };
  87327. return VRCameraMetrics;
  87328. }());
  87329. BABYLON.VRCameraMetrics = VRCameraMetrics;
  87330. })(BABYLON || (BABYLON = {}));
  87331. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  87332. var BABYLON;
  87333. (function (BABYLON) {
  87334. /**
  87335. * This represents a WebVR camera.
  87336. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  87337. * @example http://doc.babylonjs.com/how_to/webvr_camera
  87338. */
  87339. var WebVRFreeCamera = /** @class */ (function (_super) {
  87340. __extends(WebVRFreeCamera, _super);
  87341. /**
  87342. * Instantiates a WebVRFreeCamera.
  87343. * @param name The name of the WebVRFreeCamera
  87344. * @param position The starting anchor position for the camera
  87345. * @param scene The scene the camera belongs to
  87346. * @param webVROptions a set of customizable options for the webVRCamera
  87347. */
  87348. function WebVRFreeCamera(name, position, scene, webVROptions) {
  87349. if (webVROptions === void 0) { webVROptions = {}; }
  87350. var _this = _super.call(this, name, position, scene) || this;
  87351. _this.webVROptions = webVROptions;
  87352. /**
  87353. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  87354. */
  87355. _this._vrDevice = null;
  87356. /**
  87357. * The rawPose of the vrDevice.
  87358. */
  87359. _this.rawPose = null;
  87360. _this._specsVersion = "1.1";
  87361. _this._attached = false;
  87362. _this._descendants = [];
  87363. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  87364. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  87365. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  87366. _this._standingMatrix = null;
  87367. /**
  87368. * Represents device position in babylon space.
  87369. */
  87370. _this.devicePosition = BABYLON.Vector3.Zero();
  87371. /**
  87372. * Represents device rotation in babylon space.
  87373. */
  87374. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  87375. /**
  87376. * The scale of the device to be used when translating from device space to babylon space.
  87377. */
  87378. _this.deviceScaleFactor = 1;
  87379. _this._deviceToWorld = BABYLON.Matrix.Identity();
  87380. _this._worldToDevice = BABYLON.Matrix.Identity();
  87381. /**
  87382. * References to the webVR controllers for the vrDevice.
  87383. */
  87384. _this.controllers = [];
  87385. /**
  87386. * Emits an event when a controller is attached.
  87387. */
  87388. _this.onControllersAttachedObservable = new BABYLON.Observable();
  87389. /**
  87390. * Emits an event when a controller's mesh has been loaded;
  87391. */
  87392. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87393. /**
  87394. * If the rig cameras be used as parent instead of this camera.
  87395. */
  87396. _this.rigParenting = true;
  87397. _this._defaultHeight = undefined;
  87398. _this._workingVector = BABYLON.Vector3.Zero();
  87399. _this._oneVector = BABYLON.Vector3.One();
  87400. _this._workingMatrix = BABYLON.Matrix.Identity();
  87401. _this._cache.position = BABYLON.Vector3.Zero();
  87402. if (webVROptions.defaultHeight) {
  87403. _this._defaultHeight = webVROptions.defaultHeight;
  87404. _this.position.y = _this._defaultHeight;
  87405. }
  87406. _this.minZ = 0.1;
  87407. //legacy support - the compensation boolean was removed.
  87408. if (arguments.length === 5) {
  87409. _this.webVROptions = arguments[4];
  87410. }
  87411. // default webVR options
  87412. if (_this.webVROptions.trackPosition == undefined) {
  87413. _this.webVROptions.trackPosition = true;
  87414. }
  87415. if (_this.webVROptions.controllerMeshes == undefined) {
  87416. _this.webVROptions.controllerMeshes = true;
  87417. }
  87418. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  87419. _this.webVROptions.defaultLightingOnControllers = true;
  87420. }
  87421. _this.rotationQuaternion = new BABYLON.Quaternion();
  87422. if (_this.webVROptions && _this.webVROptions.positionScale) {
  87423. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  87424. }
  87425. //enable VR
  87426. var engine = _this.getEngine();
  87427. _this._onVREnabled = function (success) { if (success) {
  87428. _this.initControllers();
  87429. } };
  87430. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  87431. engine.initWebVR().add(function (event) {
  87432. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  87433. return;
  87434. }
  87435. _this._vrDevice = event.vrDisplay;
  87436. //reset the rig parameters.
  87437. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  87438. if (_this._attached) {
  87439. _this.getEngine().enableVR();
  87440. }
  87441. });
  87442. if (typeof (VRFrameData) !== "undefined")
  87443. _this._frameData = new VRFrameData();
  87444. /**
  87445. * The idea behind the following lines:
  87446. * objects that have the camera as parent should actually have the rig cameras as a parent.
  87447. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  87448. * the second will not show it correctly.
  87449. *
  87450. * To solve this - each object that has the camera as parent will be added to a protected array.
  87451. * When the rig camera renders, it will take this array and set all of those to be its children.
  87452. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  87453. * Amazing!
  87454. */
  87455. scene.onBeforeCameraRenderObservable.add(function (camera) {
  87456. if (camera.parent === _this && _this.rigParenting) {
  87457. _this._descendants = _this.getDescendants(true, function (n) {
  87458. // don't take the cameras or the controllers!
  87459. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  87460. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  87461. return !isController && !isRigCamera;
  87462. });
  87463. _this._descendants.forEach(function (node) {
  87464. node.parent = camera;
  87465. });
  87466. }
  87467. });
  87468. scene.onAfterCameraRenderObservable.add(function (camera) {
  87469. if (camera.parent === _this && _this.rigParenting) {
  87470. _this._descendants.forEach(function (node) {
  87471. node.parent = _this;
  87472. });
  87473. }
  87474. });
  87475. return _this;
  87476. }
  87477. /**
  87478. * Gets the device distance from the ground in meters.
  87479. * @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.
  87480. */
  87481. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  87482. if (this._standingMatrix) {
  87483. // Add standing matrix offset to get real offset from ground in room
  87484. this._standingMatrix.getTranslationToRef(this._workingVector);
  87485. return this._deviceRoomPosition.y + this._workingVector.y;
  87486. }
  87487. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  87488. return this._defaultHeight || 0;
  87489. };
  87490. /**
  87491. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87492. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  87493. */
  87494. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  87495. var _this = this;
  87496. if (callback === void 0) { callback = function (bool) { }; }
  87497. // Use standing matrix if available
  87498. this.getEngine().initWebVRAsync().then(function (result) {
  87499. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  87500. callback(false);
  87501. }
  87502. else {
  87503. _this._standingMatrix = new BABYLON.Matrix();
  87504. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  87505. if (!_this.getScene().useRightHandedSystem) {
  87506. [2, 6, 8, 9, 14].forEach(function (num) {
  87507. if (_this._standingMatrix) {
  87508. _this._standingMatrix.m[num] *= -1;
  87509. }
  87510. });
  87511. }
  87512. callback(true);
  87513. }
  87514. });
  87515. };
  87516. /**
  87517. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87518. * @returns A promise with a boolean set to if the standing matrix is supported.
  87519. */
  87520. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  87521. var _this = this;
  87522. return new Promise(function (res, rej) {
  87523. _this.useStandingMatrix(function (supported) {
  87524. res(supported);
  87525. });
  87526. });
  87527. };
  87528. /**
  87529. * Disposes the camera
  87530. */
  87531. WebVRFreeCamera.prototype.dispose = function () {
  87532. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  87533. _super.prototype.dispose.call(this);
  87534. };
  87535. /**
  87536. * Gets a vrController by name.
  87537. * @param name The name of the controller to retreive
  87538. * @returns the controller matching the name specified or null if not found
  87539. */
  87540. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  87541. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  87542. var gp = _a[_i];
  87543. if (gp.hand === name) {
  87544. return gp;
  87545. }
  87546. }
  87547. return null;
  87548. };
  87549. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  87550. /**
  87551. * The controller corrisponding to the users left hand.
  87552. */
  87553. get: function () {
  87554. if (!this._leftController) {
  87555. this._leftController = this.getControllerByName("left");
  87556. }
  87557. return this._leftController;
  87558. },
  87559. enumerable: true,
  87560. configurable: true
  87561. });
  87562. ;
  87563. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  87564. /**
  87565. * The controller corrisponding to the users right hand.
  87566. */
  87567. get: function () {
  87568. if (!this._rightController) {
  87569. this._rightController = this.getControllerByName("right");
  87570. }
  87571. return this._rightController;
  87572. },
  87573. enumerable: true,
  87574. configurable: true
  87575. });
  87576. ;
  87577. /**
  87578. * Casts a ray forward from the vrCamera's gaze.
  87579. * @param length Length of the ray (default: 100)
  87580. * @returns the ray corrisponding to the gaze
  87581. */
  87582. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  87583. if (length === void 0) { length = 100; }
  87584. if (this.leftCamera) {
  87585. // Use left eye to avoid computation to compute center on every call
  87586. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  87587. }
  87588. else {
  87589. return _super.prototype.getForwardRay.call(this, length);
  87590. }
  87591. };
  87592. /**
  87593. * Updates the camera based on device's frame data
  87594. */
  87595. WebVRFreeCamera.prototype._checkInputs = function () {
  87596. if (this._vrDevice && this._vrDevice.isPresenting) {
  87597. this._vrDevice.getFrameData(this._frameData);
  87598. this.updateFromDevice(this._frameData.pose);
  87599. }
  87600. _super.prototype._checkInputs.call(this);
  87601. };
  87602. /**
  87603. * Updates the poseControlled values based on the input device pose.
  87604. * @param poseData Pose coming from the device
  87605. */
  87606. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87607. if (poseData && poseData.orientation) {
  87608. this.rawPose = poseData;
  87609. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87610. if (this.getScene().useRightHandedSystem) {
  87611. this._deviceRoomRotationQuaternion.z *= -1;
  87612. this._deviceRoomRotationQuaternion.w *= -1;
  87613. }
  87614. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87615. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87616. if (this.getScene().useRightHandedSystem) {
  87617. this._deviceRoomPosition.z *= -1;
  87618. }
  87619. }
  87620. }
  87621. };
  87622. /**
  87623. * WebVR's attach control will start broadcasting frames to the device.
  87624. * Note that in certain browsers (chrome for example) this function must be called
  87625. * within a user-interaction callback. Example:
  87626. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87627. *
  87628. * @param element html element to attach the vrDevice to
  87629. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87630. */
  87631. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87632. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87633. this._attached = true;
  87634. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87635. if (this._vrDevice) {
  87636. this.getEngine().enableVR();
  87637. }
  87638. };
  87639. /**
  87640. * Detaches the camera from the html element and disables VR
  87641. *
  87642. * @param element html element to detach from
  87643. */
  87644. WebVRFreeCamera.prototype.detachControl = function (element) {
  87645. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87646. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87647. _super.prototype.detachControl.call(this, element);
  87648. this._attached = false;
  87649. this.getEngine().disableVR();
  87650. };
  87651. /**
  87652. * @returns the name of this class
  87653. */
  87654. WebVRFreeCamera.prototype.getClassName = function () {
  87655. return "WebVRFreeCamera";
  87656. };
  87657. /**
  87658. * Calls resetPose on the vrDisplay
  87659. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87660. */
  87661. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87662. //uses the vrDisplay's "resetPose()".
  87663. //pitch and roll won't be affected.
  87664. this._vrDevice.resetPose();
  87665. };
  87666. /**
  87667. * Updates the rig cameras (left and right eye)
  87668. */
  87669. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87670. var camLeft = this._rigCameras[0];
  87671. var camRight = this._rigCameras[1];
  87672. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87673. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87674. camLeft.position.copyFrom(this._deviceRoomPosition);
  87675. camRight.position.copyFrom(this._deviceRoomPosition);
  87676. };
  87677. /**
  87678. * Updates the cached values of the camera
  87679. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87680. */
  87681. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87682. var _this = this;
  87683. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87684. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87685. if (!this.updateCacheCalled) {
  87686. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87687. this.updateCacheCalled = true;
  87688. this.update();
  87689. }
  87690. // Set working vector to the device position in room space rotated by the new rotation
  87691. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87692. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87693. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87694. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87695. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87696. // Add translation from anchor position
  87697. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87698. this._workingVector.addInPlace(this.position);
  87699. this._workingVector.subtractInPlace(this._cache.position);
  87700. this._deviceToWorld.setTranslation(this._workingVector);
  87701. // Set an inverted matrix to be used when updating the camera
  87702. this._deviceToWorld.invertToRef(this._worldToDevice);
  87703. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87704. this.controllers.forEach(function (controller) {
  87705. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87706. controller.update();
  87707. });
  87708. }
  87709. if (!ignoreParentClass) {
  87710. _super.prototype._updateCache.call(this);
  87711. }
  87712. this.updateCacheCalled = false;
  87713. };
  87714. /**
  87715. * Updates the current device position and rotation in the babylon world
  87716. */
  87717. WebVRFreeCamera.prototype.update = function () {
  87718. // Get current device position in babylon world
  87719. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87720. // Get current device rotation in babylon world
  87721. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87722. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87723. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87724. _super.prototype.update.call(this);
  87725. };
  87726. /**
  87727. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87728. * @returns an identity matrix
  87729. */
  87730. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87731. return BABYLON.Matrix.Identity();
  87732. };
  87733. /**
  87734. * This function is called by the two RIG cameras.
  87735. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87736. */
  87737. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87738. var _this = this;
  87739. // Update the parent camera prior to using a child camera to avoid desynchronization
  87740. var parentCamera = this._cameraRigParams["parentCamera"];
  87741. parentCamera._updateCache();
  87742. //WebVR 1.1
  87743. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87744. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87745. if (!this.getScene().useRightHandedSystem) {
  87746. [2, 6, 8, 9, 14].forEach(function (num) {
  87747. _this._webvrViewMatrix.m[num] *= -1;
  87748. });
  87749. }
  87750. // update the camera rotation matrix
  87751. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87752. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87753. // Computing target and final matrix
  87754. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87755. // should the view matrix be updated with scale and position offset?
  87756. if (parentCamera.deviceScaleFactor !== 1) {
  87757. this._webvrViewMatrix.invert();
  87758. // scale the position, if set
  87759. if (parentCamera.deviceScaleFactor) {
  87760. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87761. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87762. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87763. }
  87764. this._webvrViewMatrix.invert();
  87765. }
  87766. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87767. // Compute global position
  87768. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87769. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87770. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87771. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87772. this._markSyncedWithParent();
  87773. return this._webvrViewMatrix;
  87774. };
  87775. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87776. var _this = this;
  87777. var parentCamera = this.parent;
  87778. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87779. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87780. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87781. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87782. //babylon compatible matrix
  87783. if (!this.getScene().useRightHandedSystem) {
  87784. [8, 9, 10, 11].forEach(function (num) {
  87785. _this._projectionMatrix.m[num] *= -1;
  87786. });
  87787. }
  87788. return this._projectionMatrix;
  87789. };
  87790. /**
  87791. * Initializes the controllers and their meshes
  87792. */
  87793. WebVRFreeCamera.prototype.initControllers = function () {
  87794. var _this = this;
  87795. this.controllers = [];
  87796. var manager = this.getScene().gamepadManager;
  87797. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87798. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87799. var webVrController = gamepad;
  87800. if (webVrController.defaultModel) {
  87801. webVrController.defaultModel.setEnabled(false);
  87802. }
  87803. if (webVrController.hand === "right") {
  87804. _this._rightController = null;
  87805. }
  87806. if (webVrController.hand === "left") {
  87807. _this._leftController = null;
  87808. }
  87809. var controllerIndex = _this.controllers.indexOf(webVrController);
  87810. if (controllerIndex !== -1) {
  87811. _this.controllers.splice(controllerIndex, 1);
  87812. }
  87813. }
  87814. });
  87815. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87816. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87817. var webVrController_1 = gamepad;
  87818. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87819. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87820. if (_this.webVROptions.controllerMeshes) {
  87821. if (webVrController_1.defaultModel) {
  87822. webVrController_1.defaultModel.setEnabled(true);
  87823. }
  87824. else {
  87825. // Load the meshes
  87826. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87827. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87828. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87829. if (_this.webVROptions.defaultLightingOnControllers) {
  87830. if (!_this._lightOnControllers) {
  87831. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87832. }
  87833. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87834. var children = mesh.getChildren();
  87835. if (children.length !== 0) {
  87836. children.forEach(function (mesh) {
  87837. light.includedOnlyMeshes.push(mesh);
  87838. activateLightOnSubMeshes_1(mesh, light);
  87839. });
  87840. }
  87841. };
  87842. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87843. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87844. }
  87845. });
  87846. }
  87847. }
  87848. webVrController_1.attachToPoseControlledCamera(_this);
  87849. // since this is async - sanity check. Is the controller already stored?
  87850. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87851. //add to the controllers array
  87852. _this.controllers.push(webVrController_1);
  87853. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87854. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87855. // So we're overriding setting left & right manually to be sure
  87856. var firstViveWandDetected = false;
  87857. for (var i = 0; i < _this.controllers.length; i++) {
  87858. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87859. if (!firstViveWandDetected) {
  87860. firstViveWandDetected = true;
  87861. _this.controllers[i].hand = "left";
  87862. }
  87863. else {
  87864. _this.controllers[i].hand = "right";
  87865. }
  87866. }
  87867. }
  87868. //did we find enough controllers? Great! let the developer know.
  87869. if (_this.controllers.length >= 2) {
  87870. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87871. }
  87872. }
  87873. }
  87874. });
  87875. };
  87876. return WebVRFreeCamera;
  87877. }(BABYLON.FreeCamera));
  87878. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87879. })(BABYLON || (BABYLON = {}));
  87880. //# sourceMappingURL=babylon.webVRCamera.js.map
  87881. var BABYLON;
  87882. (function (BABYLON) {
  87883. // We're mainly based on the logic defined into the FreeCamera code
  87884. /**
  87885. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87886. * being tilted forward or back and left or right.
  87887. */
  87888. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87889. __extends(DeviceOrientationCamera, _super);
  87890. /**
  87891. * Creates a new device orientation camera
  87892. * @param name The name of the camera
  87893. * @param position The start position camera
  87894. * @param scene The scene the camera belongs to
  87895. */
  87896. function DeviceOrientationCamera(name, position, scene) {
  87897. var _this = _super.call(this, name, position, scene) || this;
  87898. _this._quaternionCache = new BABYLON.Quaternion();
  87899. _this.inputs.addDeviceOrientation();
  87900. return _this;
  87901. }
  87902. /**
  87903. * Gets the current instance class name ("DeviceOrientationCamera").
  87904. * This helps avoiding instanceof at run time.
  87905. * @returns the class name
  87906. */
  87907. DeviceOrientationCamera.prototype.getClassName = function () {
  87908. return "DeviceOrientationCamera";
  87909. };
  87910. /**
  87911. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87912. */
  87913. DeviceOrientationCamera.prototype._checkInputs = function () {
  87914. _super.prototype._checkInputs.call(this);
  87915. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87916. if (this._initialQuaternion) {
  87917. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87918. }
  87919. };
  87920. /**
  87921. * Reset the camera to its default orientation on the specified axis only.
  87922. * @param axis The axis to reset
  87923. */
  87924. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87925. var _this = this;
  87926. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87927. //can only work if this camera has a rotation quaternion already.
  87928. if (!this.rotationQuaternion)
  87929. return;
  87930. if (!this._initialQuaternion) {
  87931. this._initialQuaternion = new BABYLON.Quaternion();
  87932. }
  87933. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87934. ['x', 'y', 'z'].forEach(function (axisName) {
  87935. if (!axis[axisName]) {
  87936. _this._initialQuaternion[axisName] = 0;
  87937. }
  87938. else {
  87939. _this._initialQuaternion[axisName] *= -1;
  87940. }
  87941. });
  87942. this._initialQuaternion.normalize();
  87943. //force rotation update
  87944. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87945. };
  87946. return DeviceOrientationCamera;
  87947. }(BABYLON.FreeCamera));
  87948. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87949. })(BABYLON || (BABYLON = {}));
  87950. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87951. var BABYLON;
  87952. (function (BABYLON) {
  87953. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87954. __extends(VRDeviceOrientationFreeCamera, _super);
  87955. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87956. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87957. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87958. var _this = _super.call(this, name, position, scene) || this;
  87959. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87960. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87961. return _this;
  87962. }
  87963. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87964. return "VRDeviceOrientationFreeCamera";
  87965. };
  87966. return VRDeviceOrientationFreeCamera;
  87967. }(BABYLON.DeviceOrientationCamera));
  87968. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87969. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87970. __extends(VRDeviceOrientationGamepadCamera, _super);
  87971. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87972. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87973. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87974. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87975. _this.inputs.addGamepad();
  87976. return _this;
  87977. }
  87978. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87979. return "VRDeviceOrientationGamepadCamera";
  87980. };
  87981. return VRDeviceOrientationGamepadCamera;
  87982. }(VRDeviceOrientationFreeCamera));
  87983. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87984. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87985. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87986. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87987. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87988. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87989. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87990. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87991. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87992. _this.inputs.addVRDeviceOrientation();
  87993. return _this;
  87994. }
  87995. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87996. return "VRDeviceOrientationArcRotateCamera";
  87997. };
  87998. return VRDeviceOrientationArcRotateCamera;
  87999. }(BABYLON.ArcRotateCamera));
  88000. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  88001. })(BABYLON || (BABYLON = {}));
  88002. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  88003. var BABYLON;
  88004. (function (BABYLON) {
  88005. /**
  88006. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  88007. */
  88008. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  88009. __extends(AnaglyphFreeCamera, _super);
  88010. /**
  88011. * Creates a new AnaglyphFreeCamera
  88012. * @param name defines camera name
  88013. * @param position defines initial position
  88014. * @param interaxialDistance defines distance between each color axis
  88015. * @param scene defines the hosting scene
  88016. */
  88017. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  88018. var _this = _super.call(this, name, position, scene) || this;
  88019. _this.interaxialDistance = interaxialDistance;
  88020. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88021. return _this;
  88022. }
  88023. /**
  88024. * Gets camera class name
  88025. * @returns AnaglyphFreeCamera
  88026. */
  88027. AnaglyphFreeCamera.prototype.getClassName = function () {
  88028. return "AnaglyphFreeCamera";
  88029. };
  88030. return AnaglyphFreeCamera;
  88031. }(BABYLON.FreeCamera));
  88032. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  88033. /**
  88034. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  88035. */
  88036. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  88037. __extends(AnaglyphArcRotateCamera, _super);
  88038. /**
  88039. * Creates a new AnaglyphArcRotateCamera
  88040. * @param name defines camera name
  88041. * @param alpha defines alpha angle (in radians)
  88042. * @param beta defines beta angle (in radians)
  88043. * @param radius defines radius
  88044. * @param target defines camera target
  88045. * @param interaxialDistance defines distance between each color axis
  88046. * @param scene defines the hosting scene
  88047. */
  88048. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  88049. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88050. _this.interaxialDistance = interaxialDistance;
  88051. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88052. return _this;
  88053. }
  88054. /**
  88055. * Gets camera class name
  88056. * @returns AnaglyphArcRotateCamera
  88057. */
  88058. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  88059. return "AnaglyphArcRotateCamera";
  88060. };
  88061. return AnaglyphArcRotateCamera;
  88062. }(BABYLON.ArcRotateCamera));
  88063. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  88064. /**
  88065. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  88066. */
  88067. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  88068. __extends(AnaglyphGamepadCamera, _super);
  88069. /**
  88070. * Creates a new AnaglyphGamepadCamera
  88071. * @param name defines camera name
  88072. * @param position defines initial position
  88073. * @param interaxialDistance defines distance between each color axis
  88074. * @param scene defines the hosting scene
  88075. */
  88076. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  88077. var _this = _super.call(this, name, position, scene) || this;
  88078. _this.interaxialDistance = interaxialDistance;
  88079. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88080. return _this;
  88081. }
  88082. /**
  88083. * Gets camera class name
  88084. * @returns AnaglyphGamepadCamera
  88085. */
  88086. AnaglyphGamepadCamera.prototype.getClassName = function () {
  88087. return "AnaglyphGamepadCamera";
  88088. };
  88089. return AnaglyphGamepadCamera;
  88090. }(BABYLON.GamepadCamera));
  88091. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  88092. /**
  88093. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  88094. */
  88095. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  88096. __extends(AnaglyphUniversalCamera, _super);
  88097. /**
  88098. * Creates a new AnaglyphUniversalCamera
  88099. * @param name defines camera name
  88100. * @param position defines initial position
  88101. * @param interaxialDistance defines distance between each color axis
  88102. * @param scene defines the hosting scene
  88103. */
  88104. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  88105. var _this = _super.call(this, name, position, scene) || this;
  88106. _this.interaxialDistance = interaxialDistance;
  88107. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88108. return _this;
  88109. }
  88110. /**
  88111. * Gets camera class name
  88112. * @returns AnaglyphUniversalCamera
  88113. */
  88114. AnaglyphUniversalCamera.prototype.getClassName = function () {
  88115. return "AnaglyphUniversalCamera";
  88116. };
  88117. return AnaglyphUniversalCamera;
  88118. }(BABYLON.UniversalCamera));
  88119. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  88120. /**
  88121. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  88122. */
  88123. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  88124. __extends(StereoscopicFreeCamera, _super);
  88125. /**
  88126. * Creates a new StereoscopicFreeCamera
  88127. * @param name defines camera name
  88128. * @param position defines initial position
  88129. * @param interaxialDistance defines distance between each color axis
  88130. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88131. * @param scene defines the hosting scene
  88132. */
  88133. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88134. var _this = _super.call(this, name, position, scene) || this;
  88135. _this.interaxialDistance = interaxialDistance;
  88136. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88137. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88138. return _this;
  88139. }
  88140. /**
  88141. * Gets camera class name
  88142. * @returns StereoscopicFreeCamera
  88143. */
  88144. StereoscopicFreeCamera.prototype.getClassName = function () {
  88145. return "StereoscopicFreeCamera";
  88146. };
  88147. return StereoscopicFreeCamera;
  88148. }(BABYLON.FreeCamera));
  88149. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  88150. /**
  88151. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  88152. */
  88153. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  88154. __extends(StereoscopicArcRotateCamera, _super);
  88155. /**
  88156. * Creates a new StereoscopicArcRotateCamera
  88157. * @param name defines camera name
  88158. * @param alpha defines alpha angle (in radians)
  88159. * @param beta defines beta angle (in radians)
  88160. * @param radius defines radius
  88161. * @param target defines camera target
  88162. * @param interaxialDistance defines distance between each color axis
  88163. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88164. * @param scene defines the hosting scene
  88165. */
  88166. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  88167. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88168. _this.interaxialDistance = interaxialDistance;
  88169. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88170. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88171. return _this;
  88172. }
  88173. /**
  88174. * Gets camera class name
  88175. * @returns StereoscopicArcRotateCamera
  88176. */
  88177. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  88178. return "StereoscopicArcRotateCamera";
  88179. };
  88180. return StereoscopicArcRotateCamera;
  88181. }(BABYLON.ArcRotateCamera));
  88182. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  88183. /**
  88184. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  88185. */
  88186. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  88187. __extends(StereoscopicGamepadCamera, _super);
  88188. /**
  88189. * Creates a new StereoscopicGamepadCamera
  88190. * @param name defines camera name
  88191. * @param position defines initial position
  88192. * @param interaxialDistance defines distance between each color axis
  88193. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88194. * @param scene defines the hosting scene
  88195. */
  88196. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88197. var _this = _super.call(this, name, position, scene) || this;
  88198. _this.interaxialDistance = interaxialDistance;
  88199. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88200. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88201. return _this;
  88202. }
  88203. /**
  88204. * Gets camera class name
  88205. * @returns StereoscopicGamepadCamera
  88206. */
  88207. StereoscopicGamepadCamera.prototype.getClassName = function () {
  88208. return "StereoscopicGamepadCamera";
  88209. };
  88210. return StereoscopicGamepadCamera;
  88211. }(BABYLON.GamepadCamera));
  88212. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  88213. /**
  88214. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  88215. */
  88216. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  88217. __extends(StereoscopicUniversalCamera, _super);
  88218. /**
  88219. * Creates a new StereoscopicUniversalCamera
  88220. * @param name defines camera name
  88221. * @param position defines initial position
  88222. * @param interaxialDistance defines distance between each color axis
  88223. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88224. * @param scene defines the hosting scene
  88225. */
  88226. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88227. var _this = _super.call(this, name, position, scene) || this;
  88228. _this.interaxialDistance = interaxialDistance;
  88229. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88230. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88231. return _this;
  88232. }
  88233. /**
  88234. * Gets camera class name
  88235. * @returns StereoscopicUniversalCamera
  88236. */
  88237. StereoscopicUniversalCamera.prototype.getClassName = function () {
  88238. return "StereoscopicUniversalCamera";
  88239. };
  88240. return StereoscopicUniversalCamera;
  88241. }(BABYLON.UniversalCamera));
  88242. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  88243. })(BABYLON || (BABYLON = {}));
  88244. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  88245. var BABYLON;
  88246. (function (BABYLON) {
  88247. var VRExperienceHelperGazer = /** @class */ (function () {
  88248. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  88249. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  88250. this.scene = scene;
  88251. this._pointerDownOnMeshAsked = false;
  88252. this._isActionableMesh = false;
  88253. this._teleportationRequestInitiated = false;
  88254. this._teleportationBackRequestInitiated = false;
  88255. this._rotationRightAsked = false;
  88256. this._rotationLeftAsked = false;
  88257. this._dpadPressed = true;
  88258. this._activePointer = false;
  88259. this._id = VRExperienceHelperGazer._idCounter++;
  88260. // Gaze tracker
  88261. if (!gazeTrackerToClone) {
  88262. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  88263. this._gazeTracker.bakeCurrentTransformIntoVertices();
  88264. this._gazeTracker.isPickable = false;
  88265. this._gazeTracker.isVisible = false;
  88266. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  88267. targetMat.specularColor = BABYLON.Color3.Black();
  88268. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88269. targetMat.backFaceCulling = false;
  88270. this._gazeTracker.material = targetMat;
  88271. }
  88272. else {
  88273. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  88274. }
  88275. }
  88276. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  88277. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  88278. };
  88279. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  88280. this._pointerDownOnMeshAsked = true;
  88281. if (this._currentHit) {
  88282. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  88283. }
  88284. };
  88285. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  88286. if (this._currentHit) {
  88287. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  88288. }
  88289. this._pointerDownOnMeshAsked = false;
  88290. };
  88291. VRExperienceHelperGazer.prototype._activatePointer = function () {
  88292. this._activePointer = true;
  88293. };
  88294. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  88295. this._activePointer = false;
  88296. };
  88297. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  88298. if (distance === void 0) { distance = 100; }
  88299. };
  88300. VRExperienceHelperGazer.prototype.dispose = function () {
  88301. this._interactionsEnabled = false;
  88302. this._teleportationEnabled = false;
  88303. if (this._gazeTracker) {
  88304. this._gazeTracker.dispose();
  88305. }
  88306. };
  88307. VRExperienceHelperGazer._idCounter = 0;
  88308. return VRExperienceHelperGazer;
  88309. }());
  88310. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  88311. __extends(VRExperienceHelperControllerGazer, _super);
  88312. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  88313. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  88314. _this.webVRController = webVRController;
  88315. // Laser pointer
  88316. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  88317. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  88318. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88319. laserPointerMaterial.alpha = 0.6;
  88320. _this._laserPointer.material = laserPointerMaterial;
  88321. _this._laserPointer.rotation.x = Math.PI / 2;
  88322. _this._laserPointer.position.z = -0.5;
  88323. _this._laserPointer.isVisible = false;
  88324. if (!webVRController.mesh) {
  88325. // Create an empty mesh that is used prior to loading the high quality model
  88326. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  88327. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  88328. preloadPointerPose.rotation.x = -0.7;
  88329. preloadMesh.addChild(preloadPointerPose);
  88330. webVRController.attachToMesh(preloadMesh);
  88331. }
  88332. _this._setLaserPointerParent(webVRController.mesh);
  88333. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  88334. _this._setLaserPointerParent(mesh);
  88335. });
  88336. return _this;
  88337. }
  88338. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  88339. return this.webVRController.getForwardRay(length);
  88340. };
  88341. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  88342. _super.prototype._activatePointer.call(this);
  88343. this._laserPointer.isVisible = true;
  88344. };
  88345. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  88346. _super.prototype._deactivatePointer.call(this);
  88347. this._laserPointer.isVisible = false;
  88348. };
  88349. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  88350. this._laserPointer.material.emissiveColor = color;
  88351. };
  88352. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  88353. var makeNotPick = function (root) {
  88354. root.name += " laserPointer";
  88355. root.getChildMeshes().forEach(function (c) {
  88356. makeNotPick(c);
  88357. });
  88358. };
  88359. makeNotPick(mesh);
  88360. var childMeshes = mesh.getChildMeshes();
  88361. this.webVRController._pointingPoseNode = null;
  88362. for (var i = 0; i < childMeshes.length; i++) {
  88363. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  88364. mesh = childMeshes[i];
  88365. this.webVRController._pointingPoseNode = mesh;
  88366. break;
  88367. }
  88368. }
  88369. this._laserPointer.parent = mesh;
  88370. };
  88371. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  88372. if (distance === void 0) { distance = 100; }
  88373. this._laserPointer.scaling.y = distance;
  88374. this._laserPointer.position.z = -distance / 2;
  88375. };
  88376. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  88377. _super.prototype.dispose.call(this);
  88378. this._laserPointer.dispose();
  88379. if (this._meshAttachedObserver) {
  88380. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  88381. }
  88382. };
  88383. return VRExperienceHelperControllerGazer;
  88384. }(VRExperienceHelperGazer));
  88385. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  88386. __extends(VRExperienceHelperCameraGazer, _super);
  88387. function VRExperienceHelperCameraGazer(getCamera, scene) {
  88388. var _this = _super.call(this, scene) || this;
  88389. _this.getCamera = getCamera;
  88390. return _this;
  88391. }
  88392. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  88393. var camera = this.getCamera();
  88394. if (camera) {
  88395. return camera.getForwardRay(length);
  88396. }
  88397. else {
  88398. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  88399. }
  88400. };
  88401. return VRExperienceHelperCameraGazer;
  88402. }(VRExperienceHelperGazer));
  88403. /**
  88404. * Helps to quickly add VR support to an existing scene.
  88405. * See http://doc.babylonjs.com/how_to/webvr_helper
  88406. */
  88407. var VRExperienceHelper = /** @class */ (function () {
  88408. /**
  88409. * Instantiates a VRExperienceHelper.
  88410. * Helps to quickly add VR support to an existing scene.
  88411. * @param scene The scene the VRExperienceHelper belongs to.
  88412. * @param webVROptions Options to modify the vr experience helper's behavior.
  88413. */
  88414. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  88415. if (webVROptions === void 0) { webVROptions = {}; }
  88416. var _this = this;
  88417. this.webVROptions = webVROptions;
  88418. // Can the system support WebVR, even if a headset isn't plugged in?
  88419. this._webVRsupported = false;
  88420. // If WebVR is supported, is a headset plugged in and are we ready to present?
  88421. this._webVRready = false;
  88422. // Are we waiting for the requestPresent callback to complete?
  88423. this._webVRrequesting = false;
  88424. // Are we presenting to the headset right now?
  88425. this._webVRpresenting = false;
  88426. // Are we presenting in the fullscreen fallback?
  88427. this._fullscreenVRpresenting = false;
  88428. /**
  88429. * Observable raised when entering VR.
  88430. */
  88431. this.onEnteringVRObservable = new BABYLON.Observable();
  88432. /**
  88433. * Observable raised when exiting VR.
  88434. */
  88435. this.onExitingVRObservable = new BABYLON.Observable();
  88436. /**
  88437. * Observable raised when controller mesh is loaded.
  88438. */
  88439. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88440. this._useCustomVRButton = false;
  88441. this._teleportationRequested = false;
  88442. this._teleportActive = false;
  88443. this._floorMeshesCollection = [];
  88444. this._rotationAllowed = true;
  88445. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  88446. this._isDefaultTeleportationTarget = true;
  88447. this._teleportationFillColor = "#444444";
  88448. this._teleportationBorderColor = "#FFFFFF";
  88449. this._rotationAngle = 0;
  88450. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  88451. this._padSensibilityUp = 0.65;
  88452. this._padSensibilityDown = 0.35;
  88453. this.leftController = null;
  88454. this.rightController = null;
  88455. /**
  88456. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  88457. */
  88458. this.onNewMeshSelected = new BABYLON.Observable();
  88459. /**
  88460. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  88461. */
  88462. this.onNewMeshPicked = new BABYLON.Observable();
  88463. /**
  88464. * Observable raised before camera teleportation
  88465. */
  88466. this.onBeforeCameraTeleport = new BABYLON.Observable();
  88467. /**
  88468. * Observable raised after camera teleportation
  88469. */
  88470. this.onAfterCameraTeleport = new BABYLON.Observable();
  88471. /**
  88472. * Observable raised when current selected mesh gets unselected
  88473. */
  88474. this.onSelectedMeshUnselected = new BABYLON.Observable();
  88475. /**
  88476. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  88477. */
  88478. this.teleportationEnabled = true;
  88479. this._teleportationInitialized = false;
  88480. this._interactionsEnabled = false;
  88481. this._interactionsRequested = false;
  88482. this._displayGaze = true;
  88483. this._displayLaserPointer = true;
  88484. this._onResize = function () {
  88485. _this.moveButtonToBottomRight();
  88486. if (_this._fullscreenVRpresenting && _this._webVRready) {
  88487. _this.exitVR();
  88488. }
  88489. };
  88490. this._onFullscreenChange = function () {
  88491. if (document.fullscreen !== undefined) {
  88492. _this._fullscreenVRpresenting = document.fullscreen;
  88493. }
  88494. else if (document.mozFullScreen !== undefined) {
  88495. _this._fullscreenVRpresenting = document.mozFullScreen;
  88496. }
  88497. else if (document.webkitIsFullScreen !== undefined) {
  88498. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  88499. }
  88500. else if (document.msIsFullScreen !== undefined) {
  88501. _this._fullscreenVRpresenting = document.msIsFullScreen;
  88502. }
  88503. if (!_this._fullscreenVRpresenting && _this._canvas) {
  88504. _this.exitVR();
  88505. if (!_this._useCustomVRButton) {
  88506. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  88507. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  88508. }
  88509. }
  88510. };
  88511. this.beforeRender = function () {
  88512. if (_this.leftController && _this.leftController._activePointer) {
  88513. _this._castRayAndSelectObject(_this.leftController);
  88514. }
  88515. if (_this.rightController && _this.rightController._activePointer) {
  88516. _this._castRayAndSelectObject(_this.rightController);
  88517. }
  88518. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  88519. _this._castRayAndSelectObject(_this._cameraGazer);
  88520. }
  88521. else {
  88522. _this._cameraGazer._gazeTracker.isVisible = false;
  88523. }
  88524. };
  88525. this._onNewGamepadConnected = function (gamepad) {
  88526. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  88527. if (gamepad.leftStick) {
  88528. gamepad.onleftstickchanged(function (stickValues) {
  88529. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  88530. // Listening to classic/xbox gamepad only if no VR controller is active
  88531. if ((!_this.leftController && !_this.rightController) ||
  88532. ((_this.leftController && !_this.leftController._activePointer) &&
  88533. (_this.rightController && !_this.rightController._activePointer))) {
  88534. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  88535. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  88536. }
  88537. }
  88538. });
  88539. }
  88540. if (gamepad.rightStick) {
  88541. gamepad.onrightstickchanged(function (stickValues) {
  88542. if (_this._teleportationInitialized) {
  88543. _this._checkRotate(stickValues, _this._cameraGazer);
  88544. }
  88545. });
  88546. }
  88547. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  88548. gamepad.onbuttondown(function (buttonPressed) {
  88549. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88550. _this._cameraGazer._selectionPointerDown();
  88551. }
  88552. });
  88553. gamepad.onbuttonup(function (buttonPressed) {
  88554. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88555. _this._cameraGazer._selectionPointerUp();
  88556. }
  88557. });
  88558. }
  88559. }
  88560. else {
  88561. var webVRController = gamepad;
  88562. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  88563. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  88564. _this.rightController = controller;
  88565. }
  88566. else {
  88567. _this.leftController = controller;
  88568. }
  88569. _this._tryEnableInteractionOnController(controller);
  88570. }
  88571. };
  88572. // 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
  88573. this._tryEnableInteractionOnController = function (controller) {
  88574. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  88575. _this._enableInteractionOnController(controller);
  88576. }
  88577. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  88578. _this._enableTeleportationOnController(controller);
  88579. }
  88580. };
  88581. this._onNewGamepadDisconnected = function (gamepad) {
  88582. if (gamepad instanceof BABYLON.WebVRController) {
  88583. if (gamepad.hand === "left" && _this.leftController != null) {
  88584. _this.leftController.dispose();
  88585. _this.leftController = null;
  88586. }
  88587. if (gamepad.hand === "right" && _this.rightController != null) {
  88588. _this.rightController.dispose();
  88589. _this.rightController = null;
  88590. }
  88591. }
  88592. };
  88593. this._workingVector = BABYLON.Vector3.Zero();
  88594. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88595. this._workingMatrix = BABYLON.Matrix.Identity();
  88596. this._scene = scene;
  88597. this._canvas = scene.getEngine().getRenderingCanvas();
  88598. // Parse options
  88599. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88600. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88601. }
  88602. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88603. webVROptions.createDeviceOrientationCamera = true;
  88604. }
  88605. if (webVROptions.laserToggle === undefined) {
  88606. webVROptions.laserToggle = true;
  88607. }
  88608. if (webVROptions.defaultHeight === undefined) {
  88609. webVROptions.defaultHeight = 1.7;
  88610. }
  88611. if (webVROptions.useCustomVRButton) {
  88612. this._useCustomVRButton = true;
  88613. if (webVROptions.customVRButton) {
  88614. this._btnVR = webVROptions.customVRButton;
  88615. }
  88616. }
  88617. if (webVROptions.rayLength) {
  88618. this._rayLength = webVROptions.rayLength;
  88619. }
  88620. this._defaultHeight = webVROptions.defaultHeight;
  88621. if (webVROptions.positionScale) {
  88622. this._rayLength *= webVROptions.positionScale;
  88623. this._defaultHeight *= webVROptions.positionScale;
  88624. }
  88625. // Set position
  88626. if (this._scene.activeCamera) {
  88627. this._position = this._scene.activeCamera.position.clone();
  88628. }
  88629. else {
  88630. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88631. }
  88632. // Set non-vr camera
  88633. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88634. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88635. // Copy data from existing camera
  88636. if (this._scene.activeCamera) {
  88637. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88638. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88639. // Set rotation from previous camera
  88640. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88641. var targetCamera = this._scene.activeCamera;
  88642. if (targetCamera.rotationQuaternion) {
  88643. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88644. }
  88645. else {
  88646. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88647. }
  88648. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88649. }
  88650. }
  88651. this._scene.activeCamera = this._deviceOrientationCamera;
  88652. if (this._canvas) {
  88653. this._scene.activeCamera.attachControl(this._canvas);
  88654. }
  88655. }
  88656. else {
  88657. this._existingCamera = this._scene.activeCamera;
  88658. }
  88659. // Create VR cameras
  88660. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88661. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88662. }
  88663. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88664. this._webVRCamera.useStandingMatrix();
  88665. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88666. // Create default button
  88667. if (!this._useCustomVRButton) {
  88668. this._btnVR = document.createElement("BUTTON");
  88669. this._btnVR.className = "babylonVRicon";
  88670. this._btnVR.id = "babylonVRiconbtn";
  88671. this._btnVR.title = "Click to switch to VR";
  88672. 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) }";
  88673. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88674. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88675. // css += ".babylonVRicon.vrdisplaysupported { }";
  88676. // css += ".babylonVRicon.vrdisplayready { }";
  88677. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88678. var style = document.createElement('style');
  88679. style.appendChild(document.createTextNode(css));
  88680. document.getElementsByTagName('head')[0].appendChild(style);
  88681. this.moveButtonToBottomRight();
  88682. }
  88683. // VR button click event
  88684. if (this._btnVR) {
  88685. this._btnVR.addEventListener("click", function () {
  88686. if (!_this.isInVRMode) {
  88687. _this.enterVR();
  88688. }
  88689. else {
  88690. _this.exitVR();
  88691. }
  88692. });
  88693. }
  88694. // Window events
  88695. window.addEventListener("resize", this._onResize);
  88696. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88697. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88698. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88699. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88700. // Display vr button when headset is connected
  88701. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88702. this.displayVRButton();
  88703. }
  88704. else {
  88705. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88706. if (e.vrDisplay) {
  88707. _this.displayVRButton();
  88708. }
  88709. });
  88710. }
  88711. // Exiting VR mode using 'ESC' key on desktop
  88712. this._onKeyDown = function (event) {
  88713. if (event.keyCode === 27 && _this.isInVRMode) {
  88714. _this.exitVR();
  88715. }
  88716. };
  88717. document.addEventListener("keydown", this._onKeyDown);
  88718. // Exiting VR mode double tapping the touch screen
  88719. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88720. if (_this.isInVRMode) {
  88721. _this.exitVR();
  88722. if (_this._fullscreenVRpresenting) {
  88723. _this._scene.getEngine().switchFullscreen(true);
  88724. }
  88725. }
  88726. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88727. // Listen for WebVR display changes
  88728. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88729. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88730. this._onVRRequestPresentStart = function () {
  88731. _this._webVRrequesting = true;
  88732. _this.updateButtonVisibility();
  88733. };
  88734. this._onVRRequestPresentComplete = function (success) {
  88735. _this._webVRrequesting = false;
  88736. _this.updateButtonVisibility();
  88737. };
  88738. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88739. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88740. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88741. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88742. scene.onDisposeObservable.add(function () {
  88743. _this.dispose();
  88744. });
  88745. // Gamepad connection events
  88746. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88747. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88748. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88749. this.updateButtonVisibility();
  88750. //create easing functions
  88751. this._circleEase = new BABYLON.CircleEase();
  88752. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88753. if (this.webVROptions.floorMeshes) {
  88754. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  88755. }
  88756. }
  88757. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88758. /** Return this.onEnteringVRObservable
  88759. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88760. */
  88761. get: function () {
  88762. return this.onEnteringVRObservable;
  88763. },
  88764. enumerable: true,
  88765. configurable: true
  88766. });
  88767. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88768. /** Return this.onExitingVRObservable
  88769. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88770. */
  88771. get: function () {
  88772. return this.onExitingVRObservable;
  88773. },
  88774. enumerable: true,
  88775. configurable: true
  88776. });
  88777. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88778. /** Return this.onControllerMeshLoadedObservable
  88779. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88780. */
  88781. get: function () {
  88782. return this.onControllerMeshLoadedObservable;
  88783. },
  88784. enumerable: true,
  88785. configurable: true
  88786. });
  88787. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88788. /**
  88789. * The mesh used to display where the user is going to teleport.
  88790. */
  88791. get: function () {
  88792. return this._teleportationTarget;
  88793. },
  88794. /**
  88795. * Sets the mesh to be used to display where the user is going to teleport.
  88796. */
  88797. set: function (value) {
  88798. if (value) {
  88799. value.name = "teleportationTarget";
  88800. this._isDefaultTeleportationTarget = false;
  88801. this._teleportationTarget = value;
  88802. }
  88803. },
  88804. enumerable: true,
  88805. configurable: true
  88806. });
  88807. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88808. /**
  88809. * The mesh used to display where the user is selecting,
  88810. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88811. * See http://doc.babylonjs.com/resources/baking_transformations
  88812. */
  88813. get: function () {
  88814. return this._cameraGazer._gazeTracker;
  88815. },
  88816. set: function (value) {
  88817. if (value) {
  88818. this._cameraGazer._gazeTracker = value;
  88819. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88820. this._cameraGazer._gazeTracker.isPickable = false;
  88821. this._cameraGazer._gazeTracker.isVisible = false;
  88822. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88823. if (this.leftController) {
  88824. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88825. }
  88826. if (this.rightController) {
  88827. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88828. }
  88829. }
  88830. },
  88831. enumerable: true,
  88832. configurable: true
  88833. });
  88834. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88835. /**
  88836. * If the ray of the gaze should be displayed.
  88837. */
  88838. get: function () {
  88839. return this._displayGaze;
  88840. },
  88841. /**
  88842. * Sets if the ray of the gaze should be displayed.
  88843. */
  88844. set: function (value) {
  88845. this._displayGaze = value;
  88846. if (!value) {
  88847. this._cameraGazer._gazeTracker.isVisible = false;
  88848. if (this.leftController) {
  88849. this.leftController._gazeTracker.isVisible = false;
  88850. }
  88851. if (this.rightController) {
  88852. this.rightController._gazeTracker.isVisible = false;
  88853. }
  88854. }
  88855. },
  88856. enumerable: true,
  88857. configurable: true
  88858. });
  88859. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88860. /**
  88861. * If the ray of the LaserPointer should be displayed.
  88862. */
  88863. get: function () {
  88864. return this._displayLaserPointer;
  88865. },
  88866. /**
  88867. * Sets if the ray of the LaserPointer should be displayed.
  88868. */
  88869. set: function (value) {
  88870. this._displayLaserPointer = value;
  88871. if (!value) {
  88872. if (this.rightController) {
  88873. this.rightController._deactivatePointer();
  88874. this.rightController._gazeTracker.isVisible = false;
  88875. }
  88876. if (this.leftController) {
  88877. this.leftController._deactivatePointer();
  88878. this.leftController._gazeTracker.isVisible = false;
  88879. }
  88880. }
  88881. else {
  88882. if (this.rightController) {
  88883. this.rightController._activatePointer();
  88884. }
  88885. if (this.leftController) {
  88886. this.leftController._activatePointer();
  88887. }
  88888. }
  88889. },
  88890. enumerable: true,
  88891. configurable: true
  88892. });
  88893. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88894. /**
  88895. * The deviceOrientationCamera used as the camera when not in VR.
  88896. */
  88897. get: function () {
  88898. return this._deviceOrientationCamera;
  88899. },
  88900. enumerable: true,
  88901. configurable: true
  88902. });
  88903. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88904. /**
  88905. * Based on the current WebVR support, returns the current VR camera used.
  88906. */
  88907. get: function () {
  88908. if (this._webVRready) {
  88909. return this._webVRCamera;
  88910. }
  88911. else {
  88912. return this._scene.activeCamera;
  88913. }
  88914. },
  88915. enumerable: true,
  88916. configurable: true
  88917. });
  88918. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88919. /**
  88920. * The webVRCamera which is used when in VR.
  88921. */
  88922. get: function () {
  88923. return this._webVRCamera;
  88924. },
  88925. enumerable: true,
  88926. configurable: true
  88927. });
  88928. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88929. /**
  88930. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88931. */
  88932. get: function () {
  88933. return this._vrDeviceOrientationCamera;
  88934. },
  88935. enumerable: true,
  88936. configurable: true
  88937. });
  88938. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88939. get: function () {
  88940. var result = this._cameraGazer._teleportationRequestInitiated
  88941. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88942. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88943. return result;
  88944. },
  88945. enumerable: true,
  88946. configurable: true
  88947. });
  88948. // Raised when one of the controller has loaded successfully its associated default mesh
  88949. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88950. if (this.leftController && this.leftController.webVRController == webVRController) {
  88951. if (webVRController.mesh) {
  88952. this.leftController._setLaserPointerParent(webVRController.mesh);
  88953. }
  88954. }
  88955. if (this.rightController && this.rightController.webVRController == webVRController) {
  88956. if (webVRController.mesh) {
  88957. this.rightController._setLaserPointerParent(webVRController.mesh);
  88958. }
  88959. }
  88960. try {
  88961. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88962. }
  88963. catch (err) {
  88964. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88965. }
  88966. };
  88967. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88968. /**
  88969. * Gets a value indicating if we are currently in VR mode.
  88970. */
  88971. get: function () {
  88972. return this._webVRpresenting || this._fullscreenVRpresenting;
  88973. },
  88974. enumerable: true,
  88975. configurable: true
  88976. });
  88977. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88978. var vrDisplay = this._scene.getEngine().getVRDevice();
  88979. if (vrDisplay) {
  88980. var wasPresenting = this._webVRpresenting;
  88981. // A VR display is connected
  88982. this._webVRpresenting = vrDisplay.isPresenting;
  88983. if (wasPresenting && !this._webVRpresenting)
  88984. this.exitVR();
  88985. }
  88986. else {
  88987. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88988. }
  88989. this.updateButtonVisibility();
  88990. };
  88991. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88992. this._webVRsupported = eventArgs.vrSupported;
  88993. this._webVRready = !!eventArgs.vrDisplay;
  88994. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88995. this.updateButtonVisibility();
  88996. };
  88997. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88998. if (this._canvas && !this._useCustomVRButton) {
  88999. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  89000. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  89001. }
  89002. };
  89003. VRExperienceHelper.prototype.displayVRButton = function () {
  89004. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  89005. document.body.appendChild(this._btnVR);
  89006. this._btnVRDisplayed = true;
  89007. }
  89008. };
  89009. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  89010. if (!this._btnVR || this._useCustomVRButton) {
  89011. return;
  89012. }
  89013. this._btnVR.className = "babylonVRicon";
  89014. if (this.isInVRMode) {
  89015. this._btnVR.className += " vrdisplaypresenting";
  89016. }
  89017. else {
  89018. if (this._webVRready)
  89019. this._btnVR.className += " vrdisplayready";
  89020. if (this._webVRsupported)
  89021. this._btnVR.className += " vrdisplaysupported";
  89022. if (this._webVRrequesting)
  89023. this._btnVR.className += " vrdisplayrequesting";
  89024. }
  89025. };
  89026. /**
  89027. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  89028. * Otherwise, will use the fullscreen API.
  89029. */
  89030. VRExperienceHelper.prototype.enterVR = function () {
  89031. if (this.onEnteringVRObservable) {
  89032. try {
  89033. this.onEnteringVRObservable.notifyObservers(this);
  89034. }
  89035. catch (err) {
  89036. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  89037. }
  89038. }
  89039. if (this._scene.activeCamera) {
  89040. this._position = this._scene.activeCamera.position.clone();
  89041. // make sure that we return to the last active camera
  89042. this._existingCamera = this._scene.activeCamera;
  89043. }
  89044. if (this._webVRrequesting)
  89045. return;
  89046. // If WebVR is supported and a headset is connected
  89047. if (this._webVRready) {
  89048. if (!this._webVRpresenting) {
  89049. this._webVRCamera.position = this._position;
  89050. this._scene.activeCamera = this._webVRCamera;
  89051. }
  89052. }
  89053. else if (this._vrDeviceOrientationCamera) {
  89054. this._vrDeviceOrientationCamera.position = this._position;
  89055. if (this._scene.activeCamera) {
  89056. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  89057. }
  89058. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  89059. this._scene.getEngine().switchFullscreen(true);
  89060. this.updateButtonVisibility();
  89061. }
  89062. if (this._scene.activeCamera && this._canvas) {
  89063. this._scene.activeCamera.attachControl(this._canvas);
  89064. }
  89065. if (this._interactionsEnabled) {
  89066. this._scene.registerBeforeRender(this.beforeRender);
  89067. }
  89068. };
  89069. /**
  89070. * Attempt to exit VR, or fullscreen.
  89071. */
  89072. VRExperienceHelper.prototype.exitVR = function () {
  89073. if (this.onExitingVRObservable) {
  89074. try {
  89075. this.onExitingVRObservable.notifyObservers(this);
  89076. }
  89077. catch (err) {
  89078. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  89079. }
  89080. }
  89081. if (this._webVRpresenting) {
  89082. this._scene.getEngine().disableVR();
  89083. }
  89084. if (this._scene.activeCamera) {
  89085. this._position = this._scene.activeCamera.position.clone();
  89086. }
  89087. if (this._deviceOrientationCamera) {
  89088. this._deviceOrientationCamera.position = this._position;
  89089. this._scene.activeCamera = this._deviceOrientationCamera;
  89090. if (this._canvas) {
  89091. this._scene.activeCamera.attachControl(this._canvas);
  89092. }
  89093. }
  89094. else if (this._existingCamera) {
  89095. this._existingCamera.position = this._position;
  89096. this._scene.activeCamera = this._existingCamera;
  89097. }
  89098. this.updateButtonVisibility();
  89099. if (this._interactionsEnabled) {
  89100. this._scene.unregisterBeforeRender(this.beforeRender);
  89101. }
  89102. // resize to update width and height when exiting vr exits fullscreen
  89103. this._scene.getEngine().resize();
  89104. };
  89105. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  89106. /**
  89107. * The position of the vr experience helper.
  89108. */
  89109. get: function () {
  89110. return this._position;
  89111. },
  89112. /**
  89113. * Sets the position of the vr experience helper.
  89114. */
  89115. set: function (value) {
  89116. this._position = value;
  89117. if (this._scene.activeCamera) {
  89118. this._scene.activeCamera.position = value;
  89119. }
  89120. },
  89121. enumerable: true,
  89122. configurable: true
  89123. });
  89124. /**
  89125. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  89126. */
  89127. VRExperienceHelper.prototype.enableInteractions = function () {
  89128. var _this = this;
  89129. if (!this._interactionsEnabled) {
  89130. this._interactionsRequested = true;
  89131. if (this.leftController) {
  89132. this._enableInteractionOnController(this.leftController);
  89133. }
  89134. if (this.rightController) {
  89135. this._enableInteractionOnController(this.rightController);
  89136. }
  89137. this.raySelectionPredicate = function (mesh) {
  89138. return mesh.isVisible;
  89139. };
  89140. this.meshSelectionPredicate = function (mesh) {
  89141. return true;
  89142. };
  89143. this._raySelectionPredicate = function (mesh) {
  89144. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  89145. && mesh.name.indexOf("teleportationTarget") === -1
  89146. && mesh.name.indexOf("torusTeleportation") === -1
  89147. && mesh.name.indexOf("laserPointer") === -1)) {
  89148. return _this.raySelectionPredicate(mesh);
  89149. }
  89150. return false;
  89151. };
  89152. this._interactionsEnabled = true;
  89153. }
  89154. };
  89155. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  89156. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  89157. if (this._floorMeshesCollection[i].id === mesh.id) {
  89158. return true;
  89159. }
  89160. }
  89161. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  89162. return true;
  89163. }
  89164. return false;
  89165. };
  89166. /**
  89167. * Adds a floor mesh to be used for teleportation.
  89168. * @param floorMesh the mesh to be used for teleportation.
  89169. */
  89170. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  89171. if (!this._floorMeshesCollection) {
  89172. return;
  89173. }
  89174. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  89175. return;
  89176. }
  89177. this._floorMeshesCollection.push(floorMesh);
  89178. };
  89179. /**
  89180. * Removes a floor mesh from being used for teleportation.
  89181. * @param floorMesh the mesh to be removed.
  89182. */
  89183. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  89184. if (!this._floorMeshesCollection) {
  89185. return;
  89186. }
  89187. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  89188. if (meshIndex !== -1) {
  89189. this._floorMeshesCollection.splice(meshIndex, 1);
  89190. }
  89191. };
  89192. /**
  89193. * Enables interactions and teleportation using the VR controllers and gaze.
  89194. * @param vrTeleportationOptions options to modify teleportation behavior.
  89195. */
  89196. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  89197. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  89198. if (!this._teleportationInitialized) {
  89199. this._teleportationRequested = true;
  89200. this.enableInteractions();
  89201. if (vrTeleportationOptions.floorMeshName) {
  89202. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  89203. }
  89204. if (vrTeleportationOptions.floorMeshes) {
  89205. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  89206. }
  89207. if (this.leftController != null) {
  89208. this._enableTeleportationOnController(this.leftController);
  89209. }
  89210. if (this.rightController != null) {
  89211. this._enableTeleportationOnController(this.rightController);
  89212. }
  89213. // Creates an image processing post process for the vignette not relying
  89214. // on the main scene configuration for image processing to reduce setup and spaces
  89215. // (gamma/linear) conflicts.
  89216. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  89217. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89218. imageProcessingConfiguration.vignetteEnabled = true;
  89219. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  89220. this._webVRCamera.detachPostProcess(this._postProcessMove);
  89221. this._teleportationInitialized = true;
  89222. if (this._isDefaultTeleportationTarget) {
  89223. this._createTeleportationCircles();
  89224. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  89225. }
  89226. }
  89227. };
  89228. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  89229. var _this = this;
  89230. var controllerMesh = controller.webVRController.mesh;
  89231. if (controllerMesh) {
  89232. controller._interactionsEnabled = true;
  89233. controller._activatePointer();
  89234. if (this.webVROptions.laserToggle) {
  89235. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  89236. // Enabling / disabling laserPointer
  89237. if (_this._displayLaserPointer && stateObject.value === 1) {
  89238. if (controller._activePointer) {
  89239. controller._deactivatePointer();
  89240. }
  89241. else {
  89242. controller._activatePointer();
  89243. }
  89244. if (_this.displayGaze) {
  89245. controller._gazeTracker.isVisible = controller._activePointer;
  89246. }
  89247. }
  89248. });
  89249. }
  89250. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  89251. if (!controller._pointerDownOnMeshAsked) {
  89252. if (stateObject.value > _this._padSensibilityUp) {
  89253. controller._selectionPointerDown();
  89254. }
  89255. }
  89256. else if (stateObject.value < _this._padSensibilityDown) {
  89257. controller._selectionPointerUp();
  89258. }
  89259. });
  89260. }
  89261. };
  89262. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  89263. // Dont teleport if another gaze already requested teleportation
  89264. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  89265. return;
  89266. }
  89267. if (!gazer._teleportationRequestInitiated) {
  89268. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  89269. gazer._activatePointer();
  89270. gazer._teleportationRequestInitiated = true;
  89271. }
  89272. }
  89273. else {
  89274. // Listening to the proper controller values changes to confirm teleportation
  89275. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  89276. if (this._teleportActive) {
  89277. this._teleportCamera(this._haloCenter);
  89278. }
  89279. gazer._teleportationRequestInitiated = false;
  89280. }
  89281. }
  89282. };
  89283. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  89284. // Only rotate when user is not currently selecting a teleportation location
  89285. if (gazer._teleportationRequestInitiated) {
  89286. return;
  89287. }
  89288. if (!gazer._rotationLeftAsked) {
  89289. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  89290. gazer._rotationLeftAsked = true;
  89291. if (this._rotationAllowed) {
  89292. this._rotateCamera(false);
  89293. }
  89294. }
  89295. }
  89296. else {
  89297. if (stateObject.x > -this._padSensibilityDown) {
  89298. gazer._rotationLeftAsked = false;
  89299. }
  89300. }
  89301. if (!gazer._rotationRightAsked) {
  89302. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  89303. gazer._rotationRightAsked = true;
  89304. if (this._rotationAllowed) {
  89305. this._rotateCamera(true);
  89306. }
  89307. }
  89308. }
  89309. else {
  89310. if (stateObject.x < this._padSensibilityDown) {
  89311. gazer._rotationRightAsked = false;
  89312. }
  89313. }
  89314. };
  89315. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  89316. // Only teleport backwards when user is not currently selecting a teleportation location
  89317. if (gazer._teleportationRequestInitiated) {
  89318. return;
  89319. }
  89320. // Teleport backwards
  89321. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  89322. if (!gazer._teleportationBackRequestInitiated) {
  89323. if (!this.currentVRCamera) {
  89324. return;
  89325. }
  89326. // Get rotation and position of the current camera
  89327. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  89328. var position = this.currentVRCamera.position;
  89329. // If the camera has device position, use that instead
  89330. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  89331. rotation = this.currentVRCamera.deviceRotationQuaternion;
  89332. position = this.currentVRCamera.devicePosition;
  89333. }
  89334. // Get matrix with only the y rotation of the device rotation
  89335. rotation.toEulerAnglesToRef(this._workingVector);
  89336. this._workingVector.z = 0;
  89337. this._workingVector.x = 0;
  89338. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  89339. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  89340. // Rotate backwards ray by device rotation to cast at the ground behind the user
  89341. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  89342. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  89343. var ray = new BABYLON.Ray(position, this._workingVector);
  89344. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89345. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  89346. this._teleportCamera(hit.pickedPoint);
  89347. }
  89348. gazer._teleportationBackRequestInitiated = true;
  89349. }
  89350. }
  89351. else {
  89352. gazer._teleportationBackRequestInitiated = false;
  89353. }
  89354. };
  89355. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  89356. var _this = this;
  89357. var controllerMesh = controller.webVRController.mesh;
  89358. if (controllerMesh) {
  89359. if (!controller._interactionsEnabled) {
  89360. this._enableInteractionOnController(controller);
  89361. }
  89362. controller._interactionsEnabled = true;
  89363. controller._teleportationEnabled = true;
  89364. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89365. controller._dpadPressed = false;
  89366. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  89367. controller._dpadPressed = stateObject.pressed;
  89368. if (!controller._dpadPressed) {
  89369. controller._rotationLeftAsked = false;
  89370. controller._rotationRightAsked = false;
  89371. controller._teleportationBackRequestInitiated = false;
  89372. }
  89373. });
  89374. }
  89375. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  89376. if (_this.teleportationEnabled) {
  89377. _this._checkTeleportBackwards(stateObject, controller);
  89378. _this._checkTeleportWithRay(stateObject, controller);
  89379. }
  89380. _this._checkRotate(stateObject, controller);
  89381. });
  89382. }
  89383. };
  89384. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  89385. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  89386. this._teleportationTarget.isPickable = false;
  89387. var length = 512;
  89388. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  89389. dynamicTexture.hasAlpha = true;
  89390. var context = dynamicTexture.getContext();
  89391. var centerX = length / 2;
  89392. var centerY = length / 2;
  89393. var radius = 200;
  89394. context.beginPath();
  89395. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  89396. context.fillStyle = this._teleportationFillColor;
  89397. context.fill();
  89398. context.lineWidth = 10;
  89399. context.strokeStyle = this._teleportationBorderColor;
  89400. context.stroke();
  89401. context.closePath();
  89402. dynamicTexture.update();
  89403. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  89404. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  89405. this._teleportationTarget.material = teleportationCircleMaterial;
  89406. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  89407. torus.isPickable = false;
  89408. torus.parent = this._teleportationTarget;
  89409. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89410. var keys = [];
  89411. keys.push({
  89412. frame: 0,
  89413. value: 0
  89414. });
  89415. keys.push({
  89416. frame: 30,
  89417. value: 0.4
  89418. });
  89419. keys.push({
  89420. frame: 60,
  89421. value: 0
  89422. });
  89423. animationInnerCircle.setKeys(keys);
  89424. var easingFunction = new BABYLON.SineEase();
  89425. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89426. animationInnerCircle.setEasingFunction(easingFunction);
  89427. torus.animations = [];
  89428. torus.animations.push(animationInnerCircle);
  89429. this._scene.beginAnimation(torus, 0, 60, true);
  89430. this._hideTeleportationTarget();
  89431. };
  89432. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  89433. this._teleportActive = true;
  89434. if (this._teleportationInitialized) {
  89435. this._teleportationTarget.isVisible = true;
  89436. if (this._isDefaultTeleportationTarget) {
  89437. this._teleportationTarget.getChildren()[0].isVisible = true;
  89438. }
  89439. }
  89440. };
  89441. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  89442. this._teleportActive = false;
  89443. if (this._teleportationInitialized) {
  89444. this._teleportationTarget.isVisible = false;
  89445. if (this._isDefaultTeleportationTarget) {
  89446. this._teleportationTarget.getChildren()[0].isVisible = false;
  89447. }
  89448. }
  89449. };
  89450. VRExperienceHelper.prototype._rotateCamera = function (right) {
  89451. var _this = this;
  89452. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89453. return;
  89454. }
  89455. if (right) {
  89456. this._rotationAngle++;
  89457. }
  89458. else {
  89459. this._rotationAngle--;
  89460. }
  89461. this.currentVRCamera.animations = [];
  89462. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  89463. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89464. var animationRotationKeys = [];
  89465. animationRotationKeys.push({
  89466. frame: 0,
  89467. value: this.currentVRCamera.rotationQuaternion
  89468. });
  89469. animationRotationKeys.push({
  89470. frame: 6,
  89471. value: target
  89472. });
  89473. animationRotation.setKeys(animationRotationKeys);
  89474. animationRotation.setEasingFunction(this._circleEase);
  89475. this.currentVRCamera.animations.push(animationRotation);
  89476. this._postProcessMove.animations = [];
  89477. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89478. var vignetteWeightKeys = [];
  89479. vignetteWeightKeys.push({
  89480. frame: 0,
  89481. value: 0
  89482. });
  89483. vignetteWeightKeys.push({
  89484. frame: 3,
  89485. value: 4
  89486. });
  89487. vignetteWeightKeys.push({
  89488. frame: 6,
  89489. value: 0
  89490. });
  89491. animationPP.setKeys(vignetteWeightKeys);
  89492. animationPP.setEasingFunction(this._circleEase);
  89493. this._postProcessMove.animations.push(animationPP);
  89494. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89495. var vignetteStretchKeys = [];
  89496. vignetteStretchKeys.push({
  89497. frame: 0,
  89498. value: 0
  89499. });
  89500. vignetteStretchKeys.push({
  89501. frame: 3,
  89502. value: 10
  89503. });
  89504. vignetteStretchKeys.push({
  89505. frame: 6,
  89506. value: 0
  89507. });
  89508. animationPP2.setKeys(vignetteStretchKeys);
  89509. animationPP2.setEasingFunction(this._circleEase);
  89510. this._postProcessMove.animations.push(animationPP2);
  89511. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89512. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89513. this._postProcessMove.samples = 4;
  89514. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89515. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  89516. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89517. });
  89518. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  89519. };
  89520. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  89521. if (hit.pickedPoint) {
  89522. if (gazer._teleportationRequestInitiated) {
  89523. this._displayTeleportationTarget();
  89524. this._haloCenter.copyFrom(hit.pickedPoint);
  89525. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  89526. }
  89527. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  89528. if (pickNormal) {
  89529. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89530. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89531. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  89532. }
  89533. this._teleportationTarget.position.y += 0.1;
  89534. }
  89535. };
  89536. VRExperienceHelper.prototype._teleportCamera = function (location) {
  89537. var _this = this;
  89538. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89539. return;
  89540. }
  89541. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  89542. // offset of the headset from the anchor.
  89543. if (this.webVRCamera.leftCamera) {
  89544. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  89545. this._workingVector.subtractInPlace(this.webVRCamera.position);
  89546. location.subtractToRef(this._workingVector, this._workingVector);
  89547. }
  89548. else {
  89549. this._workingVector.copyFrom(location);
  89550. }
  89551. // Add height to account for user's height offset
  89552. if (this.isInVRMode) {
  89553. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  89554. }
  89555. else {
  89556. this._workingVector.y += this._defaultHeight;
  89557. }
  89558. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  89559. // Create animation from the camera's position to the new location
  89560. this.currentVRCamera.animations = [];
  89561. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89562. var animationCameraTeleportationKeys = [{
  89563. frame: 0,
  89564. value: this.currentVRCamera.position
  89565. },
  89566. {
  89567. frame: 11,
  89568. value: this._workingVector
  89569. }
  89570. ];
  89571. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  89572. animationCameraTeleportation.setEasingFunction(this._circleEase);
  89573. this.currentVRCamera.animations.push(animationCameraTeleportation);
  89574. this._postProcessMove.animations = [];
  89575. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89576. var vignetteWeightKeys = [];
  89577. vignetteWeightKeys.push({
  89578. frame: 0,
  89579. value: 0
  89580. });
  89581. vignetteWeightKeys.push({
  89582. frame: 5,
  89583. value: 8
  89584. });
  89585. vignetteWeightKeys.push({
  89586. frame: 11,
  89587. value: 0
  89588. });
  89589. animationPP.setKeys(vignetteWeightKeys);
  89590. this._postProcessMove.animations.push(animationPP);
  89591. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89592. var vignetteStretchKeys = [];
  89593. vignetteStretchKeys.push({
  89594. frame: 0,
  89595. value: 0
  89596. });
  89597. vignetteStretchKeys.push({
  89598. frame: 5,
  89599. value: 10
  89600. });
  89601. vignetteStretchKeys.push({
  89602. frame: 11,
  89603. value: 0
  89604. });
  89605. animationPP2.setKeys(vignetteStretchKeys);
  89606. this._postProcessMove.animations.push(animationPP2);
  89607. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89608. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89609. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89610. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89611. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89612. });
  89613. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89614. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89615. });
  89616. this._hideTeleportationTarget();
  89617. };
  89618. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89619. if (normal) {
  89620. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89621. if (angle < Math.PI / 2) {
  89622. normal.scaleInPlace(-1);
  89623. }
  89624. }
  89625. return normal;
  89626. };
  89627. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89628. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89629. return;
  89630. }
  89631. var ray = gazer._getForwardRay(this._rayLength);
  89632. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89633. if (hit) {
  89634. // Populate the contrllers mesh that can be used for drag/drop
  89635. if (gazer._laserPointer) {
  89636. hit.originMesh = gazer._laserPointer.parent;
  89637. }
  89638. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  89639. }
  89640. gazer._currentHit = hit;
  89641. // Moving the gazeTracker on the mesh face targetted
  89642. if (hit && hit.pickedPoint) {
  89643. if (this._displayGaze) {
  89644. var multiplier = 1;
  89645. gazer._gazeTracker.isVisible = true;
  89646. if (gazer._isActionableMesh) {
  89647. multiplier = 3;
  89648. }
  89649. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89650. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89651. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89652. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89653. // To avoid z-fighting
  89654. var deltaFighting = 0.002;
  89655. if (pickNormal) {
  89656. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89657. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89658. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89659. }
  89660. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89661. if (gazer._gazeTracker.position.x < 0) {
  89662. gazer._gazeTracker.position.x += deltaFighting;
  89663. }
  89664. else {
  89665. gazer._gazeTracker.position.x -= deltaFighting;
  89666. }
  89667. if (gazer._gazeTracker.position.y < 0) {
  89668. gazer._gazeTracker.position.y += deltaFighting;
  89669. }
  89670. else {
  89671. gazer._gazeTracker.position.y -= deltaFighting;
  89672. }
  89673. if (gazer._gazeTracker.position.z < 0) {
  89674. gazer._gazeTracker.position.z += deltaFighting;
  89675. }
  89676. else {
  89677. gazer._gazeTracker.position.z -= deltaFighting;
  89678. }
  89679. }
  89680. // Changing the size of the laser pointer based on the distance from the targetted point
  89681. gazer._updatePointerDistance(hit.distance);
  89682. }
  89683. else {
  89684. gazer._updatePointerDistance();
  89685. gazer._gazeTracker.isVisible = false;
  89686. }
  89687. if (hit && hit.pickedMesh) {
  89688. // The object selected is the floor, we're in a teleportation scenario
  89689. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89690. // Moving the teleportation area to this targetted point
  89691. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89692. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89693. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89694. }
  89695. gazer._currentMeshSelected = null;
  89696. if (gazer._teleportationRequestInitiated) {
  89697. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89698. }
  89699. return;
  89700. }
  89701. // If not, we're in a selection scenario
  89702. //this._teleportationAllowed = false;
  89703. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89704. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89705. this.onNewMeshPicked.notifyObservers(hit);
  89706. gazer._currentMeshSelected = hit.pickedMesh;
  89707. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89708. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89709. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89710. gazer._isActionableMesh = true;
  89711. }
  89712. else {
  89713. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89714. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89715. gazer._isActionableMesh = false;
  89716. }
  89717. try {
  89718. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89719. }
  89720. catch (err) {
  89721. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89722. }
  89723. }
  89724. else {
  89725. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89726. gazer._currentMeshSelected = null;
  89727. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89728. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89729. }
  89730. }
  89731. }
  89732. else {
  89733. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89734. gazer._currentMeshSelected = null;
  89735. //this._teleportationAllowed = false;
  89736. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89737. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89738. }
  89739. };
  89740. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89741. if (mesh) {
  89742. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89743. }
  89744. };
  89745. /**
  89746. * Sets the color of the laser ray from the vr controllers.
  89747. * @param color new color for the ray.
  89748. */
  89749. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89750. if (this.leftController) {
  89751. this.leftController._setLaserPointerColor(color);
  89752. }
  89753. if (this.rightController) {
  89754. this.rightController._setLaserPointerColor(color);
  89755. }
  89756. };
  89757. /**
  89758. * Sets the color of the ray from the vr headsets gaze.
  89759. * @param color new color for the ray.
  89760. */
  89761. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89762. if (!this._cameraGazer._gazeTracker.material) {
  89763. return;
  89764. }
  89765. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89766. if (this.leftController) {
  89767. this.leftController._gazeTracker.material.emissiveColor = color;
  89768. }
  89769. if (this.rightController) {
  89770. this.rightController._gazeTracker.material.emissiveColor = color;
  89771. }
  89772. };
  89773. /**
  89774. * Exits VR and disposes of the vr experience helper
  89775. */
  89776. VRExperienceHelper.prototype.dispose = function () {
  89777. if (this.isInVRMode) {
  89778. this.exitVR();
  89779. }
  89780. if (this._postProcessMove) {
  89781. this._postProcessMove.dispose();
  89782. }
  89783. if (this._webVRCamera) {
  89784. this._webVRCamera.dispose();
  89785. }
  89786. if (this._vrDeviceOrientationCamera) {
  89787. this._vrDeviceOrientationCamera.dispose();
  89788. }
  89789. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89790. document.body.removeChild(this._btnVR);
  89791. }
  89792. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89793. this._deviceOrientationCamera.dispose();
  89794. }
  89795. if (this._cameraGazer) {
  89796. this._cameraGazer.dispose();
  89797. }
  89798. if (this.leftController) {
  89799. this.leftController.dispose();
  89800. }
  89801. if (this.rightController) {
  89802. this.rightController.dispose();
  89803. }
  89804. if (this._teleportationTarget) {
  89805. this._teleportationTarget.dispose();
  89806. }
  89807. this._floorMeshesCollection = [];
  89808. document.removeEventListener("keydown", this._onKeyDown);
  89809. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89810. window.removeEventListener("resize", this._onResize);
  89811. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89812. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89813. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89814. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89815. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89816. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89817. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89818. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89819. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89820. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89821. this._scene.unregisterBeforeRender(this.beforeRender);
  89822. };
  89823. /**
  89824. * Gets the name of the VRExperienceHelper class
  89825. * @returns "VRExperienceHelper"
  89826. */
  89827. VRExperienceHelper.prototype.getClassName = function () {
  89828. return "VRExperienceHelper";
  89829. };
  89830. return VRExperienceHelper;
  89831. }());
  89832. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89833. })(BABYLON || (BABYLON = {}));
  89834. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89835. // Mainly based on these 2 articles :
  89836. // 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
  89837. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89838. var BABYLON;
  89839. (function (BABYLON) {
  89840. /**
  89841. * Defines the potential axis of a Joystick
  89842. */
  89843. var JoystickAxis;
  89844. (function (JoystickAxis) {
  89845. /** X axis */
  89846. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89847. /** Y axis */
  89848. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89849. /** Z axis */
  89850. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89851. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89852. /**
  89853. * Class used to define virtual joystick (used in touch mode)
  89854. */
  89855. var VirtualJoystick = /** @class */ (function () {
  89856. /**
  89857. * Creates a new virtual joystick
  89858. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89859. */
  89860. function VirtualJoystick(leftJoystick) {
  89861. var _this = this;
  89862. if (leftJoystick) {
  89863. this._leftJoystick = true;
  89864. }
  89865. else {
  89866. this._leftJoystick = false;
  89867. }
  89868. VirtualJoystick._globalJoystickIndex++;
  89869. // By default left & right arrow keys are moving the X
  89870. // and up & down keys are moving the Y
  89871. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89872. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89873. this.reverseLeftRight = false;
  89874. this.reverseUpDown = false;
  89875. // collections of pointers
  89876. this._touches = new BABYLON.StringDictionary();
  89877. this.deltaPosition = BABYLON.Vector3.Zero();
  89878. this._joystickSensibility = 25;
  89879. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89880. this._onResize = function (evt) {
  89881. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89882. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89883. if (VirtualJoystick.vjCanvas) {
  89884. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89885. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89886. }
  89887. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89888. };
  89889. // injecting a canvas element on top of the canvas 3D game
  89890. if (!VirtualJoystick.vjCanvas) {
  89891. window.addEventListener("resize", this._onResize, false);
  89892. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89893. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89894. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89895. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89896. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89897. VirtualJoystick.vjCanvas.style.width = "100%";
  89898. VirtualJoystick.vjCanvas.style.height = "100%";
  89899. VirtualJoystick.vjCanvas.style.position = "absolute";
  89900. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89901. VirtualJoystick.vjCanvas.style.top = "0px";
  89902. VirtualJoystick.vjCanvas.style.left = "0px";
  89903. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89904. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89905. // Support for jQuery PEP polyfill
  89906. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89907. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89908. if (!context) {
  89909. throw new Error("Unable to create canvas for virtual joystick");
  89910. }
  89911. VirtualJoystick.vjCanvasContext = context;
  89912. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89913. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89914. document.body.appendChild(VirtualJoystick.vjCanvas);
  89915. }
  89916. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89917. this.pressed = false;
  89918. // default joystick color
  89919. this._joystickColor = "cyan";
  89920. this._joystickPointerID = -1;
  89921. // current joystick position
  89922. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89923. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89924. // origin joystick position
  89925. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89926. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89927. this._onPointerDownHandlerRef = function (evt) {
  89928. _this._onPointerDown(evt);
  89929. };
  89930. this._onPointerMoveHandlerRef = function (evt) {
  89931. _this._onPointerMove(evt);
  89932. };
  89933. this._onPointerUpHandlerRef = function (evt) {
  89934. _this._onPointerUp(evt);
  89935. };
  89936. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89937. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89938. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89939. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89940. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89941. evt.preventDefault(); // Disables system menu
  89942. }, false);
  89943. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89944. }
  89945. /**
  89946. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89947. * @param newJoystickSensibility defines the new sensibility
  89948. */
  89949. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89950. this._joystickSensibility = newJoystickSensibility;
  89951. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89952. };
  89953. VirtualJoystick.prototype._onPointerDown = function (e) {
  89954. var positionOnScreenCondition;
  89955. e.preventDefault();
  89956. if (this._leftJoystick === true) {
  89957. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89958. }
  89959. else {
  89960. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89961. }
  89962. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89963. // First contact will be dedicated to the virtual joystick
  89964. this._joystickPointerID = e.pointerId;
  89965. this._joystickPointerStartPos.x = e.clientX;
  89966. this._joystickPointerStartPos.y = e.clientY;
  89967. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89968. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89969. this._deltaJoystickVector.x = 0;
  89970. this._deltaJoystickVector.y = 0;
  89971. this.pressed = true;
  89972. this._touches.add(e.pointerId.toString(), e);
  89973. }
  89974. else {
  89975. // You can only trigger the action buttons with a joystick declared
  89976. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89977. this._action();
  89978. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89979. }
  89980. }
  89981. };
  89982. VirtualJoystick.prototype._onPointerMove = function (e) {
  89983. // If the current pointer is the one associated to the joystick (first touch contact)
  89984. if (this._joystickPointerID == e.pointerId) {
  89985. this._joystickPointerPos.x = e.clientX;
  89986. this._joystickPointerPos.y = e.clientY;
  89987. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89988. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89989. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89990. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89991. switch (this._axisTargetedByLeftAndRight) {
  89992. case JoystickAxis.X:
  89993. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89994. break;
  89995. case JoystickAxis.Y:
  89996. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89997. break;
  89998. case JoystickAxis.Z:
  89999. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  90000. break;
  90001. }
  90002. var directionUpDown = this.reverseUpDown ? 1 : -1;
  90003. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  90004. switch (this._axisTargetedByUpAndDown) {
  90005. case JoystickAxis.X:
  90006. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  90007. break;
  90008. case JoystickAxis.Y:
  90009. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  90010. break;
  90011. case JoystickAxis.Z:
  90012. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  90013. break;
  90014. }
  90015. }
  90016. else {
  90017. var data = this._touches.get(e.pointerId.toString());
  90018. if (data) {
  90019. data.x = e.clientX;
  90020. data.y = e.clientY;
  90021. }
  90022. }
  90023. };
  90024. VirtualJoystick.prototype._onPointerUp = function (e) {
  90025. if (this._joystickPointerID == e.pointerId) {
  90026. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  90027. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  90028. this._joystickPointerID = -1;
  90029. this.pressed = false;
  90030. }
  90031. else {
  90032. var touch = this._touches.get(e.pointerId.toString());
  90033. if (touch) {
  90034. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90035. }
  90036. }
  90037. this._deltaJoystickVector.x = 0;
  90038. this._deltaJoystickVector.y = 0;
  90039. this._touches.remove(e.pointerId.toString());
  90040. };
  90041. /**
  90042. * Change the color of the virtual joystick
  90043. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  90044. */
  90045. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  90046. this._joystickColor = newColor;
  90047. };
  90048. /**
  90049. * Defines a callback to call when the joystick is touched
  90050. * @param action defines the callback
  90051. */
  90052. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  90053. this._action = action;
  90054. };
  90055. /**
  90056. * Defines which axis you'd like to control for left & right
  90057. * @param axis defines the axis to use
  90058. */
  90059. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  90060. switch (axis) {
  90061. case JoystickAxis.X:
  90062. case JoystickAxis.Y:
  90063. case JoystickAxis.Z:
  90064. this._axisTargetedByLeftAndRight = axis;
  90065. break;
  90066. default:
  90067. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  90068. break;
  90069. }
  90070. };
  90071. /**
  90072. * Defines which axis you'd like to control for up & down
  90073. * @param axis defines the axis to use
  90074. */
  90075. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  90076. switch (axis) {
  90077. case JoystickAxis.X:
  90078. case JoystickAxis.Y:
  90079. case JoystickAxis.Z:
  90080. this._axisTargetedByUpAndDown = axis;
  90081. break;
  90082. default:
  90083. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  90084. break;
  90085. }
  90086. };
  90087. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  90088. var _this = this;
  90089. if (this.pressed) {
  90090. this._touches.forEach(function (key, touch) {
  90091. if (touch.pointerId === _this._joystickPointerID) {
  90092. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  90093. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  90094. VirtualJoystick.vjCanvasContext.beginPath();
  90095. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90096. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90097. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  90098. VirtualJoystick.vjCanvasContext.stroke();
  90099. VirtualJoystick.vjCanvasContext.closePath();
  90100. VirtualJoystick.vjCanvasContext.beginPath();
  90101. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90102. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  90103. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  90104. VirtualJoystick.vjCanvasContext.stroke();
  90105. VirtualJoystick.vjCanvasContext.closePath();
  90106. VirtualJoystick.vjCanvasContext.beginPath();
  90107. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90108. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  90109. VirtualJoystick.vjCanvasContext.stroke();
  90110. VirtualJoystick.vjCanvasContext.closePath();
  90111. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  90112. }
  90113. else {
  90114. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90115. VirtualJoystick.vjCanvasContext.beginPath();
  90116. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  90117. VirtualJoystick.vjCanvasContext.beginPath();
  90118. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  90119. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90120. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  90121. VirtualJoystick.vjCanvasContext.stroke();
  90122. VirtualJoystick.vjCanvasContext.closePath();
  90123. touch.prevX = touch.x;
  90124. touch.prevY = touch.y;
  90125. }
  90126. ;
  90127. });
  90128. }
  90129. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  90130. };
  90131. /**
  90132. * Release internal HTML canvas
  90133. */
  90134. VirtualJoystick.prototype.releaseCanvas = function () {
  90135. if (VirtualJoystick.vjCanvas) {
  90136. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  90137. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  90138. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  90139. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  90140. window.removeEventListener("resize", this._onResize);
  90141. document.body.removeChild(VirtualJoystick.vjCanvas);
  90142. VirtualJoystick.vjCanvas = null;
  90143. }
  90144. };
  90145. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  90146. VirtualJoystick._globalJoystickIndex = 0;
  90147. return VirtualJoystick;
  90148. }());
  90149. BABYLON.VirtualJoystick = VirtualJoystick;
  90150. })(BABYLON || (BABYLON = {}));
  90151. //# sourceMappingURL=babylon.virtualJoystick.js.map
  90152. var BABYLON;
  90153. (function (BABYLON) {
  90154. // We're mainly based on the logic defined into the FreeCamera code
  90155. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  90156. __extends(VirtualJoysticksCamera, _super);
  90157. function VirtualJoysticksCamera(name, position, scene) {
  90158. var _this = _super.call(this, name, position, scene) || this;
  90159. _this.inputs.addVirtualJoystick();
  90160. return _this;
  90161. }
  90162. VirtualJoysticksCamera.prototype.getClassName = function () {
  90163. return "VirtualJoysticksCamera";
  90164. };
  90165. return VirtualJoysticksCamera;
  90166. }(BABYLON.FreeCamera));
  90167. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  90168. })(BABYLON || (BABYLON = {}));
  90169. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  90170. var BABYLON;
  90171. (function (BABYLON) {
  90172. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  90173. function FreeCameraVirtualJoystickInput() {
  90174. }
  90175. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  90176. return this._leftjoystick;
  90177. };
  90178. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  90179. return this._rightjoystick;
  90180. };
  90181. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  90182. if (this._leftjoystick) {
  90183. var camera = this.camera;
  90184. var speed = camera._computeLocalCameraSpeed() * 50;
  90185. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  90186. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  90187. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  90188. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  90189. if (!this._leftjoystick.pressed) {
  90190. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  90191. }
  90192. if (!this._rightjoystick.pressed) {
  90193. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  90194. }
  90195. }
  90196. };
  90197. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  90198. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  90199. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  90200. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  90201. this._leftjoystick.setJoystickSensibility(0.15);
  90202. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  90203. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  90204. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  90205. this._rightjoystick.reverseUpDown = true;
  90206. this._rightjoystick.setJoystickSensibility(0.05);
  90207. this._rightjoystick.setJoystickColor("yellow");
  90208. };
  90209. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  90210. this._leftjoystick.releaseCanvas();
  90211. this._rightjoystick.releaseCanvas();
  90212. };
  90213. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  90214. return "FreeCameraVirtualJoystickInput";
  90215. };
  90216. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  90217. return "virtualJoystick";
  90218. };
  90219. return FreeCameraVirtualJoystickInput;
  90220. }());
  90221. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  90222. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  90223. })(BABYLON || (BABYLON = {}));
  90224. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  90225. var BABYLON;
  90226. (function (BABYLON) {
  90227. var SimplificationSettings = /** @class */ (function () {
  90228. function SimplificationSettings(quality, distance, optimizeMesh) {
  90229. this.quality = quality;
  90230. this.distance = distance;
  90231. this.optimizeMesh = optimizeMesh;
  90232. }
  90233. return SimplificationSettings;
  90234. }());
  90235. BABYLON.SimplificationSettings = SimplificationSettings;
  90236. var SimplificationQueue = /** @class */ (function () {
  90237. function SimplificationQueue() {
  90238. this.running = false;
  90239. this._simplificationArray = [];
  90240. }
  90241. SimplificationQueue.prototype.addTask = function (task) {
  90242. this._simplificationArray.push(task);
  90243. };
  90244. SimplificationQueue.prototype.executeNext = function () {
  90245. var task = this._simplificationArray.pop();
  90246. if (task) {
  90247. this.running = true;
  90248. this.runSimplification(task);
  90249. }
  90250. else {
  90251. this.running = false;
  90252. }
  90253. };
  90254. SimplificationQueue.prototype.runSimplification = function (task) {
  90255. var _this = this;
  90256. if (task.parallelProcessing) {
  90257. //parallel simplifier
  90258. task.settings.forEach(function (setting) {
  90259. var simplifier = _this.getSimplifier(task);
  90260. simplifier.simplify(setting, function (newMesh) {
  90261. task.mesh.addLODLevel(setting.distance, newMesh);
  90262. newMesh.isVisible = true;
  90263. //check if it is the last
  90264. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  90265. //all done, run the success callback.
  90266. task.successCallback();
  90267. }
  90268. _this.executeNext();
  90269. });
  90270. });
  90271. }
  90272. else {
  90273. //single simplifier.
  90274. var simplifier = this.getSimplifier(task);
  90275. var runDecimation = function (setting, callback) {
  90276. simplifier.simplify(setting, function (newMesh) {
  90277. task.mesh.addLODLevel(setting.distance, newMesh);
  90278. newMesh.isVisible = true;
  90279. //run the next quality level
  90280. callback();
  90281. });
  90282. };
  90283. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  90284. runDecimation(task.settings[loop.index], function () {
  90285. loop.executeNext();
  90286. });
  90287. }, function () {
  90288. //execution ended, run the success callback.
  90289. if (task.successCallback) {
  90290. task.successCallback();
  90291. }
  90292. _this.executeNext();
  90293. });
  90294. }
  90295. };
  90296. SimplificationQueue.prototype.getSimplifier = function (task) {
  90297. switch (task.simplificationType) {
  90298. case SimplificationType.QUADRATIC:
  90299. default:
  90300. return new QuadraticErrorSimplification(task.mesh);
  90301. }
  90302. };
  90303. return SimplificationQueue;
  90304. }());
  90305. BABYLON.SimplificationQueue = SimplificationQueue;
  90306. /**
  90307. * The implemented types of simplification
  90308. * At the moment only Quadratic Error Decimation is implemented
  90309. */
  90310. var SimplificationType;
  90311. (function (SimplificationType) {
  90312. /** Quadratic error decimation */
  90313. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  90314. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  90315. var DecimationTriangle = /** @class */ (function () {
  90316. function DecimationTriangle(vertices) {
  90317. this.vertices = vertices;
  90318. this.error = new Array(4);
  90319. this.deleted = false;
  90320. this.isDirty = false;
  90321. this.deletePending = false;
  90322. this.borderFactor = 0;
  90323. }
  90324. return DecimationTriangle;
  90325. }());
  90326. BABYLON.DecimationTriangle = DecimationTriangle;
  90327. var DecimationVertex = /** @class */ (function () {
  90328. function DecimationVertex(position, id) {
  90329. this.position = position;
  90330. this.id = id;
  90331. this.isBorder = true;
  90332. this.q = new QuadraticMatrix();
  90333. this.triangleCount = 0;
  90334. this.triangleStart = 0;
  90335. this.originalOffsets = [];
  90336. }
  90337. DecimationVertex.prototype.updatePosition = function (newPosition) {
  90338. this.position.copyFrom(newPosition);
  90339. };
  90340. return DecimationVertex;
  90341. }());
  90342. BABYLON.DecimationVertex = DecimationVertex;
  90343. var QuadraticMatrix = /** @class */ (function () {
  90344. function QuadraticMatrix(data) {
  90345. this.data = new Array(10);
  90346. for (var i = 0; i < 10; ++i) {
  90347. if (data && data[i]) {
  90348. this.data[i] = data[i];
  90349. }
  90350. else {
  90351. this.data[i] = 0;
  90352. }
  90353. }
  90354. }
  90355. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  90356. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  90357. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  90358. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  90359. return det;
  90360. };
  90361. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  90362. for (var i = 0; i < 10; ++i) {
  90363. this.data[i] += matrix.data[i];
  90364. }
  90365. };
  90366. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  90367. for (var i = 0; i < 10; ++i) {
  90368. this.data[i] += data[i];
  90369. }
  90370. };
  90371. QuadraticMatrix.prototype.add = function (matrix) {
  90372. var m = new QuadraticMatrix();
  90373. for (var i = 0; i < 10; ++i) {
  90374. m.data[i] = this.data[i] + matrix.data[i];
  90375. }
  90376. return m;
  90377. };
  90378. QuadraticMatrix.FromData = function (a, b, c, d) {
  90379. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  90380. };
  90381. //returning an array to avoid garbage collection
  90382. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  90383. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  90384. };
  90385. return QuadraticMatrix;
  90386. }());
  90387. BABYLON.QuadraticMatrix = QuadraticMatrix;
  90388. var Reference = /** @class */ (function () {
  90389. function Reference(vertexId, triangleId) {
  90390. this.vertexId = vertexId;
  90391. this.triangleId = triangleId;
  90392. }
  90393. return Reference;
  90394. }());
  90395. BABYLON.Reference = Reference;
  90396. /**
  90397. * An implementation of the Quadratic Error simplification algorithm.
  90398. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  90399. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  90400. * @author RaananW
  90401. */
  90402. var QuadraticErrorSimplification = /** @class */ (function () {
  90403. function QuadraticErrorSimplification(_mesh) {
  90404. this._mesh = _mesh;
  90405. this.syncIterations = 5000;
  90406. this.aggressiveness = 7;
  90407. this.decimationIterations = 100;
  90408. this.boundingBoxEpsilon = BABYLON.Epsilon;
  90409. }
  90410. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  90411. var _this = this;
  90412. this.initDecimatedMesh();
  90413. //iterating through the submeshes array, one after the other.
  90414. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  90415. _this.initWithMesh(loop.index, function () {
  90416. _this.runDecimation(settings, loop.index, function () {
  90417. loop.executeNext();
  90418. });
  90419. }, settings.optimizeMesh);
  90420. }, function () {
  90421. setTimeout(function () {
  90422. successCallback(_this._reconstructedMesh);
  90423. }, 0);
  90424. });
  90425. };
  90426. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  90427. var _this = this;
  90428. var targetCount = ~~(this.triangles.length * settings.quality);
  90429. var deletedTriangles = 0;
  90430. var triangleCount = this.triangles.length;
  90431. var iterationFunction = function (iteration, callback) {
  90432. setTimeout(function () {
  90433. if (iteration % 5 === 0) {
  90434. _this.updateMesh(iteration === 0);
  90435. }
  90436. for (var i = 0; i < _this.triangles.length; ++i) {
  90437. _this.triangles[i].isDirty = false;
  90438. }
  90439. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  90440. var trianglesIterator = function (i) {
  90441. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  90442. var t = _this.triangles[tIdx];
  90443. if (!t)
  90444. return;
  90445. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  90446. return;
  90447. }
  90448. for (var j = 0; j < 3; ++j) {
  90449. if (t.error[j] < threshold) {
  90450. var deleted0 = [];
  90451. var deleted1 = [];
  90452. var v0 = t.vertices[j];
  90453. var v1 = t.vertices[(j + 1) % 3];
  90454. if (v0.isBorder || v1.isBorder)
  90455. continue;
  90456. var p = BABYLON.Vector3.Zero();
  90457. var n = BABYLON.Vector3.Zero();
  90458. var uv = BABYLON.Vector2.Zero();
  90459. var color = new BABYLON.Color4(0, 0, 0, 1);
  90460. _this.calculateError(v0, v1, p, n, uv, color);
  90461. var delTr = new Array();
  90462. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  90463. continue;
  90464. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  90465. continue;
  90466. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  90467. continue;
  90468. var uniqueArray = new Array();
  90469. delTr.forEach(function (deletedT) {
  90470. if (uniqueArray.indexOf(deletedT) === -1) {
  90471. deletedT.deletePending = true;
  90472. uniqueArray.push(deletedT);
  90473. }
  90474. });
  90475. if (uniqueArray.length % 2 !== 0) {
  90476. continue;
  90477. }
  90478. v0.q = v1.q.add(v0.q);
  90479. v0.updatePosition(p);
  90480. var tStart = _this.references.length;
  90481. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  90482. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  90483. var tCount = _this.references.length - tStart;
  90484. if (tCount <= v0.triangleCount) {
  90485. if (tCount) {
  90486. for (var c = 0; c < tCount; c++) {
  90487. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  90488. }
  90489. }
  90490. }
  90491. else {
  90492. v0.triangleStart = tStart;
  90493. }
  90494. v0.triangleCount = tCount;
  90495. break;
  90496. }
  90497. }
  90498. };
  90499. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  90500. }, 0);
  90501. };
  90502. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  90503. if (triangleCount - deletedTriangles <= targetCount)
  90504. loop.breakLoop();
  90505. else {
  90506. iterationFunction(loop.index, function () {
  90507. loop.executeNext();
  90508. });
  90509. }
  90510. }, function () {
  90511. setTimeout(function () {
  90512. //reconstruct this part of the mesh
  90513. _this.reconstructMesh(submeshIndex);
  90514. successCallback();
  90515. }, 0);
  90516. });
  90517. };
  90518. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  90519. var _this = this;
  90520. this.vertices = [];
  90521. this.triangles = [];
  90522. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90523. var indices = this._mesh.getIndices();
  90524. var submesh = this._mesh.subMeshes[submeshIndex];
  90525. var findInVertices = function (positionToSearch) {
  90526. if (optimizeMesh) {
  90527. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  90528. if (_this.vertices[ii].position.equals(positionToSearch)) {
  90529. return _this.vertices[ii];
  90530. }
  90531. }
  90532. }
  90533. return null;
  90534. };
  90535. var vertexReferences = [];
  90536. var vertexInit = function (i) {
  90537. if (!positionData) {
  90538. return;
  90539. }
  90540. var offset = i + submesh.verticesStart;
  90541. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  90542. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  90543. vertex.originalOffsets.push(offset);
  90544. if (vertex.id === _this.vertices.length) {
  90545. _this.vertices.push(vertex);
  90546. }
  90547. vertexReferences.push(vertex.id);
  90548. };
  90549. //var totalVertices = mesh.getTotalVertices();
  90550. var totalVertices = submesh.verticesCount;
  90551. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  90552. var indicesInit = function (i) {
  90553. if (!indices) {
  90554. return;
  90555. }
  90556. var offset = (submesh.indexStart / 3) + i;
  90557. var pos = (offset * 3);
  90558. var i0 = indices[pos + 0];
  90559. var i1 = indices[pos + 1];
  90560. var i2 = indices[pos + 2];
  90561. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  90562. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  90563. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  90564. var triangle = new DecimationTriangle([v0, v1, v2]);
  90565. triangle.originalOffset = pos;
  90566. _this.triangles.push(triangle);
  90567. };
  90568. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  90569. _this.init(callback);
  90570. });
  90571. });
  90572. };
  90573. QuadraticErrorSimplification.prototype.init = function (callback) {
  90574. var _this = this;
  90575. var triangleInit1 = function (i) {
  90576. var t = _this.triangles[i];
  90577. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  90578. for (var j = 0; j < 3; j++) {
  90579. 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))));
  90580. }
  90581. };
  90582. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  90583. var triangleInit2 = function (i) {
  90584. var t = _this.triangles[i];
  90585. for (var j = 0; j < 3; ++j) {
  90586. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  90587. }
  90588. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90589. };
  90590. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  90591. callback();
  90592. });
  90593. });
  90594. };
  90595. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  90596. var newTriangles = [];
  90597. var i;
  90598. for (i = 0; i < this.vertices.length; ++i) {
  90599. this.vertices[i].triangleCount = 0;
  90600. }
  90601. var t;
  90602. var j;
  90603. for (i = 0; i < this.triangles.length; ++i) {
  90604. if (!this.triangles[i].deleted) {
  90605. t = this.triangles[i];
  90606. for (j = 0; j < 3; ++j) {
  90607. t.vertices[j].triangleCount = 1;
  90608. }
  90609. newTriangles.push(t);
  90610. }
  90611. }
  90612. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90613. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90614. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90615. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90616. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90617. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90618. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90619. var vertexCount = 0;
  90620. for (i = 0; i < this.vertices.length; ++i) {
  90621. var vertex = this.vertices[i];
  90622. vertex.id = vertexCount;
  90623. if (vertex.triangleCount) {
  90624. vertex.originalOffsets.forEach(function (originalOffset) {
  90625. if (!normalData) {
  90626. return;
  90627. }
  90628. newPositionData.push(vertex.position.x);
  90629. newPositionData.push(vertex.position.y);
  90630. newPositionData.push(vertex.position.z);
  90631. newNormalData.push(normalData[originalOffset * 3]);
  90632. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90633. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90634. if (uvs && uvs.length) {
  90635. newUVsData.push(uvs[(originalOffset * 2)]);
  90636. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90637. }
  90638. else if (colorsData && colorsData.length) {
  90639. newColorsData.push(colorsData[(originalOffset * 4)]);
  90640. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90641. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90642. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90643. }
  90644. ++vertexCount;
  90645. });
  90646. }
  90647. }
  90648. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90649. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90650. var submeshesArray = this._reconstructedMesh.subMeshes;
  90651. this._reconstructedMesh.subMeshes = [];
  90652. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90653. var originalIndices = this._mesh.getIndices();
  90654. for (i = 0; i < newTriangles.length; ++i) {
  90655. t = newTriangles[i]; //now get the new referencing point for each vertex
  90656. [0, 1, 2].forEach(function (idx) {
  90657. var id = originalIndices[t.originalOffset + idx];
  90658. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90659. if (offset < 0)
  90660. offset = 0;
  90661. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90662. });
  90663. }
  90664. //overwriting the old vertex buffers and indices.
  90665. this._reconstructedMesh.setIndices(newIndicesArray);
  90666. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90667. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90668. if (newUVsData.length > 0)
  90669. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90670. if (newColorsData.length > 0)
  90671. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90672. //create submesh
  90673. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90674. if (submeshIndex > 0) {
  90675. this._reconstructedMesh.subMeshes = [];
  90676. submeshesArray.forEach(function (submesh) {
  90677. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90678. });
  90679. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90680. }
  90681. };
  90682. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90683. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90684. this._reconstructedMesh.material = this._mesh.material;
  90685. this._reconstructedMesh.parent = this._mesh.parent;
  90686. this._reconstructedMesh.isVisible = false;
  90687. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90688. };
  90689. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90690. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90691. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90692. if (t.deleted)
  90693. continue;
  90694. var s = this.references[vertex1.triangleStart + i].vertexId;
  90695. var v1 = t.vertices[(s + 1) % 3];
  90696. var v2 = t.vertices[(s + 2) % 3];
  90697. if ((v1 === vertex2 || v2 === vertex2)) {
  90698. deletedArray[i] = true;
  90699. delTr.push(t);
  90700. continue;
  90701. }
  90702. var d1 = v1.position.subtract(point);
  90703. d1 = d1.normalize();
  90704. var d2 = v2.position.subtract(point);
  90705. d2 = d2.normalize();
  90706. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90707. return true;
  90708. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90709. deletedArray[i] = false;
  90710. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90711. return true;
  90712. }
  90713. return false;
  90714. };
  90715. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90716. var newDeleted = deletedTriangles;
  90717. for (var i = 0; i < vertex.triangleCount; ++i) {
  90718. var ref = this.references[vertex.triangleStart + i];
  90719. var t = this.triangles[ref.triangleId];
  90720. if (t.deleted)
  90721. continue;
  90722. if (deletedArray[i] && t.deletePending) {
  90723. t.deleted = true;
  90724. newDeleted++;
  90725. continue;
  90726. }
  90727. t.vertices[ref.vertexId] = origVertex;
  90728. t.isDirty = true;
  90729. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90730. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90731. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90732. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90733. this.references.push(ref);
  90734. }
  90735. return newDeleted;
  90736. };
  90737. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90738. for (var i = 0; i < this.vertices.length; ++i) {
  90739. var vCount = [];
  90740. var vId = [];
  90741. var v = this.vertices[i];
  90742. var j;
  90743. for (j = 0; j < v.triangleCount; ++j) {
  90744. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90745. for (var ii = 0; ii < 3; ii++) {
  90746. var ofs = 0;
  90747. var vv = triangle.vertices[ii];
  90748. while (ofs < vCount.length) {
  90749. if (vId[ofs] === vv.id)
  90750. break;
  90751. ++ofs;
  90752. }
  90753. if (ofs === vCount.length) {
  90754. vCount.push(1);
  90755. vId.push(vv.id);
  90756. }
  90757. else {
  90758. vCount[ofs]++;
  90759. }
  90760. }
  90761. }
  90762. for (j = 0; j < vCount.length; ++j) {
  90763. if (vCount[j] === 1) {
  90764. this.vertices[vId[j]].isBorder = true;
  90765. }
  90766. else {
  90767. this.vertices[vId[j]].isBorder = false;
  90768. }
  90769. }
  90770. }
  90771. };
  90772. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90773. if (identifyBorders === void 0) { identifyBorders = false; }
  90774. var i;
  90775. if (!identifyBorders) {
  90776. var newTrianglesVector = [];
  90777. for (i = 0; i < this.triangles.length; ++i) {
  90778. if (!this.triangles[i].deleted) {
  90779. newTrianglesVector.push(this.triangles[i]);
  90780. }
  90781. }
  90782. this.triangles = newTrianglesVector;
  90783. }
  90784. for (i = 0; i < this.vertices.length; ++i) {
  90785. this.vertices[i].triangleCount = 0;
  90786. this.vertices[i].triangleStart = 0;
  90787. }
  90788. var t;
  90789. var j;
  90790. var v;
  90791. for (i = 0; i < this.triangles.length; ++i) {
  90792. t = this.triangles[i];
  90793. for (j = 0; j < 3; ++j) {
  90794. v = t.vertices[j];
  90795. v.triangleCount++;
  90796. }
  90797. }
  90798. var tStart = 0;
  90799. for (i = 0; i < this.vertices.length; ++i) {
  90800. this.vertices[i].triangleStart = tStart;
  90801. tStart += this.vertices[i].triangleCount;
  90802. this.vertices[i].triangleCount = 0;
  90803. }
  90804. var newReferences = new Array(this.triangles.length * 3);
  90805. for (i = 0; i < this.triangles.length; ++i) {
  90806. t = this.triangles[i];
  90807. for (j = 0; j < 3; ++j) {
  90808. v = t.vertices[j];
  90809. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90810. v.triangleCount++;
  90811. }
  90812. }
  90813. this.references = newReferences;
  90814. if (identifyBorders) {
  90815. this.identifyBorder();
  90816. }
  90817. };
  90818. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90819. var x = point.x;
  90820. var y = point.y;
  90821. var z = point.z;
  90822. 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
  90823. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90824. };
  90825. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90826. var q = vertex1.q.add(vertex2.q);
  90827. var border = vertex1.isBorder && vertex2.isBorder;
  90828. var error = 0;
  90829. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90830. if (qDet !== 0 && !border) {
  90831. if (!pointResult) {
  90832. pointResult = BABYLON.Vector3.Zero();
  90833. }
  90834. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90835. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90836. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90837. error = this.vertexError(q, pointResult);
  90838. }
  90839. else {
  90840. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90841. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90842. var error1 = this.vertexError(q, vertex1.position);
  90843. var error2 = this.vertexError(q, vertex2.position);
  90844. var error3 = this.vertexError(q, p3);
  90845. error = Math.min(error1, error2, error3);
  90846. if (error === error1) {
  90847. if (pointResult) {
  90848. pointResult.copyFrom(vertex1.position);
  90849. }
  90850. }
  90851. else if (error === error2) {
  90852. if (pointResult) {
  90853. pointResult.copyFrom(vertex2.position);
  90854. }
  90855. }
  90856. else {
  90857. if (pointResult) {
  90858. pointResult.copyFrom(p3);
  90859. }
  90860. }
  90861. }
  90862. return error;
  90863. };
  90864. return QuadraticErrorSimplification;
  90865. }());
  90866. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90867. })(BABYLON || (BABYLON = {}));
  90868. //# sourceMappingURL=babylon.meshSimplification.js.map
  90869. var BABYLON;
  90870. (function (BABYLON) {
  90871. var MeshLODLevel = /** @class */ (function () {
  90872. function MeshLODLevel(distance, mesh) {
  90873. this.distance = distance;
  90874. this.mesh = mesh;
  90875. }
  90876. return MeshLODLevel;
  90877. }());
  90878. BABYLON.MeshLODLevel = MeshLODLevel;
  90879. })(BABYLON || (BABYLON = {}));
  90880. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90881. var BABYLON;
  90882. (function (BABYLON) {
  90883. /**
  90884. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90885. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90886. */
  90887. var SceneOptimization = /** @class */ (function () {
  90888. /**
  90889. * Creates the SceneOptimization object
  90890. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90891. * @param desc defines the description associated with the optimization
  90892. */
  90893. function SceneOptimization(
  90894. /**
  90895. * Defines the priority of this optimization (0 by default which means first in the list)
  90896. */
  90897. priority) {
  90898. if (priority === void 0) { priority = 0; }
  90899. this.priority = priority;
  90900. }
  90901. /**
  90902. * Gets a string describing the action executed by the current optimization
  90903. * @returns description string
  90904. */
  90905. SceneOptimization.prototype.getDescription = function () {
  90906. return "";
  90907. };
  90908. /**
  90909. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90910. * @param scene defines the current scene where to apply this optimization
  90911. * @param optimizer defines the current optimizer
  90912. * @returns true if everything that can be done was applied
  90913. */
  90914. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90915. return true;
  90916. };
  90917. ;
  90918. return SceneOptimization;
  90919. }());
  90920. BABYLON.SceneOptimization = SceneOptimization;
  90921. /**
  90922. * Defines an optimization used to reduce the size of render target textures
  90923. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90924. */
  90925. var TextureOptimization = /** @class */ (function (_super) {
  90926. __extends(TextureOptimization, _super);
  90927. /**
  90928. * Creates the TextureOptimization object
  90929. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90930. * @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
  90931. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90932. */
  90933. function TextureOptimization(
  90934. /**
  90935. * Defines the priority of this optimization (0 by default which means first in the list)
  90936. */
  90937. priority,
  90938. /**
  90939. * 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
  90940. */
  90941. maximumSize,
  90942. /**
  90943. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90944. */
  90945. step) {
  90946. if (priority === void 0) { priority = 0; }
  90947. if (maximumSize === void 0) { maximumSize = 1024; }
  90948. if (step === void 0) { step = 0.5; }
  90949. var _this = _super.call(this, priority) || this;
  90950. _this.priority = priority;
  90951. _this.maximumSize = maximumSize;
  90952. _this.step = step;
  90953. return _this;
  90954. }
  90955. /**
  90956. * Gets a string describing the action executed by the current optimization
  90957. * @returns description string
  90958. */
  90959. TextureOptimization.prototype.getDescription = function () {
  90960. return "Reducing render target texture size to " + this.maximumSize;
  90961. };
  90962. /**
  90963. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90964. * @param scene defines the current scene where to apply this optimization
  90965. * @param optimizer defines the current optimizer
  90966. * @returns true if everything that can be done was applied
  90967. */
  90968. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90969. var allDone = true;
  90970. for (var index = 0; index < scene.textures.length; index++) {
  90971. var texture = scene.textures[index];
  90972. if (!texture.canRescale || texture.getContext) {
  90973. continue;
  90974. }
  90975. var currentSize = texture.getSize();
  90976. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90977. if (maxDimension > this.maximumSize) {
  90978. texture.scale(this.step);
  90979. allDone = false;
  90980. }
  90981. }
  90982. return allDone;
  90983. };
  90984. return TextureOptimization;
  90985. }(SceneOptimization));
  90986. BABYLON.TextureOptimization = TextureOptimization;
  90987. /**
  90988. * Defines an optimization used to increase or decrease the rendering resolution
  90989. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90990. */
  90991. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90992. __extends(HardwareScalingOptimization, _super);
  90993. /**
  90994. * Creates the HardwareScalingOptimization object
  90995. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90996. * @param maximumScale defines the maximum scale to use (2 by default)
  90997. * @param step defines the step to use between two passes (0.5 by default)
  90998. */
  90999. function HardwareScalingOptimization(
  91000. /**
  91001. * Defines the priority of this optimization (0 by default which means first in the list)
  91002. */
  91003. priority,
  91004. /**
  91005. * Defines the maximum scale to use (2 by default)
  91006. */
  91007. maximumScale,
  91008. /**
  91009. * Defines the step to use between two passes (0.5 by default)
  91010. */
  91011. step) {
  91012. if (priority === void 0) { priority = 0; }
  91013. if (maximumScale === void 0) { maximumScale = 2; }
  91014. if (step === void 0) { step = 0.25; }
  91015. var _this = _super.call(this, priority) || this;
  91016. _this.priority = priority;
  91017. _this.maximumScale = maximumScale;
  91018. _this.step = step;
  91019. _this._currentScale = -1;
  91020. _this._directionOffset = 1;
  91021. return _this;
  91022. }
  91023. /**
  91024. * Gets a string describing the action executed by the current optimization
  91025. * @return description string
  91026. */
  91027. HardwareScalingOptimization.prototype.getDescription = function () {
  91028. return "Setting hardware scaling level to " + this._currentScale;
  91029. };
  91030. /**
  91031. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91032. * @param scene defines the current scene where to apply this optimization
  91033. * @param optimizer defines the current optimizer
  91034. * @returns true if everything that can be done was applied
  91035. */
  91036. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  91037. if (this._currentScale === -1) {
  91038. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  91039. if (this._currentScale > this.maximumScale) {
  91040. this._directionOffset = -1;
  91041. }
  91042. }
  91043. this._currentScale += this._directionOffset * this.step;
  91044. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  91045. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  91046. };
  91047. ;
  91048. return HardwareScalingOptimization;
  91049. }(SceneOptimization));
  91050. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  91051. /**
  91052. * Defines an optimization used to remove shadows
  91053. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91054. */
  91055. var ShadowsOptimization = /** @class */ (function (_super) {
  91056. __extends(ShadowsOptimization, _super);
  91057. function ShadowsOptimization() {
  91058. return _super !== null && _super.apply(this, arguments) || this;
  91059. }
  91060. /**
  91061. * Gets a string describing the action executed by the current optimization
  91062. * @return description string
  91063. */
  91064. ShadowsOptimization.prototype.getDescription = function () {
  91065. return "Turning shadows on/off";
  91066. };
  91067. /**
  91068. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91069. * @param scene defines the current scene where to apply this optimization
  91070. * @param optimizer defines the current optimizer
  91071. * @returns true if everything that can be done was applied
  91072. */
  91073. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  91074. scene.shadowsEnabled = optimizer.isInImprovementMode;
  91075. return true;
  91076. };
  91077. ;
  91078. return ShadowsOptimization;
  91079. }(SceneOptimization));
  91080. BABYLON.ShadowsOptimization = ShadowsOptimization;
  91081. /**
  91082. * Defines an optimization used to turn post-processes off
  91083. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91084. */
  91085. var PostProcessesOptimization = /** @class */ (function (_super) {
  91086. __extends(PostProcessesOptimization, _super);
  91087. function PostProcessesOptimization() {
  91088. return _super !== null && _super.apply(this, arguments) || this;
  91089. }
  91090. /**
  91091. * Gets a string describing the action executed by the current optimization
  91092. * @return description string
  91093. */
  91094. PostProcessesOptimization.prototype.getDescription = function () {
  91095. return "Turning post-processes on/off";
  91096. };
  91097. /**
  91098. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91099. * @param scene defines the current scene where to apply this optimization
  91100. * @param optimizer defines the current optimizer
  91101. * @returns true if everything that can be done was applied
  91102. */
  91103. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  91104. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  91105. return true;
  91106. };
  91107. ;
  91108. return PostProcessesOptimization;
  91109. }(SceneOptimization));
  91110. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  91111. /**
  91112. * Defines an optimization used to turn lens flares off
  91113. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91114. */
  91115. var LensFlaresOptimization = /** @class */ (function (_super) {
  91116. __extends(LensFlaresOptimization, _super);
  91117. function LensFlaresOptimization() {
  91118. return _super !== null && _super.apply(this, arguments) || this;
  91119. }
  91120. /**
  91121. * Gets a string describing the action executed by the current optimization
  91122. * @return description string
  91123. */
  91124. LensFlaresOptimization.prototype.getDescription = function () {
  91125. return "Turning lens flares on/off";
  91126. };
  91127. /**
  91128. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91129. * @param scene defines the current scene where to apply this optimization
  91130. * @param optimizer defines the current optimizer
  91131. * @returns true if everything that can be done was applied
  91132. */
  91133. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  91134. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  91135. return true;
  91136. };
  91137. ;
  91138. return LensFlaresOptimization;
  91139. }(SceneOptimization));
  91140. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  91141. /**
  91142. * Defines an optimization based on user defined callback.
  91143. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91144. */
  91145. var CustomOptimization = /** @class */ (function (_super) {
  91146. __extends(CustomOptimization, _super);
  91147. function CustomOptimization() {
  91148. return _super !== null && _super.apply(this, arguments) || this;
  91149. }
  91150. /**
  91151. * Gets a string describing the action executed by the current optimization
  91152. * @returns description string
  91153. */
  91154. CustomOptimization.prototype.getDescription = function () {
  91155. if (this.onGetDescription) {
  91156. return this.onGetDescription();
  91157. }
  91158. return "Running user defined callback";
  91159. };
  91160. /**
  91161. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91162. * @param scene defines the current scene where to apply this optimization
  91163. * @param optimizer defines the current optimizer
  91164. * @returns true if everything that can be done was applied
  91165. */
  91166. CustomOptimization.prototype.apply = function (scene, optimizer) {
  91167. if (this.onApply) {
  91168. return this.onApply(scene, optimizer);
  91169. }
  91170. return true;
  91171. };
  91172. ;
  91173. return CustomOptimization;
  91174. }(SceneOptimization));
  91175. BABYLON.CustomOptimization = CustomOptimization;
  91176. /**
  91177. * Defines an optimization used to turn particles off
  91178. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91179. */
  91180. var ParticlesOptimization = /** @class */ (function (_super) {
  91181. __extends(ParticlesOptimization, _super);
  91182. function ParticlesOptimization() {
  91183. return _super !== null && _super.apply(this, arguments) || this;
  91184. }
  91185. /**
  91186. * Gets a string describing the action executed by the current optimization
  91187. * @return description string
  91188. */
  91189. ParticlesOptimization.prototype.getDescription = function () {
  91190. return "Turning particles on/off";
  91191. };
  91192. /**
  91193. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91194. * @param scene defines the current scene where to apply this optimization
  91195. * @param optimizer defines the current optimizer
  91196. * @returns true if everything that can be done was applied
  91197. */
  91198. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  91199. scene.particlesEnabled = optimizer.isInImprovementMode;
  91200. return true;
  91201. };
  91202. ;
  91203. return ParticlesOptimization;
  91204. }(SceneOptimization));
  91205. BABYLON.ParticlesOptimization = ParticlesOptimization;
  91206. /**
  91207. * Defines an optimization used to turn render targets off
  91208. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91209. */
  91210. var RenderTargetsOptimization = /** @class */ (function (_super) {
  91211. __extends(RenderTargetsOptimization, _super);
  91212. function RenderTargetsOptimization() {
  91213. return _super !== null && _super.apply(this, arguments) || this;
  91214. }
  91215. /**
  91216. * Gets a string describing the action executed by the current optimization
  91217. * @return description string
  91218. */
  91219. RenderTargetsOptimization.prototype.getDescription = function () {
  91220. return "Turning render targets off";
  91221. };
  91222. /**
  91223. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91224. * @param scene defines the current scene where to apply this optimization
  91225. * @param optimizer defines the current optimizer
  91226. * @returns true if everything that can be done was applied
  91227. */
  91228. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  91229. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  91230. return true;
  91231. };
  91232. ;
  91233. return RenderTargetsOptimization;
  91234. }(SceneOptimization));
  91235. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  91236. /**
  91237. * Defines an optimization used to merge meshes with compatible materials
  91238. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91239. */
  91240. var MergeMeshesOptimization = /** @class */ (function (_super) {
  91241. __extends(MergeMeshesOptimization, _super);
  91242. function MergeMeshesOptimization() {
  91243. var _this = _super !== null && _super.apply(this, arguments) || this;
  91244. _this._canBeMerged = function (abstractMesh) {
  91245. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  91246. return false;
  91247. }
  91248. var mesh = abstractMesh;
  91249. if (!mesh.isVisible || !mesh.isEnabled()) {
  91250. return false;
  91251. }
  91252. if (mesh.instances.length > 0) {
  91253. return false;
  91254. }
  91255. if (mesh.skeleton || mesh.hasLODLevels) {
  91256. return false;
  91257. }
  91258. if (mesh.parent) {
  91259. return false;
  91260. }
  91261. return true;
  91262. };
  91263. return _this;
  91264. }
  91265. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  91266. /**
  91267. * Gets or sets a boolean which defines if optimization octree has to be updated
  91268. */
  91269. get: function () {
  91270. return MergeMeshesOptimization._UpdateSelectionTree;
  91271. },
  91272. /**
  91273. * Gets or sets a boolean which defines if optimization octree has to be updated
  91274. */
  91275. set: function (value) {
  91276. MergeMeshesOptimization._UpdateSelectionTree = value;
  91277. },
  91278. enumerable: true,
  91279. configurable: true
  91280. });
  91281. /**
  91282. * Gets a string describing the action executed by the current optimization
  91283. * @return description string
  91284. */
  91285. MergeMeshesOptimization.prototype.getDescription = function () {
  91286. return "Merging similar meshes together";
  91287. };
  91288. /**
  91289. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91290. * @param scene defines the current scene where to apply this optimization
  91291. * @param optimizer defines the current optimizer
  91292. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  91293. * @returns true if everything that can be done was applied
  91294. */
  91295. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  91296. var globalPool = scene.meshes.slice(0);
  91297. var globalLength = globalPool.length;
  91298. for (var index = 0; index < globalLength; index++) {
  91299. var currentPool = new Array();
  91300. var current = globalPool[index];
  91301. // Checks
  91302. if (!this._canBeMerged(current)) {
  91303. continue;
  91304. }
  91305. currentPool.push(current);
  91306. // Find compatible meshes
  91307. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  91308. var otherMesh = globalPool[subIndex];
  91309. if (!this._canBeMerged(otherMesh)) {
  91310. continue;
  91311. }
  91312. if (otherMesh.material !== current.material) {
  91313. continue;
  91314. }
  91315. if (otherMesh.checkCollisions !== current.checkCollisions) {
  91316. continue;
  91317. }
  91318. currentPool.push(otherMesh);
  91319. globalLength--;
  91320. globalPool.splice(subIndex, 1);
  91321. subIndex--;
  91322. }
  91323. if (currentPool.length < 2) {
  91324. continue;
  91325. }
  91326. // Merge meshes
  91327. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  91328. }
  91329. if (updateSelectionTree != undefined) {
  91330. if (updateSelectionTree) {
  91331. scene.createOrUpdateSelectionOctree();
  91332. }
  91333. }
  91334. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  91335. scene.createOrUpdateSelectionOctree();
  91336. }
  91337. return true;
  91338. };
  91339. ;
  91340. MergeMeshesOptimization._UpdateSelectionTree = false;
  91341. return MergeMeshesOptimization;
  91342. }(SceneOptimization));
  91343. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  91344. /**
  91345. * Defines a list of options used by SceneOptimizer
  91346. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91347. */
  91348. var SceneOptimizerOptions = /** @class */ (function () {
  91349. /**
  91350. * Creates a new list of options used by SceneOptimizer
  91351. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  91352. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  91353. */
  91354. function SceneOptimizerOptions(
  91355. /**
  91356. * Defines the target frame rate to reach (60 by default)
  91357. */
  91358. targetFrameRate,
  91359. /**
  91360. * Defines the interval between two checkes (2000ms by default)
  91361. */
  91362. trackerDuration) {
  91363. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  91364. if (trackerDuration === void 0) { trackerDuration = 2000; }
  91365. this.targetFrameRate = targetFrameRate;
  91366. this.trackerDuration = trackerDuration;
  91367. /**
  91368. * Gets the list of optimizations to apply
  91369. */
  91370. this.optimizations = new Array();
  91371. }
  91372. /**
  91373. * Add a new optimization
  91374. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  91375. * @returns the current SceneOptimizerOptions
  91376. */
  91377. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  91378. this.optimizations.push(optimization);
  91379. return this;
  91380. };
  91381. /**
  91382. * Add a new custom optimization
  91383. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  91384. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  91385. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91386. * @returns the current SceneOptimizerOptions
  91387. */
  91388. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  91389. if (priority === void 0) { priority = 0; }
  91390. var optimization = new CustomOptimization(priority);
  91391. optimization.onApply = onApply;
  91392. optimization.onGetDescription = onGetDescription;
  91393. this.optimizations.push(optimization);
  91394. return this;
  91395. };
  91396. /**
  91397. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  91398. * @param targetFrameRate defines the target frame rate (60 by default)
  91399. * @returns a SceneOptimizerOptions object
  91400. */
  91401. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  91402. var result = new SceneOptimizerOptions(targetFrameRate);
  91403. var priority = 0;
  91404. result.addOptimization(new MergeMeshesOptimization(priority));
  91405. result.addOptimization(new ShadowsOptimization(priority));
  91406. result.addOptimization(new LensFlaresOptimization(priority));
  91407. // Next priority
  91408. priority++;
  91409. result.addOptimization(new PostProcessesOptimization(priority));
  91410. result.addOptimization(new ParticlesOptimization(priority));
  91411. // Next priority
  91412. priority++;
  91413. result.addOptimization(new TextureOptimization(priority, 1024));
  91414. return result;
  91415. };
  91416. /**
  91417. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  91418. * @param targetFrameRate defines the target frame rate (60 by default)
  91419. * @returns a SceneOptimizerOptions object
  91420. */
  91421. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  91422. var result = new SceneOptimizerOptions(targetFrameRate);
  91423. var priority = 0;
  91424. result.addOptimization(new MergeMeshesOptimization(priority));
  91425. result.addOptimization(new ShadowsOptimization(priority));
  91426. result.addOptimization(new LensFlaresOptimization(priority));
  91427. // Next priority
  91428. priority++;
  91429. result.addOptimization(new PostProcessesOptimization(priority));
  91430. result.addOptimization(new ParticlesOptimization(priority));
  91431. // Next priority
  91432. priority++;
  91433. result.addOptimization(new TextureOptimization(priority, 512));
  91434. // Next priority
  91435. priority++;
  91436. result.addOptimization(new RenderTargetsOptimization(priority));
  91437. // Next priority
  91438. priority++;
  91439. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  91440. return result;
  91441. };
  91442. /**
  91443. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  91444. * @param targetFrameRate defines the target frame rate (60 by default)
  91445. * @returns a SceneOptimizerOptions object
  91446. */
  91447. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  91448. var result = new SceneOptimizerOptions(targetFrameRate);
  91449. var priority = 0;
  91450. result.addOptimization(new MergeMeshesOptimization(priority));
  91451. result.addOptimization(new ShadowsOptimization(priority));
  91452. result.addOptimization(new LensFlaresOptimization(priority));
  91453. // Next priority
  91454. priority++;
  91455. result.addOptimization(new PostProcessesOptimization(priority));
  91456. result.addOptimization(new ParticlesOptimization(priority));
  91457. // Next priority
  91458. priority++;
  91459. result.addOptimization(new TextureOptimization(priority, 256));
  91460. // Next priority
  91461. priority++;
  91462. result.addOptimization(new RenderTargetsOptimization(priority));
  91463. // Next priority
  91464. priority++;
  91465. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  91466. return result;
  91467. };
  91468. return SceneOptimizerOptions;
  91469. }());
  91470. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  91471. /**
  91472. * Class used to run optimizations in order to reach a target frame rate
  91473. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91474. */
  91475. var SceneOptimizer = /** @class */ (function () {
  91476. /**
  91477. * Creates a new SceneOptimizer
  91478. * @param scene defines the scene to work on
  91479. * @param options defines the options to use with the SceneOptimizer
  91480. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  91481. * @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)
  91482. */
  91483. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  91484. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  91485. if (improvementMode === void 0) { improvementMode = false; }
  91486. var _this = this;
  91487. this._isRunning = false;
  91488. this._currentPriorityLevel = 0;
  91489. this._targetFrameRate = 60;
  91490. this._trackerDuration = 2000;
  91491. this._currentFrameRate = 0;
  91492. this._improvementMode = false;
  91493. /**
  91494. * Defines an observable called when the optimizer reaches the target frame rate
  91495. */
  91496. this.onSuccessObservable = new BABYLON.Observable();
  91497. /**
  91498. * Defines an observable called when the optimizer enables an optimization
  91499. */
  91500. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  91501. /**
  91502. * Defines an observable called when the optimizer is not able to reach the target frame rate
  91503. */
  91504. this.onFailureObservable = new BABYLON.Observable();
  91505. if (!options) {
  91506. this._options = new SceneOptimizerOptions();
  91507. }
  91508. else {
  91509. this._options = options;
  91510. }
  91511. if (this._options.targetFrameRate) {
  91512. this._targetFrameRate = this._options.targetFrameRate;
  91513. }
  91514. if (this._options.trackerDuration) {
  91515. this._trackerDuration = this._options.trackerDuration;
  91516. }
  91517. if (autoGeneratePriorities) {
  91518. var priority = 0;
  91519. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  91520. var optim = _a[_i];
  91521. optim.priority = priority++;
  91522. }
  91523. }
  91524. this._improvementMode = improvementMode;
  91525. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91526. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  91527. _this._sceneDisposeObserver = null;
  91528. _this.dispose();
  91529. });
  91530. }
  91531. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  91532. /**
  91533. * Gets a boolean indicating if the optimizer is in improvement mode
  91534. */
  91535. get: function () {
  91536. return this._improvementMode;
  91537. },
  91538. enumerable: true,
  91539. configurable: true
  91540. });
  91541. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  91542. /**
  91543. * Gets the current priority level (0 at start)
  91544. */
  91545. get: function () {
  91546. return this._currentPriorityLevel;
  91547. },
  91548. enumerable: true,
  91549. configurable: true
  91550. });
  91551. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  91552. /**
  91553. * Gets the current frame rate checked by the SceneOptimizer
  91554. */
  91555. get: function () {
  91556. return this._currentFrameRate;
  91557. },
  91558. enumerable: true,
  91559. configurable: true
  91560. });
  91561. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  91562. /**
  91563. * Gets or sets the current target frame rate (60 by default)
  91564. */
  91565. get: function () {
  91566. return this._targetFrameRate;
  91567. },
  91568. /**
  91569. * Gets or sets the current target frame rate (60 by default)
  91570. */
  91571. set: function (value) {
  91572. this._targetFrameRate = value;
  91573. },
  91574. enumerable: true,
  91575. configurable: true
  91576. });
  91577. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  91578. /**
  91579. * Gets or sets the current interval between two checks (every 2000ms by default)
  91580. */
  91581. get: function () {
  91582. return this._trackerDuration;
  91583. },
  91584. /**
  91585. * Gets or sets the current interval between two checks (every 2000ms by default)
  91586. */
  91587. set: function (value) {
  91588. this._trackerDuration = value;
  91589. },
  91590. enumerable: true,
  91591. configurable: true
  91592. });
  91593. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  91594. /**
  91595. * Gets the list of active optimizations
  91596. */
  91597. get: function () {
  91598. return this._options.optimizations;
  91599. },
  91600. enumerable: true,
  91601. configurable: true
  91602. });
  91603. /**
  91604. * Stops the current optimizer
  91605. */
  91606. SceneOptimizer.prototype.stop = function () {
  91607. this._isRunning = false;
  91608. };
  91609. /**
  91610. * Reset the optimizer to initial step (current priority level = 0)
  91611. */
  91612. SceneOptimizer.prototype.reset = function () {
  91613. this._currentPriorityLevel = 0;
  91614. };
  91615. /**
  91616. * Start the optimizer. By default it will try to reach a specific framerate
  91617. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91618. */
  91619. SceneOptimizer.prototype.start = function () {
  91620. var _this = this;
  91621. if (this._isRunning) {
  91622. return;
  91623. }
  91624. this._isRunning = true;
  91625. // Let's wait for the scene to be ready before running our check
  91626. this._scene.executeWhenReady(function () {
  91627. setTimeout(function () {
  91628. _this._checkCurrentState();
  91629. }, _this._trackerDuration);
  91630. });
  91631. };
  91632. SceneOptimizer.prototype._checkCurrentState = function () {
  91633. var _this = this;
  91634. if (!this._isRunning) {
  91635. return;
  91636. }
  91637. var scene = this._scene;
  91638. var options = this._options;
  91639. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91640. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91641. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91642. this._isRunning = false;
  91643. this.onSuccessObservable.notifyObservers(this);
  91644. return;
  91645. }
  91646. // Apply current level of optimizations
  91647. var allDone = true;
  91648. var noOptimizationApplied = true;
  91649. for (var index = 0; index < options.optimizations.length; index++) {
  91650. var optimization = options.optimizations[index];
  91651. if (optimization.priority === this._currentPriorityLevel) {
  91652. noOptimizationApplied = false;
  91653. allDone = allDone && optimization.apply(scene, this);
  91654. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91655. }
  91656. }
  91657. // If no optimization was applied, this is a failure :(
  91658. if (noOptimizationApplied) {
  91659. this._isRunning = false;
  91660. this.onFailureObservable.notifyObservers(this);
  91661. return;
  91662. }
  91663. // If all optimizations were done, move to next level
  91664. if (allDone) {
  91665. this._currentPriorityLevel++;
  91666. }
  91667. // Let's the system running for a specific amount of time before checking FPS
  91668. scene.executeWhenReady(function () {
  91669. setTimeout(function () {
  91670. _this._checkCurrentState();
  91671. }, _this._trackerDuration);
  91672. });
  91673. };
  91674. /**
  91675. * Release all resources
  91676. */
  91677. SceneOptimizer.prototype.dispose = function () {
  91678. this.stop();
  91679. this.onSuccessObservable.clear();
  91680. this.onFailureObservable.clear();
  91681. this.onNewOptimizationAppliedObservable.clear();
  91682. if (this._sceneDisposeObserver) {
  91683. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91684. }
  91685. };
  91686. /**
  91687. * Helper function to create a SceneOptimizer with one single line of code
  91688. * @param scene defines the scene to work on
  91689. * @param options defines the options to use with the SceneOptimizer
  91690. * @param onSuccess defines a callback to call on success
  91691. * @param onFailure defines a callback to call on failure
  91692. * @returns the new SceneOptimizer object
  91693. */
  91694. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91695. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91696. if (onSuccess) {
  91697. optimizer.onSuccessObservable.add(function () {
  91698. onSuccess();
  91699. });
  91700. }
  91701. if (onFailure) {
  91702. optimizer.onFailureObservable.add(function () {
  91703. onFailure();
  91704. });
  91705. }
  91706. optimizer.start();
  91707. return optimizer;
  91708. };
  91709. return SceneOptimizer;
  91710. }());
  91711. BABYLON.SceneOptimizer = SceneOptimizer;
  91712. })(BABYLON || (BABYLON = {}));
  91713. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91714. var BABYLON;
  91715. (function (BABYLON) {
  91716. var OutlineRenderer = /** @class */ (function () {
  91717. function OutlineRenderer(scene) {
  91718. this.zOffset = 1;
  91719. this._scene = scene;
  91720. }
  91721. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91722. var _this = this;
  91723. if (useOverlay === void 0) { useOverlay = false; }
  91724. var scene = this._scene;
  91725. var engine = this._scene.getEngine();
  91726. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91727. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91728. return;
  91729. }
  91730. var mesh = subMesh.getRenderingMesh();
  91731. var material = subMesh.getMaterial();
  91732. if (!material || !scene.activeCamera) {
  91733. return;
  91734. }
  91735. engine.enableEffect(this._effect);
  91736. // Logarithmic depth
  91737. if (material.useLogarithmicDepth) {
  91738. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91739. }
  91740. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91741. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91742. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91743. // Bones
  91744. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91745. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91746. }
  91747. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91748. // Alpha test
  91749. if (material && material.needAlphaTesting()) {
  91750. var alphaTexture = material.getAlphaTestTexture();
  91751. if (alphaTexture) {
  91752. this._effect.setTexture("diffuseSampler", alphaTexture);
  91753. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91754. }
  91755. }
  91756. engine.setZOffset(-this.zOffset);
  91757. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91758. engine.setZOffset(0);
  91759. };
  91760. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91761. var defines = [];
  91762. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91763. var mesh = subMesh.getMesh();
  91764. var material = subMesh.getMaterial();
  91765. if (material) {
  91766. // Alpha test
  91767. if (material.needAlphaTesting()) {
  91768. defines.push("#define ALPHATEST");
  91769. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91770. attribs.push(BABYLON.VertexBuffer.UVKind);
  91771. defines.push("#define UV1");
  91772. }
  91773. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91774. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91775. defines.push("#define UV2");
  91776. }
  91777. }
  91778. //Logarithmic depth
  91779. if (material.useLogarithmicDepth) {
  91780. defines.push("#define LOGARITHMICDEPTH");
  91781. }
  91782. }
  91783. // Bones
  91784. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91787. if (mesh.numBoneInfluencers > 4) {
  91788. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91789. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91790. }
  91791. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91792. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91793. }
  91794. else {
  91795. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91796. }
  91797. // Instances
  91798. if (useInstances) {
  91799. defines.push("#define INSTANCES");
  91800. attribs.push("world0");
  91801. attribs.push("world1");
  91802. attribs.push("world2");
  91803. attribs.push("world3");
  91804. }
  91805. // Get correct effect
  91806. var join = defines.join("\n");
  91807. if (this._cachedDefines !== join) {
  91808. this._cachedDefines = join;
  91809. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91810. }
  91811. return this._effect.isReady();
  91812. };
  91813. return OutlineRenderer;
  91814. }());
  91815. BABYLON.OutlineRenderer = OutlineRenderer;
  91816. })(BABYLON || (BABYLON = {}));
  91817. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91818. var BABYLON;
  91819. (function (BABYLON) {
  91820. var FaceAdjacencies = /** @class */ (function () {
  91821. function FaceAdjacencies() {
  91822. this.edges = new Array();
  91823. this.edgesConnectedCount = 0;
  91824. }
  91825. return FaceAdjacencies;
  91826. }());
  91827. var EdgesRenderer = /** @class */ (function () {
  91828. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91829. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91830. if (epsilon === void 0) { epsilon = 0.95; }
  91831. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91832. this.edgesWidthScalerForOrthographic = 1000.0;
  91833. this.edgesWidthScalerForPerspective = 50.0;
  91834. this._linesPositions = new Array();
  91835. this._linesNormals = new Array();
  91836. this._linesIndices = new Array();
  91837. this._buffers = {};
  91838. this._checkVerticesInsteadOfIndices = false;
  91839. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  91840. this.isEnabled = true;
  91841. this._source = source;
  91842. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91843. this._epsilon = epsilon;
  91844. this._prepareRessources();
  91845. this._generateEdgesLines();
  91846. }
  91847. EdgesRenderer.prototype._prepareRessources = function () {
  91848. if (this._lineShader) {
  91849. return;
  91850. }
  91851. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91852. attributes: ["position", "normal"],
  91853. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91854. });
  91855. this._lineShader.disableDepthWrite = true;
  91856. this._lineShader.backFaceCulling = false;
  91857. };
  91858. EdgesRenderer.prototype._rebuild = function () {
  91859. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91860. if (buffer) {
  91861. buffer._rebuild();
  91862. }
  91863. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91864. if (buffer) {
  91865. buffer._rebuild();
  91866. }
  91867. var scene = this._source.getScene();
  91868. var engine = scene.getEngine();
  91869. this._ib = engine.createIndexBuffer(this._linesIndices);
  91870. };
  91871. EdgesRenderer.prototype.dispose = function () {
  91872. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91873. if (buffer) {
  91874. buffer.dispose();
  91875. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91876. }
  91877. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91878. if (buffer) {
  91879. buffer.dispose();
  91880. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91881. }
  91882. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91883. this._lineShader.dispose();
  91884. };
  91885. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91886. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91887. return 0;
  91888. }
  91889. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91890. return 1;
  91891. }
  91892. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91893. return 2;
  91894. }
  91895. return -1;
  91896. };
  91897. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91898. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91899. return 0;
  91900. }
  91901. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91902. return 1;
  91903. }
  91904. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91905. return 2;
  91906. }
  91907. return -1;
  91908. };
  91909. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91910. var needToCreateLine;
  91911. if (edge === undefined) {
  91912. needToCreateLine = true;
  91913. }
  91914. else {
  91915. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91916. needToCreateLine = dotProduct < this._epsilon;
  91917. }
  91918. if (needToCreateLine) {
  91919. var offset = this._linesPositions.length / 3;
  91920. var normal = p0.subtract(p1);
  91921. normal.normalize();
  91922. // Positions
  91923. this._linesPositions.push(p0.x);
  91924. this._linesPositions.push(p0.y);
  91925. this._linesPositions.push(p0.z);
  91926. this._linesPositions.push(p0.x);
  91927. this._linesPositions.push(p0.y);
  91928. this._linesPositions.push(p0.z);
  91929. this._linesPositions.push(p1.x);
  91930. this._linesPositions.push(p1.y);
  91931. this._linesPositions.push(p1.z);
  91932. this._linesPositions.push(p1.x);
  91933. this._linesPositions.push(p1.y);
  91934. this._linesPositions.push(p1.z);
  91935. // Normals
  91936. this._linesNormals.push(p1.x);
  91937. this._linesNormals.push(p1.y);
  91938. this._linesNormals.push(p1.z);
  91939. this._linesNormals.push(-1);
  91940. this._linesNormals.push(p1.x);
  91941. this._linesNormals.push(p1.y);
  91942. this._linesNormals.push(p1.z);
  91943. this._linesNormals.push(1);
  91944. this._linesNormals.push(p0.x);
  91945. this._linesNormals.push(p0.y);
  91946. this._linesNormals.push(p0.z);
  91947. this._linesNormals.push(-1);
  91948. this._linesNormals.push(p0.x);
  91949. this._linesNormals.push(p0.y);
  91950. this._linesNormals.push(p0.z);
  91951. this._linesNormals.push(1);
  91952. // Indices
  91953. this._linesIndices.push(offset);
  91954. this._linesIndices.push(offset + 1);
  91955. this._linesIndices.push(offset + 2);
  91956. this._linesIndices.push(offset);
  91957. this._linesIndices.push(offset + 2);
  91958. this._linesIndices.push(offset + 3);
  91959. }
  91960. };
  91961. EdgesRenderer.prototype._generateEdgesLines = function () {
  91962. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91963. var indices = this._source.getIndices();
  91964. if (!indices || !positions) {
  91965. return;
  91966. }
  91967. // First let's find adjacencies
  91968. var adjacencies = new Array();
  91969. var faceNormals = new Array();
  91970. var index;
  91971. var faceAdjacencies;
  91972. // Prepare faces
  91973. for (index = 0; index < indices.length; index += 3) {
  91974. faceAdjacencies = new FaceAdjacencies();
  91975. var p0Index = indices[index];
  91976. var p1Index = indices[index + 1];
  91977. var p2Index = indices[index + 2];
  91978. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91979. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91980. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91981. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91982. faceNormal.normalize();
  91983. faceNormals.push(faceNormal);
  91984. adjacencies.push(faceAdjacencies);
  91985. }
  91986. // Scan
  91987. for (index = 0; index < adjacencies.length; index++) {
  91988. faceAdjacencies = adjacencies[index];
  91989. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91990. var otherFaceAdjacencies = adjacencies[otherIndex];
  91991. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91992. break;
  91993. }
  91994. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91995. continue;
  91996. }
  91997. var otherP0 = indices[otherIndex * 3];
  91998. var otherP1 = indices[otherIndex * 3 + 1];
  91999. var otherP2 = indices[otherIndex * 3 + 2];
  92000. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  92001. var otherEdgeIndex = 0;
  92002. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  92003. continue;
  92004. }
  92005. switch (edgeIndex) {
  92006. case 0:
  92007. if (this._checkVerticesInsteadOfIndices) {
  92008. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92009. }
  92010. else {
  92011. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  92012. }
  92013. break;
  92014. case 1:
  92015. if (this._checkVerticesInsteadOfIndices) {
  92016. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92017. }
  92018. else {
  92019. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  92020. }
  92021. break;
  92022. case 2:
  92023. if (this._checkVerticesInsteadOfIndices) {
  92024. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92025. }
  92026. else {
  92027. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  92028. }
  92029. break;
  92030. }
  92031. if (otherEdgeIndex === -1) {
  92032. continue;
  92033. }
  92034. faceAdjacencies.edges[edgeIndex] = otherIndex;
  92035. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  92036. faceAdjacencies.edgesConnectedCount++;
  92037. otherFaceAdjacencies.edgesConnectedCount++;
  92038. if (faceAdjacencies.edgesConnectedCount === 3) {
  92039. break;
  92040. }
  92041. }
  92042. }
  92043. }
  92044. // Create lines
  92045. for (index = 0; index < adjacencies.length; index++) {
  92046. // 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
  92047. var current = adjacencies[index];
  92048. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  92049. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  92050. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  92051. }
  92052. // Merge into a single mesh
  92053. var engine = this._source.getScene().getEngine();
  92054. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  92055. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  92056. this._ib = engine.createIndexBuffer(this._linesIndices);
  92057. this._indicesCount = this._linesIndices.length;
  92058. };
  92059. EdgesRenderer.prototype.render = function () {
  92060. var scene = this._source.getScene();
  92061. if (!this._lineShader.isReady() || !scene.activeCamera) {
  92062. return;
  92063. }
  92064. var engine = scene.getEngine();
  92065. this._lineShader._preBind();
  92066. // VBOs
  92067. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  92068. scene.resetCachedMaterial();
  92069. this._lineShader.setColor4("color", this._source.edgesColor);
  92070. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  92071. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  92072. }
  92073. else {
  92074. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  92075. }
  92076. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  92077. this._lineShader.bind(this._source.getWorldMatrix());
  92078. // Draw order
  92079. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  92080. this._lineShader.unbind();
  92081. engine.setDepthWrite(true);
  92082. };
  92083. return EdgesRenderer;
  92084. }());
  92085. BABYLON.EdgesRenderer = EdgesRenderer;
  92086. })(BABYLON || (BABYLON = {}));
  92087. //# sourceMappingURL=babylon.edgesRenderer.js.map
  92088. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92089. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92090. s = arguments[i];
  92091. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92092. t[p] = s[p];
  92093. }
  92094. return t;
  92095. };
  92096. var BABYLON;
  92097. (function (BABYLON) {
  92098. /**
  92099. * The effect layer Helps adding post process effect blended with the main pass.
  92100. *
  92101. * This can be for instance use to generate glow or higlight effects on the scene.
  92102. *
  92103. * The effect layer class can not be used directly and is intented to inherited from to be
  92104. * customized per effects.
  92105. */
  92106. var EffectLayer = /** @class */ (function () {
  92107. /**
  92108. * Instantiates a new effect Layer and references it in the scene.
  92109. * @param name The name of the layer
  92110. * @param scene The scene to use the layer in
  92111. */
  92112. function EffectLayer(
  92113. /** The Friendly of the effect in the scene */
  92114. name, scene) {
  92115. this._vertexBuffers = {};
  92116. this._maxSize = 0;
  92117. this._mainTextureDesiredSize = { width: 0, height: 0 };
  92118. this._shouldRender = true;
  92119. this._postProcesses = [];
  92120. this._textures = [];
  92121. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  92122. /**
  92123. * The clear color of the texture used to generate the glow map.
  92124. */
  92125. this.neutralColor = new BABYLON.Color4();
  92126. /**
  92127. * Specifies wether the highlight layer is enabled or not.
  92128. */
  92129. this.isEnabled = true;
  92130. /**
  92131. * An event triggered when the effect layer has been disposed.
  92132. */
  92133. this.onDisposeObservable = new BABYLON.Observable();
  92134. /**
  92135. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  92136. */
  92137. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  92138. /**
  92139. * An event triggered when the generated texture is being merged in the scene.
  92140. */
  92141. this.onBeforeComposeObservable = new BABYLON.Observable();
  92142. /**
  92143. * An event triggered when the generated texture has been merged in the scene.
  92144. */
  92145. this.onAfterComposeObservable = new BABYLON.Observable();
  92146. /**
  92147. * An event triggered when the efffect layer changes its size.
  92148. */
  92149. this.onSizeChangedObservable = new BABYLON.Observable();
  92150. this.name = name;
  92151. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92152. this._engine = scene.getEngine();
  92153. this._maxSize = this._engine.getCaps().maxTextureSize;
  92154. this._scene.effectLayers.push(this);
  92155. // Generate Buffers
  92156. this._generateIndexBuffer();
  92157. this._genrateVertexBuffer();
  92158. }
  92159. Object.defineProperty(EffectLayer.prototype, "camera", {
  92160. /**
  92161. * Gets the camera attached to the layer.
  92162. */
  92163. get: function () {
  92164. return this._effectLayerOptions.camera;
  92165. },
  92166. enumerable: true,
  92167. configurable: true
  92168. });
  92169. /**
  92170. * Initializes the effect layer with the required options.
  92171. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  92172. */
  92173. EffectLayer.prototype._init = function (options) {
  92174. // Adapt options
  92175. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92176. this._setMainTextureSize();
  92177. this._createMainTexture();
  92178. this._createTextureAndPostProcesses();
  92179. this._mergeEffect = this._createMergeEffect();
  92180. };
  92181. /**
  92182. * Generates the index buffer of the full screen quad blending to the main canvas.
  92183. */
  92184. EffectLayer.prototype._generateIndexBuffer = function () {
  92185. // Indices
  92186. var indices = [];
  92187. indices.push(0);
  92188. indices.push(1);
  92189. indices.push(2);
  92190. indices.push(0);
  92191. indices.push(2);
  92192. indices.push(3);
  92193. this._indexBuffer = this._engine.createIndexBuffer(indices);
  92194. };
  92195. /**
  92196. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  92197. */
  92198. EffectLayer.prototype._genrateVertexBuffer = function () {
  92199. // VBO
  92200. var vertices = [];
  92201. vertices.push(1, 1);
  92202. vertices.push(-1, 1);
  92203. vertices.push(-1, -1);
  92204. vertices.push(1, -1);
  92205. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92207. };
  92208. /**
  92209. * Sets the main texture desired size which is the closest power of two
  92210. * of the engine canvas size.
  92211. */
  92212. EffectLayer.prototype._setMainTextureSize = function () {
  92213. if (this._effectLayerOptions.mainTextureFixedSize) {
  92214. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  92215. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  92216. }
  92217. else {
  92218. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  92219. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  92220. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  92221. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  92222. }
  92223. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  92224. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  92225. };
  92226. /**
  92227. * Creates the main texture for the effect layer.
  92228. */
  92229. EffectLayer.prototype._createMainTexture = function () {
  92230. var _this = this;
  92231. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  92232. width: this._mainTextureDesiredSize.width,
  92233. height: this._mainTextureDesiredSize.height
  92234. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92235. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  92236. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92237. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92238. this._mainTexture.anisotropicFilteringLevel = 1;
  92239. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92240. this._mainTexture.renderParticles = false;
  92241. this._mainTexture.renderList = null;
  92242. this._mainTexture.ignoreCameraViewport = true;
  92243. // Custom render function
  92244. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  92245. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  92246. var index;
  92247. var engine = _this._scene.getEngine();
  92248. if (depthOnlySubMeshes.length) {
  92249. engine.setColorWrite(false);
  92250. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  92251. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  92252. }
  92253. engine.setColorWrite(true);
  92254. }
  92255. for (index = 0; index < opaqueSubMeshes.length; index++) {
  92256. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  92257. }
  92258. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  92259. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  92260. }
  92261. for (index = 0; index < transparentSubMeshes.length; index++) {
  92262. _this._renderSubMesh(transparentSubMeshes.data[index]);
  92263. }
  92264. };
  92265. this._mainTexture.onClearObservable.add(function (engine) {
  92266. engine.clear(_this.neutralColor, true, true, true);
  92267. });
  92268. };
  92269. /**
  92270. * Checks for the readiness of the element composing the layer.
  92271. * @param subMesh the mesh to check for
  92272. * @param useInstances specify wether or not to use instances to render the mesh
  92273. * @param emissiveTexture the associated emissive texture used to generate the glow
  92274. * @return true if ready otherwise, false
  92275. */
  92276. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  92277. var material = subMesh.getMaterial();
  92278. if (!material) {
  92279. return false;
  92280. }
  92281. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  92282. return false;
  92283. }
  92284. var defines = [];
  92285. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92286. var mesh = subMesh.getMesh();
  92287. var uv1 = false;
  92288. var uv2 = false;
  92289. // Alpha test
  92290. if (material && material.needAlphaTesting()) {
  92291. var alphaTexture = material.getAlphaTestTexture();
  92292. if (alphaTexture) {
  92293. defines.push("#define ALPHATEST");
  92294. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92295. alphaTexture.coordinatesIndex === 1) {
  92296. defines.push("#define DIFFUSEUV2");
  92297. uv2 = true;
  92298. }
  92299. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92300. defines.push("#define DIFFUSEUV1");
  92301. uv1 = true;
  92302. }
  92303. }
  92304. }
  92305. // Emissive
  92306. if (emissiveTexture) {
  92307. defines.push("#define EMISSIVE");
  92308. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92309. emissiveTexture.coordinatesIndex === 1) {
  92310. defines.push("#define EMISSIVEUV2");
  92311. uv2 = true;
  92312. }
  92313. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92314. defines.push("#define EMISSIVEUV1");
  92315. uv1 = true;
  92316. }
  92317. }
  92318. if (uv1) {
  92319. attribs.push(BABYLON.VertexBuffer.UVKind);
  92320. defines.push("#define UV1");
  92321. }
  92322. if (uv2) {
  92323. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92324. defines.push("#define UV2");
  92325. }
  92326. // Bones
  92327. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92328. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92329. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92330. if (mesh.numBoneInfluencers > 4) {
  92331. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92332. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92333. }
  92334. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92335. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  92336. }
  92337. else {
  92338. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92339. }
  92340. // Morph targets
  92341. var manager = mesh.morphTargetManager;
  92342. var morphInfluencers = 0;
  92343. if (manager) {
  92344. if (manager.numInfluencers > 0) {
  92345. defines.push("#define MORPHTARGETS");
  92346. morphInfluencers = manager.numInfluencers;
  92347. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  92348. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  92349. }
  92350. }
  92351. // Instances
  92352. if (useInstances) {
  92353. defines.push("#define INSTANCES");
  92354. attribs.push("world0");
  92355. attribs.push("world1");
  92356. attribs.push("world2");
  92357. attribs.push("world3");
  92358. }
  92359. // Get correct effect
  92360. var join = defines.join("\n");
  92361. if (this._cachedDefines !== join) {
  92362. this._cachedDefines = join;
  92363. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  92364. }
  92365. return this._effectLayerMapGenerationEffect.isReady();
  92366. };
  92367. /**
  92368. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  92369. */
  92370. EffectLayer.prototype.render = function () {
  92371. var currentEffect = this._mergeEffect;
  92372. // Check
  92373. if (!currentEffect.isReady())
  92374. return;
  92375. for (var i = 0; i < this._postProcesses.length; i++) {
  92376. if (!this._postProcesses[i].isReady()) {
  92377. return;
  92378. }
  92379. }
  92380. var engine = this._scene.getEngine();
  92381. this.onBeforeComposeObservable.notifyObservers(this);
  92382. // Render
  92383. engine.enableEffect(currentEffect);
  92384. engine.setState(false);
  92385. // VBOs
  92386. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92387. // Cache
  92388. var previousAlphaMode = engine.getAlphaMode();
  92389. // Go Blend.
  92390. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  92391. // Blends the map on the main canvas.
  92392. this._internalRender(currentEffect);
  92393. // Restore Alpha
  92394. engine.setAlphaMode(previousAlphaMode);
  92395. this.onAfterComposeObservable.notifyObservers(this);
  92396. // Handle size changes.
  92397. var size = this._mainTexture.getSize();
  92398. this._setMainTextureSize();
  92399. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  92400. // Recreate RTT and post processes on size change.
  92401. this.onSizeChangedObservable.notifyObservers(this);
  92402. this._disposeTextureAndPostProcesses();
  92403. this._createMainTexture();
  92404. this._createTextureAndPostProcesses();
  92405. }
  92406. };
  92407. /**
  92408. * Determine if a given mesh will be used in the current effect.
  92409. * @param mesh mesh to test
  92410. * @returns true if the mesh will be used
  92411. */
  92412. EffectLayer.prototype.hasMesh = function (mesh) {
  92413. return true;
  92414. };
  92415. /**
  92416. * Returns true if the layer contains information to display, otherwise false.
  92417. * @returns true if the glow layer should be rendered
  92418. */
  92419. EffectLayer.prototype.shouldRender = function () {
  92420. return this.isEnabled && this._shouldRender;
  92421. };
  92422. /**
  92423. * Returns true if the mesh should render, otherwise false.
  92424. * @param mesh The mesh to render
  92425. * @returns true if it should render otherwise false
  92426. */
  92427. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  92428. return true;
  92429. };
  92430. /**
  92431. * Returns true if the mesh should render, otherwise false.
  92432. * @param mesh The mesh to render
  92433. * @returns true if it should render otherwise false
  92434. */
  92435. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  92436. return true;
  92437. };
  92438. /**
  92439. * Renders the submesh passed in parameter to the generation map.
  92440. */
  92441. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  92442. var _this = this;
  92443. if (!this.shouldRender()) {
  92444. return;
  92445. }
  92446. var material = subMesh.getMaterial();
  92447. var mesh = subMesh.getRenderingMesh();
  92448. var scene = this._scene;
  92449. var engine = scene.getEngine();
  92450. if (!material) {
  92451. return;
  92452. }
  92453. // Do not block in blend mode.
  92454. if (material.needAlphaBlendingForMesh(mesh)) {
  92455. return;
  92456. }
  92457. // Culling
  92458. engine.setState(material.backFaceCulling);
  92459. // Managing instances
  92460. var batch = mesh._getInstancesRenderList(subMesh._id);
  92461. if (batch.mustReturn) {
  92462. return;
  92463. }
  92464. // Early Exit per mesh
  92465. if (!this._shouldRenderMesh(mesh)) {
  92466. return;
  92467. }
  92468. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92469. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  92470. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  92471. engine.enableEffect(this._effectLayerMapGenerationEffect);
  92472. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  92473. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  92474. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  92475. // Alpha test
  92476. if (material && material.needAlphaTesting()) {
  92477. var alphaTexture = material.getAlphaTestTexture();
  92478. if (alphaTexture) {
  92479. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  92480. var textureMatrix = alphaTexture.getTextureMatrix();
  92481. if (textureMatrix) {
  92482. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  92483. }
  92484. }
  92485. }
  92486. // Glow emissive only
  92487. if (this._emissiveTextureAndColor.texture) {
  92488. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  92489. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  92490. }
  92491. // Bones
  92492. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92493. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92494. }
  92495. // Morph targets
  92496. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  92497. // Draw
  92498. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  92499. }
  92500. else {
  92501. // Need to reset refresh rate of the shadowMap
  92502. this._mainTexture.resetRefreshCounter();
  92503. }
  92504. };
  92505. /**
  92506. * Rebuild the required buffers.
  92507. * @hidden Internal use only.
  92508. */
  92509. EffectLayer.prototype._rebuild = function () {
  92510. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92511. if (vb) {
  92512. vb._rebuild();
  92513. }
  92514. this._generateIndexBuffer();
  92515. };
  92516. /**
  92517. * Dispose only the render target textures and post process.
  92518. */
  92519. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  92520. this._mainTexture.dispose();
  92521. for (var i = 0; i < this._postProcesses.length; i++) {
  92522. if (this._postProcesses[i]) {
  92523. this._postProcesses[i].dispose();
  92524. }
  92525. }
  92526. this._postProcesses = [];
  92527. for (var i = 0; i < this._textures.length; i++) {
  92528. if (this._textures[i]) {
  92529. this._textures[i].dispose();
  92530. }
  92531. }
  92532. this._textures = [];
  92533. };
  92534. /**
  92535. * Dispose the highlight layer and free resources.
  92536. */
  92537. EffectLayer.prototype.dispose = function () {
  92538. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92539. if (vertexBuffer) {
  92540. vertexBuffer.dispose();
  92541. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92542. }
  92543. if (this._indexBuffer) {
  92544. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92545. this._indexBuffer = null;
  92546. }
  92547. // Clean textures and post processes
  92548. this._disposeTextureAndPostProcesses();
  92549. // Remove from scene
  92550. var index = this._scene.effectLayers.indexOf(this, 0);
  92551. if (index > -1) {
  92552. this._scene.effectLayers.splice(index, 1);
  92553. }
  92554. // Callback
  92555. this.onDisposeObservable.notifyObservers(this);
  92556. this.onDisposeObservable.clear();
  92557. this.onBeforeRenderMainTextureObservable.clear();
  92558. this.onBeforeComposeObservable.clear();
  92559. this.onAfterComposeObservable.clear();
  92560. this.onSizeChangedObservable.clear();
  92561. };
  92562. /**
  92563. * Gets the class name of the effect layer
  92564. * @returns the string with the class name of the effect layer
  92565. */
  92566. EffectLayer.prototype.getClassName = function () {
  92567. return "EffectLayer";
  92568. };
  92569. /**
  92570. * Creates an effect layer from parsed effect layer data
  92571. * @param parsedEffectLayer defines effect layer data
  92572. * @param scene defines the current scene
  92573. * @param rootUrl defines the root URL containing the effect layer information
  92574. * @returns a parsed effect Layer
  92575. */
  92576. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  92577. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  92578. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  92579. };
  92580. __decorate([
  92581. BABYLON.serialize()
  92582. ], EffectLayer.prototype, "name", void 0);
  92583. __decorate([
  92584. BABYLON.serializeAsColor4()
  92585. ], EffectLayer.prototype, "neutralColor", void 0);
  92586. __decorate([
  92587. BABYLON.serialize()
  92588. ], EffectLayer.prototype, "isEnabled", void 0);
  92589. __decorate([
  92590. BABYLON.serializeAsCameraReference()
  92591. ], EffectLayer.prototype, "camera", null);
  92592. return EffectLayer;
  92593. }());
  92594. BABYLON.EffectLayer = EffectLayer;
  92595. })(BABYLON || (BABYLON = {}));
  92596. //# sourceMappingURL=babylon.effectLayer.js.map
  92597. var BABYLON;
  92598. (function (BABYLON) {
  92599. /**
  92600. * Special Glow Blur post process only blurring the alpha channel
  92601. * It enforces keeping the most luminous color in the color channel.
  92602. */
  92603. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92604. __extends(GlowBlurPostProcess, _super);
  92605. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92607. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92608. _this.direction = direction;
  92609. _this.kernel = kernel;
  92610. _this.onApplyObservable.add(function (effect) {
  92611. effect.setFloat2("screenSize", _this.width, _this.height);
  92612. effect.setVector2("direction", _this.direction);
  92613. effect.setFloat("blurWidth", _this.kernel);
  92614. });
  92615. return _this;
  92616. }
  92617. return GlowBlurPostProcess;
  92618. }(BABYLON.PostProcess));
  92619. /**
  92620. * The highlight layer Helps adding a glow effect around a mesh.
  92621. *
  92622. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92623. * glowy meshes to your scene.
  92624. *
  92625. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92626. */
  92627. var HighlightLayer = /** @class */ (function (_super) {
  92628. __extends(HighlightLayer, _super);
  92629. /**
  92630. * Instantiates a new highlight Layer and references it to the scene..
  92631. * @param name The name of the layer
  92632. * @param scene The scene to use the layer in
  92633. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92634. */
  92635. function HighlightLayer(name, scene, options) {
  92636. var _this = _super.call(this, name, scene) || this;
  92637. _this.name = name;
  92638. /**
  92639. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92640. */
  92641. _this.innerGlow = true;
  92642. /**
  92643. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92644. */
  92645. _this.outerGlow = true;
  92646. /**
  92647. * An event triggered when the highlight layer is being blurred.
  92648. */
  92649. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92650. /**
  92651. * An event triggered when the highlight layer has been blurred.
  92652. */
  92653. _this.onAfterBlurObservable = new BABYLON.Observable();
  92654. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92655. _this._meshes = {};
  92656. _this._excludedMeshes = {};
  92657. _this.neutralColor = HighlightLayer.NeutralColor;
  92658. // Warn on stencil
  92659. if (!_this._engine.isStencilEnable) {
  92660. 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 }");
  92661. }
  92662. // Adapt options
  92663. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92664. // Initialize the layer
  92665. _this._init({
  92666. alphaBlendingMode: _this._options.alphaBlendingMode,
  92667. camera: _this._options.camera,
  92668. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92669. mainTextureRatio: _this._options.mainTextureRatio
  92670. });
  92671. // Do not render as long as no meshes have been added
  92672. _this._shouldRender = false;
  92673. return _this;
  92674. }
  92675. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92676. /**
  92677. * Gets the horizontal size of the blur.
  92678. */
  92679. get: function () {
  92680. return this._horizontalBlurPostprocess.kernel;
  92681. },
  92682. /**
  92683. * Specifies the horizontal size of the blur.
  92684. */
  92685. set: function (value) {
  92686. this._horizontalBlurPostprocess.kernel = value;
  92687. },
  92688. enumerable: true,
  92689. configurable: true
  92690. });
  92691. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92692. /**
  92693. * Gets the vertical size of the blur.
  92694. */
  92695. get: function () {
  92696. return this._verticalBlurPostprocess.kernel;
  92697. },
  92698. /**
  92699. * Specifies the vertical size of the blur.
  92700. */
  92701. set: function (value) {
  92702. this._verticalBlurPostprocess.kernel = value;
  92703. },
  92704. enumerable: true,
  92705. configurable: true
  92706. });
  92707. /**
  92708. * Get the effect name of the layer.
  92709. * @return The effect name
  92710. */
  92711. HighlightLayer.prototype.getEffectName = function () {
  92712. return HighlightLayer.EffectName;
  92713. };
  92714. /**
  92715. * Create the merge effect. This is the shader use to blit the information back
  92716. * to the main canvas at the end of the scene rendering.
  92717. */
  92718. HighlightLayer.prototype._createMergeEffect = function () {
  92719. // Effect
  92720. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92721. };
  92722. /**
  92723. * Creates the render target textures and post processes used in the highlight layer.
  92724. */
  92725. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92726. var _this = this;
  92727. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92728. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92729. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92730. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92731. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92732. width: blurTextureWidth,
  92733. height: blurTextureHeight
  92734. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92735. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92736. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92737. this._blurTexture.anisotropicFilteringLevel = 16;
  92738. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92739. this._blurTexture.renderParticles = false;
  92740. this._blurTexture.ignoreCameraViewport = true;
  92741. this._textures = [this._blurTexture];
  92742. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92743. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92744. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92745. effect.setTexture("textureSampler", _this._mainTexture);
  92746. });
  92747. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92748. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92749. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92750. });
  92751. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92752. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92753. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92754. });
  92755. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92756. }
  92757. else {
  92758. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92759. width: blurTextureWidth,
  92760. height: blurTextureHeight
  92761. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92762. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92763. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92764. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92765. effect.setTexture("textureSampler", _this._mainTexture);
  92766. });
  92767. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92768. width: blurTextureWidth,
  92769. height: blurTextureHeight
  92770. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92771. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92772. }
  92773. this._mainTexture.onAfterUnbindObservable.add(function () {
  92774. _this.onBeforeBlurObservable.notifyObservers(_this);
  92775. var internalTexture = _this._blurTexture.getInternalTexture();
  92776. if (internalTexture) {
  92777. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92778. }
  92779. _this.onAfterBlurObservable.notifyObservers(_this);
  92780. });
  92781. // Prevent autoClear.
  92782. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92783. };
  92784. /**
  92785. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92786. */
  92787. HighlightLayer.prototype.needStencil = function () {
  92788. return true;
  92789. };
  92790. /**
  92791. * Checks for the readiness of the element composing the layer.
  92792. * @param subMesh the mesh to check for
  92793. * @param useInstances specify wether or not to use instances to render the mesh
  92794. * @param emissiveTexture the associated emissive texture used to generate the glow
  92795. * @return true if ready otherwise, false
  92796. */
  92797. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92798. var material = subMesh.getMaterial();
  92799. var mesh = subMesh.getRenderingMesh();
  92800. if (!material || !mesh || !this._meshes) {
  92801. return false;
  92802. }
  92803. var emissiveTexture = null;
  92804. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92805. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92806. emissiveTexture = material.emissiveTexture;
  92807. }
  92808. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92809. };
  92810. /**
  92811. * Implementation specific of rendering the generating effect on the main canvas.
  92812. * @param effect The effect used to render through
  92813. */
  92814. HighlightLayer.prototype._internalRender = function (effect) {
  92815. // Texture
  92816. effect.setTexture("textureSampler", this._blurTexture);
  92817. // Cache
  92818. var engine = this._engine;
  92819. var previousStencilBuffer = engine.getStencilBuffer();
  92820. var previousStencilFunction = engine.getStencilFunction();
  92821. var previousStencilMask = engine.getStencilMask();
  92822. var previousStencilOperationPass = engine.getStencilOperationPass();
  92823. var previousStencilOperationFail = engine.getStencilOperationFail();
  92824. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92825. var previousStencilReference = engine.getStencilFunctionReference();
  92826. // Stencil operations
  92827. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92828. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92829. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92830. // Draw order
  92831. engine.setStencilMask(0x00);
  92832. engine.setStencilBuffer(true);
  92833. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92834. // 2 passes inner outer
  92835. if (this.outerGlow) {
  92836. effect.setFloat("offset", 0);
  92837. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92838. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92839. }
  92840. if (this.innerGlow) {
  92841. effect.setFloat("offset", 1);
  92842. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92843. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92844. }
  92845. // Restore Cache
  92846. engine.setStencilFunction(previousStencilFunction);
  92847. engine.setStencilMask(previousStencilMask);
  92848. engine.setStencilBuffer(previousStencilBuffer);
  92849. engine.setStencilOperationPass(previousStencilOperationPass);
  92850. engine.setStencilOperationFail(previousStencilOperationFail);
  92851. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92852. engine.setStencilFunctionReference(previousStencilReference);
  92853. };
  92854. /**
  92855. * Returns true if the layer contains information to display, otherwise false.
  92856. */
  92857. HighlightLayer.prototype.shouldRender = function () {
  92858. if (_super.prototype.shouldRender.call(this)) {
  92859. return this._meshes ? true : false;
  92860. }
  92861. return false;
  92862. };
  92863. /**
  92864. * Returns true if the mesh should render, otherwise false.
  92865. * @param mesh The mesh to render
  92866. * @returns true if it should render otherwise false
  92867. */
  92868. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92869. // Excluded Mesh
  92870. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92871. return false;
  92872. }
  92873. ;
  92874. return true;
  92875. };
  92876. /**
  92877. * Sets the required values for both the emissive texture and and the main color.
  92878. */
  92879. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92880. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92881. if (highlightLayerMesh) {
  92882. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92883. }
  92884. else {
  92885. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92886. }
  92887. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92888. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92889. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92890. }
  92891. else {
  92892. this._emissiveTextureAndColor.texture = null;
  92893. }
  92894. };
  92895. /**
  92896. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92897. * @param mesh The mesh to exclude from the highlight layer
  92898. */
  92899. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92900. if (!this._excludedMeshes) {
  92901. return;
  92902. }
  92903. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92904. if (!meshExcluded) {
  92905. this._excludedMeshes[mesh.uniqueId] = {
  92906. mesh: mesh,
  92907. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92908. mesh.getEngine().setStencilBuffer(false);
  92909. }),
  92910. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92911. mesh.getEngine().setStencilBuffer(true);
  92912. }),
  92913. };
  92914. }
  92915. };
  92916. /**
  92917. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92918. * @param mesh The mesh to highlight
  92919. */
  92920. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92921. if (!this._excludedMeshes) {
  92922. return;
  92923. }
  92924. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92925. if (meshExcluded) {
  92926. if (meshExcluded.beforeRender) {
  92927. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92928. }
  92929. if (meshExcluded.afterRender) {
  92930. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92931. }
  92932. }
  92933. this._excludedMeshes[mesh.uniqueId] = null;
  92934. };
  92935. /**
  92936. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92937. * @param mesh mesh to test
  92938. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92939. */
  92940. HighlightLayer.prototype.hasMesh = function (mesh) {
  92941. if (!this._meshes) {
  92942. return false;
  92943. }
  92944. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92945. };
  92946. /**
  92947. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92948. * @param mesh The mesh to highlight
  92949. * @param color The color of the highlight
  92950. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92951. */
  92952. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92953. var _this = this;
  92954. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92955. if (!this._meshes) {
  92956. return;
  92957. }
  92958. var meshHighlight = this._meshes[mesh.uniqueId];
  92959. if (meshHighlight) {
  92960. meshHighlight.color = color;
  92961. }
  92962. else {
  92963. this._meshes[mesh.uniqueId] = {
  92964. mesh: mesh,
  92965. color: color,
  92966. // Lambda required for capture due to Observable this context
  92967. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92968. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92969. _this._defaultStencilReference(mesh);
  92970. }
  92971. else {
  92972. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92973. }
  92974. }),
  92975. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92976. glowEmissiveOnly: glowEmissiveOnly
  92977. };
  92978. }
  92979. this._shouldRender = true;
  92980. };
  92981. /**
  92982. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92983. * @param mesh The mesh to highlight
  92984. */
  92985. HighlightLayer.prototype.removeMesh = function (mesh) {
  92986. if (!this._meshes) {
  92987. return;
  92988. }
  92989. var meshHighlight = this._meshes[mesh.uniqueId];
  92990. if (meshHighlight) {
  92991. if (meshHighlight.observerHighlight) {
  92992. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92993. }
  92994. if (meshHighlight.observerDefault) {
  92995. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92996. }
  92997. delete this._meshes[mesh.uniqueId];
  92998. }
  92999. this._shouldRender = false;
  93000. for (var meshHighlightToCheck in this._meshes) {
  93001. if (this._meshes[meshHighlightToCheck]) {
  93002. this._shouldRender = true;
  93003. break;
  93004. }
  93005. }
  93006. };
  93007. /**
  93008. * Force the stencil to the normal expected value for none glowing parts
  93009. */
  93010. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  93011. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  93012. };
  93013. /**
  93014. * Free any resources and references associated to a mesh.
  93015. * Internal use
  93016. * @param mesh The mesh to free.
  93017. */
  93018. HighlightLayer.prototype._disposeMesh = function (mesh) {
  93019. this.removeMesh(mesh);
  93020. this.removeExcludedMesh(mesh);
  93021. };
  93022. /**
  93023. * Dispose the highlight layer and free resources.
  93024. */
  93025. HighlightLayer.prototype.dispose = function () {
  93026. if (this._meshes) {
  93027. // Clean mesh references
  93028. for (var id in this._meshes) {
  93029. var meshHighlight = this._meshes[id];
  93030. if (meshHighlight && meshHighlight.mesh) {
  93031. if (meshHighlight.observerHighlight) {
  93032. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  93033. }
  93034. if (meshHighlight.observerDefault) {
  93035. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  93036. }
  93037. }
  93038. }
  93039. this._meshes = null;
  93040. }
  93041. if (this._excludedMeshes) {
  93042. for (var id in this._excludedMeshes) {
  93043. var meshHighlight = this._excludedMeshes[id];
  93044. if (meshHighlight) {
  93045. if (meshHighlight.beforeRender) {
  93046. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  93047. }
  93048. if (meshHighlight.afterRender) {
  93049. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  93050. }
  93051. }
  93052. }
  93053. this._excludedMeshes = null;
  93054. }
  93055. _super.prototype.dispose.call(this);
  93056. };
  93057. /**
  93058. * Gets the class name of the effect layer
  93059. * @returns the string with the class name of the effect layer
  93060. */
  93061. HighlightLayer.prototype.getClassName = function () {
  93062. return "HighlightLayer";
  93063. };
  93064. /**
  93065. * Serializes this Highlight layer
  93066. * @returns a serialized Highlight layer object
  93067. */
  93068. HighlightLayer.prototype.serialize = function () {
  93069. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93070. serializationObject.customType = "BABYLON.HighlightLayer";
  93071. // Highlighted meshes
  93072. serializationObject.meshes = [];
  93073. if (this._meshes) {
  93074. for (var m in this._meshes) {
  93075. var mesh = this._meshes[m];
  93076. if (mesh) {
  93077. serializationObject.meshes.push({
  93078. glowEmissiveOnly: mesh.glowEmissiveOnly,
  93079. color: mesh.color.asArray(),
  93080. meshId: mesh.mesh.id
  93081. });
  93082. }
  93083. }
  93084. }
  93085. // Excluded meshes
  93086. serializationObject.excludedMeshes = [];
  93087. if (this._excludedMeshes) {
  93088. for (var e in this._excludedMeshes) {
  93089. var excludedMesh = this._excludedMeshes[e];
  93090. if (excludedMesh) {
  93091. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  93092. }
  93093. }
  93094. }
  93095. return serializationObject;
  93096. };
  93097. /**
  93098. * Creates a Highlight layer from parsed Highlight layer data
  93099. * @param parsedHightlightLayer defines the Highlight layer data
  93100. * @param scene defines the current scene
  93101. * @param rootUrl defines the root URL containing the Highlight layer information
  93102. * @returns a parsed Highlight layer
  93103. */
  93104. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  93105. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  93106. var index;
  93107. // Excluded meshes
  93108. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  93109. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  93110. if (mesh) {
  93111. hl.addExcludedMesh(mesh);
  93112. }
  93113. }
  93114. // Included meshes
  93115. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  93116. var highlightedMesh = parsedHightlightLayer.meshes[index];
  93117. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  93118. if (mesh) {
  93119. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  93120. }
  93121. }
  93122. return hl;
  93123. };
  93124. /**
  93125. * Effect Name of the highlight layer.
  93126. */
  93127. HighlightLayer.EffectName = "HighlightLayer";
  93128. /**
  93129. * The neutral color used during the preparation of the glow effect.
  93130. * This is black by default as the blend operation is a blend operation.
  93131. */
  93132. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  93133. /**
  93134. * Stencil value used for glowing meshes.
  93135. */
  93136. HighlightLayer.GlowingMeshStencilReference = 0x02;
  93137. /**
  93138. * Stencil value used for the other meshes in the scene.
  93139. */
  93140. HighlightLayer.NormalMeshStencilReference = 0x01;
  93141. __decorate([
  93142. BABYLON.serialize()
  93143. ], HighlightLayer.prototype, "innerGlow", void 0);
  93144. __decorate([
  93145. BABYLON.serialize()
  93146. ], HighlightLayer.prototype, "outerGlow", void 0);
  93147. __decorate([
  93148. BABYLON.serialize()
  93149. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  93150. __decorate([
  93151. BABYLON.serialize()
  93152. ], HighlightLayer.prototype, "blurVerticalSize", null);
  93153. __decorate([
  93154. BABYLON.serialize("options")
  93155. ], HighlightLayer.prototype, "_options", void 0);
  93156. return HighlightLayer;
  93157. }(BABYLON.EffectLayer));
  93158. BABYLON.HighlightLayer = HighlightLayer;
  93159. })(BABYLON || (BABYLON = {}));
  93160. //# sourceMappingURL=babylon.highlightLayer.js.map
  93161. var BABYLON;
  93162. (function (BABYLON) {
  93163. /**
  93164. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  93165. *
  93166. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93167. * glowy meshes to your scene.
  93168. *
  93169. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  93170. */
  93171. var GlowLayer = /** @class */ (function (_super) {
  93172. __extends(GlowLayer, _super);
  93173. /**
  93174. * Instantiates a new glow Layer and references it to the scene.
  93175. * @param name The name of the layer
  93176. * @param scene The scene to use the layer in
  93177. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  93178. */
  93179. function GlowLayer(name, scene, options) {
  93180. var _this = _super.call(this, name, scene) || this;
  93181. _this._intensity = 1.0;
  93182. _this._includedOnlyMeshes = [];
  93183. _this._excludedMeshes = [];
  93184. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  93185. // Adapt options
  93186. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  93187. // Initialize the layer
  93188. _this._init({
  93189. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  93190. camera: _this._options.camera,
  93191. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  93192. mainTextureRatio: _this._options.mainTextureRatio
  93193. });
  93194. return _this;
  93195. }
  93196. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  93197. /**
  93198. * Gets the kernel size of the blur.
  93199. */
  93200. get: function () {
  93201. return this._horizontalBlurPostprocess1.kernel;
  93202. },
  93203. /**
  93204. * Sets the kernel size of the blur.
  93205. */
  93206. set: function (value) {
  93207. this._horizontalBlurPostprocess1.kernel = value;
  93208. this._verticalBlurPostprocess1.kernel = value;
  93209. this._horizontalBlurPostprocess2.kernel = value;
  93210. this._verticalBlurPostprocess2.kernel = value;
  93211. },
  93212. enumerable: true,
  93213. configurable: true
  93214. });
  93215. Object.defineProperty(GlowLayer.prototype, "intensity", {
  93216. /**
  93217. * Gets the glow intensity.
  93218. */
  93219. get: function () {
  93220. return this._intensity;
  93221. },
  93222. /**
  93223. * Sets the glow intensity.
  93224. */
  93225. set: function (value) {
  93226. this._intensity = value;
  93227. },
  93228. enumerable: true,
  93229. configurable: true
  93230. });
  93231. /**
  93232. * Get the effect name of the layer.
  93233. * @return The effect name
  93234. */
  93235. GlowLayer.prototype.getEffectName = function () {
  93236. return GlowLayer.EffectName;
  93237. };
  93238. /**
  93239. * Create the merge effect. This is the shader use to blit the information back
  93240. * to the main canvas at the end of the scene rendering.
  93241. */
  93242. GlowLayer.prototype._createMergeEffect = function () {
  93243. // Effect
  93244. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  93245. };
  93246. /**
  93247. * Creates the render target textures and post processes used in the glow layer.
  93248. */
  93249. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  93250. var _this = this;
  93251. var blurTextureWidth = this._mainTextureDesiredSize.width;
  93252. var blurTextureHeight = this._mainTextureDesiredSize.height;
  93253. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  93254. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  93255. var textureType = 0;
  93256. if (this._engine.getCaps().textureHalfFloatRender) {
  93257. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93258. }
  93259. else {
  93260. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93261. }
  93262. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  93263. width: blurTextureWidth,
  93264. height: blurTextureHeight
  93265. }, this._scene, false, true, textureType);
  93266. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93267. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93268. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93269. this._blurTexture1.renderParticles = false;
  93270. this._blurTexture1.ignoreCameraViewport = true;
  93271. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  93272. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  93273. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  93274. width: blurTextureWidth2,
  93275. height: blurTextureHeight2
  93276. }, this._scene, false, true, textureType);
  93277. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93278. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93279. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93280. this._blurTexture2.renderParticles = false;
  93281. this._blurTexture2.ignoreCameraViewport = true;
  93282. this._textures = [this._blurTexture1, this._blurTexture2];
  93283. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93284. width: blurTextureWidth,
  93285. height: blurTextureHeight
  93286. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93287. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  93288. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  93289. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  93290. effect.setTexture("textureSampler", _this._mainTexture);
  93291. });
  93292. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93293. width: blurTextureWidth,
  93294. height: blurTextureHeight
  93295. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93296. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93297. width: blurTextureWidth2,
  93298. height: blurTextureHeight2
  93299. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93300. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  93301. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  93302. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  93303. effect.setTexture("textureSampler", _this._blurTexture1);
  93304. });
  93305. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93306. width: blurTextureWidth2,
  93307. height: blurTextureHeight2
  93308. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93309. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93310. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  93311. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93312. this._mainTexture.samples = this._options.mainTextureSamples;
  93313. this._mainTexture.onAfterUnbindObservable.add(function () {
  93314. var internalTexture = _this._blurTexture1.getInternalTexture();
  93315. if (internalTexture) {
  93316. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  93317. internalTexture = _this._blurTexture2.getInternalTexture();
  93318. if (internalTexture) {
  93319. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  93320. }
  93321. }
  93322. });
  93323. // Prevent autoClear.
  93324. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  93325. };
  93326. /**
  93327. * Checks for the readiness of the element composing the layer.
  93328. * @param subMesh the mesh to check for
  93329. * @param useInstances specify wether or not to use instances to render the mesh
  93330. * @param emissiveTexture the associated emissive texture used to generate the glow
  93331. * @return true if ready otherwise, false
  93332. */
  93333. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  93334. var material = subMesh.getMaterial();
  93335. var mesh = subMesh.getRenderingMesh();
  93336. if (!material || !mesh) {
  93337. return false;
  93338. }
  93339. var emissiveTexture = material.emissiveTexture;
  93340. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93341. };
  93342. /**
  93343. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93344. */
  93345. GlowLayer.prototype.needStencil = function () {
  93346. return false;
  93347. };
  93348. /**
  93349. * Implementation specific of rendering the generating effect on the main canvas.
  93350. * @param effect The effect used to render through
  93351. */
  93352. GlowLayer.prototype._internalRender = function (effect) {
  93353. // Texture
  93354. effect.setTexture("textureSampler", this._blurTexture1);
  93355. effect.setTexture("textureSampler2", this._blurTexture2);
  93356. effect.setFloat("offset", this._intensity);
  93357. // Cache
  93358. var engine = this._engine;
  93359. var previousStencilBuffer = engine.getStencilBuffer();
  93360. // Draw order
  93361. engine.setStencilBuffer(false);
  93362. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93363. // Draw order
  93364. engine.setStencilBuffer(previousStencilBuffer);
  93365. };
  93366. /**
  93367. * Sets the required values for both the emissive texture and and the main color.
  93368. */
  93369. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93370. var textureLevel = 1.0;
  93371. if (this.customEmissiveTextureSelector) {
  93372. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  93373. }
  93374. else {
  93375. if (material) {
  93376. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93377. if (this._emissiveTextureAndColor.texture) {
  93378. textureLevel = this._emissiveTextureAndColor.texture.level;
  93379. }
  93380. }
  93381. else {
  93382. this._emissiveTextureAndColor.texture = null;
  93383. }
  93384. }
  93385. if (this.customEmissiveColorSelector) {
  93386. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  93387. }
  93388. else {
  93389. if (material.emissiveColor) {
  93390. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  93391. }
  93392. else {
  93393. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93394. }
  93395. }
  93396. };
  93397. /**
  93398. * Returns true if the mesh should render, otherwise false.
  93399. * @param mesh The mesh to render
  93400. * @returns true if it should render otherwise false
  93401. */
  93402. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  93403. return this.hasMesh(mesh);
  93404. };
  93405. /**
  93406. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  93407. * @param mesh The mesh to exclude from the glow layer
  93408. */
  93409. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  93410. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  93411. this._excludedMeshes.push(mesh.uniqueId);
  93412. }
  93413. };
  93414. /**
  93415. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  93416. * @param mesh The mesh to remove
  93417. */
  93418. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  93419. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  93420. if (index !== -1) {
  93421. this._excludedMeshes.splice(index, 1);
  93422. }
  93423. };
  93424. /**
  93425. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  93426. * @param mesh The mesh to include in the glow layer
  93427. */
  93428. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  93429. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  93430. this._includedOnlyMeshes.push(mesh.uniqueId);
  93431. }
  93432. };
  93433. /**
  93434. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  93435. * @param mesh The mesh to remove
  93436. */
  93437. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  93438. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  93439. if (index !== -1) {
  93440. this._includedOnlyMeshes.splice(index, 1);
  93441. }
  93442. };
  93443. /**
  93444. * Determine if a given mesh will be used in the glow layer
  93445. * @param mesh The mesh to test
  93446. * @returns true if the mesh will be highlighted by the current glow layer
  93447. */
  93448. GlowLayer.prototype.hasMesh = function (mesh) {
  93449. // Included Mesh
  93450. if (this._includedOnlyMeshes.length) {
  93451. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  93452. }
  93453. ;
  93454. // Excluded Mesh
  93455. if (this._excludedMeshes.length) {
  93456. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  93457. }
  93458. ;
  93459. return true;
  93460. };
  93461. /**
  93462. * Free any resources and references associated to a mesh.
  93463. * Internal use
  93464. * @param mesh The mesh to free.
  93465. */
  93466. GlowLayer.prototype._disposeMesh = function (mesh) {
  93467. this.removeIncludedOnlyMesh(mesh);
  93468. this.removeExcludedMesh(mesh);
  93469. };
  93470. /**
  93471. * Gets the class name of the effect layer
  93472. * @returns the string with the class name of the effect layer
  93473. */
  93474. GlowLayer.prototype.getClassName = function () {
  93475. return "GlowLayer";
  93476. };
  93477. /**
  93478. * Serializes this glow layer
  93479. * @returns a serialized glow layer object
  93480. */
  93481. GlowLayer.prototype.serialize = function () {
  93482. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93483. serializationObject.customType = "BABYLON.GlowLayer";
  93484. var index;
  93485. // Included meshes
  93486. serializationObject.includedMeshes = [];
  93487. if (this._includedOnlyMeshes.length) {
  93488. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  93489. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  93490. if (mesh) {
  93491. serializationObject.includedMeshes.push(mesh.id);
  93492. }
  93493. }
  93494. }
  93495. // Excluded meshes
  93496. serializationObject.excludedMeshes = [];
  93497. if (this._excludedMeshes.length) {
  93498. for (index = 0; index < this._excludedMeshes.length; index++) {
  93499. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  93500. if (mesh) {
  93501. serializationObject.excludedMeshes.push(mesh.id);
  93502. }
  93503. }
  93504. }
  93505. return serializationObject;
  93506. };
  93507. /**
  93508. * Creates a Glow Layer from parsed glow layer data
  93509. * @param parsedGlowLayer defines glow layer data
  93510. * @param scene defines the current scene
  93511. * @param rootUrl defines the root URL containing the glow layer information
  93512. * @returns a parsed Glow Layer
  93513. */
  93514. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  93515. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  93516. var index;
  93517. // Excluded meshes
  93518. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  93519. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  93520. if (mesh) {
  93521. gl.addExcludedMesh(mesh);
  93522. }
  93523. }
  93524. // Included meshes
  93525. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  93526. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  93527. if (mesh) {
  93528. gl.addIncludedOnlyMesh(mesh);
  93529. }
  93530. }
  93531. return gl;
  93532. };
  93533. /**
  93534. * Effect Name of the layer.
  93535. */
  93536. GlowLayer.EffectName = "GlowLayer";
  93537. /**
  93538. * The default blur kernel size used for the glow.
  93539. */
  93540. GlowLayer.DefaultBlurKernelSize = 32;
  93541. /**
  93542. * The default texture size ratio used for the glow.
  93543. */
  93544. GlowLayer.DefaultTextureRatio = 0.5;
  93545. __decorate([
  93546. BABYLON.serialize()
  93547. ], GlowLayer.prototype, "blurKernelSize", null);
  93548. __decorate([
  93549. BABYLON.serialize()
  93550. ], GlowLayer.prototype, "intensity", null);
  93551. __decorate([
  93552. BABYLON.serialize("options")
  93553. ], GlowLayer.prototype, "_options", void 0);
  93554. return GlowLayer;
  93555. }(BABYLON.EffectLayer));
  93556. BABYLON.GlowLayer = GlowLayer;
  93557. })(BABYLON || (BABYLON = {}));
  93558. //# sourceMappingURL=babylon.glowLayer.js.map
  93559. var BABYLON;
  93560. (function (BABYLON) {
  93561. /**
  93562. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  93563. */
  93564. var AssetTaskState;
  93565. (function (AssetTaskState) {
  93566. /**
  93567. * Initialization
  93568. */
  93569. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  93570. /**
  93571. * Running
  93572. */
  93573. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  93574. /**
  93575. * Done
  93576. */
  93577. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  93578. /**
  93579. * Error
  93580. */
  93581. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  93582. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  93583. /**
  93584. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  93585. */
  93586. var AbstractAssetTask = /** @class */ (function () {
  93587. /**
  93588. * Creates a new {BABYLON.AssetsManager}
  93589. * @param name defines the name of the task
  93590. */
  93591. function AbstractAssetTask(
  93592. /**
  93593. * Task name
  93594. */ name) {
  93595. this.name = name;
  93596. this._isCompleted = false;
  93597. this._taskState = AssetTaskState.INIT;
  93598. }
  93599. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  93600. /**
  93601. * Get if the task is completed
  93602. */
  93603. get: function () {
  93604. return this._isCompleted;
  93605. },
  93606. enumerable: true,
  93607. configurable: true
  93608. });
  93609. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93610. /**
  93611. * Gets the current state of the task
  93612. */
  93613. get: function () {
  93614. return this._taskState;
  93615. },
  93616. enumerable: true,
  93617. configurable: true
  93618. });
  93619. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93620. /**
  93621. * Gets the current error object (if task is in error)
  93622. */
  93623. get: function () {
  93624. return this._errorObject;
  93625. },
  93626. enumerable: true,
  93627. configurable: true
  93628. });
  93629. /**
  93630. * Internal only
  93631. * @hidden
  93632. */
  93633. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93634. if (this._errorObject) {
  93635. return;
  93636. }
  93637. this._errorObject = {
  93638. message: message,
  93639. exception: exception
  93640. };
  93641. };
  93642. /**
  93643. * Execute the current task
  93644. * @param scene defines the scene where you want your assets to be loaded
  93645. * @param onSuccess is a callback called when the task is successfully executed
  93646. * @param onError is a callback called if an error occurs
  93647. */
  93648. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93649. var _this = this;
  93650. this._taskState = AssetTaskState.RUNNING;
  93651. this.runTask(scene, function () {
  93652. _this.onDoneCallback(onSuccess, onError);
  93653. }, function (msg, exception) {
  93654. _this.onErrorCallback(onError, msg, exception);
  93655. });
  93656. };
  93657. /**
  93658. * Execute the current task
  93659. * @param scene defines the scene where you want your assets to be loaded
  93660. * @param onSuccess is a callback called when the task is successfully executed
  93661. * @param onError is a callback called if an error occurs
  93662. */
  93663. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93664. throw new Error("runTask is not implemented");
  93665. };
  93666. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93667. this._taskState = AssetTaskState.ERROR;
  93668. this._errorObject = {
  93669. message: message,
  93670. exception: exception
  93671. };
  93672. if (this.onError) {
  93673. this.onError(this, message, exception);
  93674. }
  93675. onError();
  93676. };
  93677. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93678. try {
  93679. this._taskState = AssetTaskState.DONE;
  93680. this._isCompleted = true;
  93681. if (this.onSuccess) {
  93682. this.onSuccess(this);
  93683. }
  93684. onSuccess();
  93685. }
  93686. catch (e) {
  93687. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93688. }
  93689. };
  93690. return AbstractAssetTask;
  93691. }());
  93692. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93693. /**
  93694. * Class used to share progress information about assets loading
  93695. */
  93696. var AssetsProgressEvent = /** @class */ (function () {
  93697. /**
  93698. * Creates a {BABYLON.AssetsProgressEvent}
  93699. * @param remainingCount defines the number of remaining tasks to process
  93700. * @param totalCount defines the total number of tasks
  93701. * @param task defines the task that was just processed
  93702. */
  93703. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93704. this.remainingCount = remainingCount;
  93705. this.totalCount = totalCount;
  93706. this.task = task;
  93707. }
  93708. return AssetsProgressEvent;
  93709. }());
  93710. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93711. /**
  93712. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93713. */
  93714. var MeshAssetTask = /** @class */ (function (_super) {
  93715. __extends(MeshAssetTask, _super);
  93716. /**
  93717. * Creates a new {BABYLON.MeshAssetTask}
  93718. * @param name defines the name of the task
  93719. * @param meshesNames defines the list of mesh's names you want to load
  93720. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93721. * @param sceneFilename defines the filename of the scene to load from
  93722. */
  93723. function MeshAssetTask(
  93724. /**
  93725. * Defines the name of the task
  93726. */
  93727. name,
  93728. /**
  93729. * Defines the list of mesh's names you want to load
  93730. */
  93731. meshesNames,
  93732. /**
  93733. * Defines the root url to use as a base to load your meshes and associated resources
  93734. */
  93735. rootUrl,
  93736. /**
  93737. * Defines the filename of the scene to load from
  93738. */
  93739. sceneFilename) {
  93740. var _this = _super.call(this, name) || this;
  93741. _this.name = name;
  93742. _this.meshesNames = meshesNames;
  93743. _this.rootUrl = rootUrl;
  93744. _this.sceneFilename = sceneFilename;
  93745. return _this;
  93746. }
  93747. /**
  93748. * Execute the current task
  93749. * @param scene defines the scene where you want your assets to be loaded
  93750. * @param onSuccess is a callback called when the task is successfully executed
  93751. * @param onError is a callback called if an error occurs
  93752. */
  93753. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93754. var _this = this;
  93755. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93756. _this.loadedMeshes = meshes;
  93757. _this.loadedParticleSystems = particleSystems;
  93758. _this.loadedSkeletons = skeletons;
  93759. onSuccess();
  93760. }, null, function (scene, message, exception) {
  93761. onError(message, exception);
  93762. });
  93763. };
  93764. return MeshAssetTask;
  93765. }(AbstractAssetTask));
  93766. BABYLON.MeshAssetTask = MeshAssetTask;
  93767. /**
  93768. * Define a task used by {BABYLON.AssetsManager} to load text content
  93769. */
  93770. var TextFileAssetTask = /** @class */ (function (_super) {
  93771. __extends(TextFileAssetTask, _super);
  93772. /**
  93773. * Creates a new TextFileAssetTask object
  93774. * @param name defines the name of the task
  93775. * @param url defines the location of the file to load
  93776. */
  93777. function TextFileAssetTask(
  93778. /**
  93779. * Defines the name of the task
  93780. */
  93781. name,
  93782. /**
  93783. * Defines the location of the file to load
  93784. */
  93785. url) {
  93786. var _this = _super.call(this, name) || this;
  93787. _this.name = name;
  93788. _this.url = url;
  93789. return _this;
  93790. }
  93791. /**
  93792. * Execute the current task
  93793. * @param scene defines the scene where you want your assets to be loaded
  93794. * @param onSuccess is a callback called when the task is successfully executed
  93795. * @param onError is a callback called if an error occurs
  93796. */
  93797. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93798. var _this = this;
  93799. scene._loadFile(this.url, function (data) {
  93800. _this.text = data;
  93801. onSuccess();
  93802. }, undefined, false, false, function (request, exception) {
  93803. if (request) {
  93804. onError(request.status + " " + request.statusText, exception);
  93805. }
  93806. });
  93807. };
  93808. return TextFileAssetTask;
  93809. }(AbstractAssetTask));
  93810. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93811. /**
  93812. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93813. */
  93814. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93815. __extends(BinaryFileAssetTask, _super);
  93816. /**
  93817. * Creates a new BinaryFileAssetTask object
  93818. * @param name defines the name of the new task
  93819. * @param url defines the location of the file to load
  93820. */
  93821. function BinaryFileAssetTask(
  93822. /**
  93823. * Defines the name of the task
  93824. */
  93825. name,
  93826. /**
  93827. * Defines the location of the file to load
  93828. */
  93829. url) {
  93830. var _this = _super.call(this, name) || this;
  93831. _this.name = name;
  93832. _this.url = url;
  93833. return _this;
  93834. }
  93835. /**
  93836. * Execute the current task
  93837. * @param scene defines the scene where you want your assets to be loaded
  93838. * @param onSuccess is a callback called when the task is successfully executed
  93839. * @param onError is a callback called if an error occurs
  93840. */
  93841. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93842. var _this = this;
  93843. scene._loadFile(this.url, function (data) {
  93844. _this.data = data;
  93845. onSuccess();
  93846. }, undefined, true, true, function (request, exception) {
  93847. if (request) {
  93848. onError(request.status + " " + request.statusText, exception);
  93849. }
  93850. });
  93851. };
  93852. return BinaryFileAssetTask;
  93853. }(AbstractAssetTask));
  93854. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93855. /**
  93856. * Define a task used by {BABYLON.AssetsManager} to load images
  93857. */
  93858. var ImageAssetTask = /** @class */ (function (_super) {
  93859. __extends(ImageAssetTask, _super);
  93860. /**
  93861. * Creates a new ImageAssetTask
  93862. * @param name defines the name of the task
  93863. * @param url defines the location of the image to load
  93864. */
  93865. function ImageAssetTask(
  93866. /**
  93867. * Defines the name of the task
  93868. */
  93869. name,
  93870. /**
  93871. * Defines the location of the image to load
  93872. */
  93873. url) {
  93874. var _this = _super.call(this, name) || this;
  93875. _this.name = name;
  93876. _this.url = url;
  93877. return _this;
  93878. }
  93879. /**
  93880. * Execute the current task
  93881. * @param scene defines the scene where you want your assets to be loaded
  93882. * @param onSuccess is a callback called when the task is successfully executed
  93883. * @param onError is a callback called if an error occurs
  93884. */
  93885. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93886. var _this = this;
  93887. var img = new Image();
  93888. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93889. img.onload = function () {
  93890. _this.image = img;
  93891. onSuccess();
  93892. };
  93893. img.onerror = function (err) {
  93894. onError("Error loading image", err);
  93895. };
  93896. img.src = this.url;
  93897. };
  93898. return ImageAssetTask;
  93899. }(AbstractAssetTask));
  93900. BABYLON.ImageAssetTask = ImageAssetTask;
  93901. /**
  93902. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93903. */
  93904. var TextureAssetTask = /** @class */ (function (_super) {
  93905. __extends(TextureAssetTask, _super);
  93906. /**
  93907. * Creates a new TextureAssetTask object
  93908. * @param name defines the name of the task
  93909. * @param url defines the location of the file to load
  93910. * @param noMipmap defines if mipmap should not be generated (default is false)
  93911. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93912. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93913. */
  93914. function TextureAssetTask(
  93915. /**
  93916. * Defines the name of the task
  93917. */
  93918. name,
  93919. /**
  93920. * Defines the location of the file to load
  93921. */
  93922. url,
  93923. /**
  93924. * Defines if mipmap should not be generated (default is false)
  93925. */
  93926. noMipmap,
  93927. /**
  93928. * Defines if texture must be inverted on Y axis (default is false)
  93929. */
  93930. invertY,
  93931. /**
  93932. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93933. */
  93934. samplingMode) {
  93935. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93936. var _this = _super.call(this, name) || this;
  93937. _this.name = name;
  93938. _this.url = url;
  93939. _this.noMipmap = noMipmap;
  93940. _this.invertY = invertY;
  93941. _this.samplingMode = samplingMode;
  93942. return _this;
  93943. }
  93944. /**
  93945. * Execute the current task
  93946. * @param scene defines the scene where you want your assets to be loaded
  93947. * @param onSuccess is a callback called when the task is successfully executed
  93948. * @param onError is a callback called if an error occurs
  93949. */
  93950. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93951. var onload = function () {
  93952. onSuccess();
  93953. };
  93954. var onerror = function (message, exception) {
  93955. onError(message, exception);
  93956. };
  93957. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93958. };
  93959. return TextureAssetTask;
  93960. }(AbstractAssetTask));
  93961. BABYLON.TextureAssetTask = TextureAssetTask;
  93962. /**
  93963. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93964. */
  93965. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93966. __extends(CubeTextureAssetTask, _super);
  93967. /**
  93968. * Creates a new CubeTextureAssetTask
  93969. * @param name defines the name of the task
  93970. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93971. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93972. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93973. * @param files defines the explicit list of files (undefined by default)
  93974. */
  93975. function CubeTextureAssetTask(
  93976. /**
  93977. * Defines the name of the task
  93978. */
  93979. name,
  93980. /**
  93981. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93982. */
  93983. url,
  93984. /**
  93985. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93986. */
  93987. extensions,
  93988. /**
  93989. * Defines if mipmaps should not be generated (default is false)
  93990. */
  93991. noMipmap,
  93992. /**
  93993. * Defines the explicit list of files (undefined by default)
  93994. */
  93995. files) {
  93996. var _this = _super.call(this, name) || this;
  93997. _this.name = name;
  93998. _this.url = url;
  93999. _this.extensions = extensions;
  94000. _this.noMipmap = noMipmap;
  94001. _this.files = files;
  94002. return _this;
  94003. }
  94004. /**
  94005. * Execute the current task
  94006. * @param scene defines the scene where you want your assets to be loaded
  94007. * @param onSuccess is a callback called when the task is successfully executed
  94008. * @param onError is a callback called if an error occurs
  94009. */
  94010. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94011. var onload = function () {
  94012. onSuccess();
  94013. };
  94014. var onerror = function (message, exception) {
  94015. onError(message, exception);
  94016. };
  94017. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  94018. };
  94019. return CubeTextureAssetTask;
  94020. }(AbstractAssetTask));
  94021. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  94022. /**
  94023. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  94024. */
  94025. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  94026. __extends(HDRCubeTextureAssetTask, _super);
  94027. /**
  94028. * Creates a new HDRCubeTextureAssetTask object
  94029. * @param name defines the name of the task
  94030. * @param url defines the location of the file to load
  94031. * @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.
  94032. * @param noMipmap defines if mipmaps should not be generated (default is false)
  94033. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  94034. * @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)
  94035. * @param reserved Internal use only
  94036. */
  94037. function HDRCubeTextureAssetTask(
  94038. /**
  94039. * Defines the name of the task
  94040. */
  94041. name,
  94042. /**
  94043. * Defines the location of the file to load
  94044. */
  94045. url,
  94046. /**
  94047. * Defines the desired size (the more it increases the longer the generation will be)
  94048. */
  94049. size,
  94050. /**
  94051. * Defines if mipmaps should not be generated (default is false)
  94052. */
  94053. noMipmap,
  94054. /**
  94055. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  94056. */
  94057. generateHarmonics,
  94058. /**
  94059. * 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)
  94060. */
  94061. gammaSpace,
  94062. /**
  94063. * Internal Use Only
  94064. */
  94065. reserved) {
  94066. if (noMipmap === void 0) { noMipmap = false; }
  94067. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94068. if (gammaSpace === void 0) { gammaSpace = false; }
  94069. if (reserved === void 0) { reserved = false; }
  94070. var _this = _super.call(this, name) || this;
  94071. _this.name = name;
  94072. _this.url = url;
  94073. _this.size = size;
  94074. _this.noMipmap = noMipmap;
  94075. _this.generateHarmonics = generateHarmonics;
  94076. _this.gammaSpace = gammaSpace;
  94077. _this.reserved = reserved;
  94078. return _this;
  94079. }
  94080. /**
  94081. * Execute the current task
  94082. * @param scene defines the scene where you want your assets to be loaded
  94083. * @param onSuccess is a callback called when the task is successfully executed
  94084. * @param onError is a callback called if an error occurs
  94085. */
  94086. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  94087. var onload = function () {
  94088. onSuccess();
  94089. };
  94090. var onerror = function (message, exception) {
  94091. onError(message, exception);
  94092. };
  94093. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  94094. };
  94095. return HDRCubeTextureAssetTask;
  94096. }(AbstractAssetTask));
  94097. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  94098. /**
  94099. * This class can be used to easily import assets into a scene
  94100. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  94101. */
  94102. var AssetsManager = /** @class */ (function () {
  94103. /**
  94104. * Creates a new AssetsManager
  94105. * @param scene defines the scene to work on
  94106. */
  94107. function AssetsManager(scene) {
  94108. this._isLoading = false;
  94109. this._tasks = new Array();
  94110. this._waitingTasksCount = 0;
  94111. this._totalTasksCount = 0;
  94112. /**
  94113. * Observable called when all tasks are processed
  94114. */
  94115. this.onTaskSuccessObservable = new BABYLON.Observable();
  94116. /**
  94117. * Observable called when a task had an error
  94118. */
  94119. this.onTaskErrorObservable = new BABYLON.Observable();
  94120. /**
  94121. * Observable called when a task is successful
  94122. */
  94123. this.onTasksDoneObservable = new BABYLON.Observable();
  94124. /**
  94125. * Observable called when a task is done (whatever the result is)
  94126. */
  94127. this.onProgressObservable = new BABYLON.Observable();
  94128. /**
  94129. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  94130. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  94131. */
  94132. this.useDefaultLoadingScreen = true;
  94133. this._scene = scene;
  94134. }
  94135. /**
  94136. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  94137. * @param taskName defines the name of the new task
  94138. * @param meshesNames defines the name of meshes to load
  94139. * @param rootUrl defines the root url to use to locate files
  94140. * @param sceneFilename defines the filename of the scene file
  94141. * @returns a new {BABYLON.MeshAssetTask} object
  94142. */
  94143. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  94144. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  94145. this._tasks.push(task);
  94146. return task;
  94147. };
  94148. /**
  94149. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  94150. * @param taskName defines the name of the new task
  94151. * @param url defines the url of the file to load
  94152. * @returns a new {BABYLON.TextFileAssetTask} object
  94153. */
  94154. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  94155. var task = new TextFileAssetTask(taskName, url);
  94156. this._tasks.push(task);
  94157. return task;
  94158. };
  94159. /**
  94160. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  94161. * @param taskName defines the name of the new task
  94162. * @param url defines the url of the file to load
  94163. * @returns a new {BABYLON.BinaryFileAssetTask} object
  94164. */
  94165. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  94166. var task = new BinaryFileAssetTask(taskName, url);
  94167. this._tasks.push(task);
  94168. return task;
  94169. };
  94170. /**
  94171. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  94172. * @param taskName defines the name of the new task
  94173. * @param url defines the url of the file to load
  94174. * @returns a new {BABYLON.ImageAssetTask} object
  94175. */
  94176. AssetsManager.prototype.addImageTask = function (taskName, url) {
  94177. var task = new ImageAssetTask(taskName, url);
  94178. this._tasks.push(task);
  94179. return task;
  94180. };
  94181. /**
  94182. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  94183. * @param taskName defines the name of the new task
  94184. * @param url defines the url of the file to load
  94185. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94186. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  94187. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  94188. * @returns a new {BABYLON.TextureAssetTask} object
  94189. */
  94190. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  94191. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94192. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  94193. this._tasks.push(task);
  94194. return task;
  94195. };
  94196. /**
  94197. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  94198. * @param taskName defines the name of the new task
  94199. * @param url defines the url of the file to load
  94200. * @param extensions defines the extension to use to load the cube map (can be null)
  94201. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94202. * @param files defines the list of files to load (can be null)
  94203. * @returns a new {BABYLON.CubeTextureAssetTask} object
  94204. */
  94205. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  94206. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  94207. this._tasks.push(task);
  94208. return task;
  94209. };
  94210. /**
  94211. *
  94212. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  94213. * @param taskName defines the name of the new task
  94214. * @param url defines the url of the file to load
  94215. * @param size defines the size you want for the cubemap (can be null)
  94216. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94217. * @param generateHarmonics defines if you want to automatically generate (true by default)
  94218. * @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)
  94219. * @param reserved Internal use only
  94220. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  94221. */
  94222. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  94223. if (noMipmap === void 0) { noMipmap = false; }
  94224. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94225. if (gammaSpace === void 0) { gammaSpace = false; }
  94226. if (reserved === void 0) { reserved = false; }
  94227. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  94228. this._tasks.push(task);
  94229. return task;
  94230. };
  94231. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  94232. this._waitingTasksCount--;
  94233. try {
  94234. if (this.onProgress) {
  94235. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  94236. }
  94237. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  94238. }
  94239. catch (e) {
  94240. BABYLON.Tools.Error("Error running progress callbacks.");
  94241. console.log(e);
  94242. }
  94243. if (this._waitingTasksCount === 0) {
  94244. try {
  94245. if (this.onFinish) {
  94246. this.onFinish(this._tasks);
  94247. }
  94248. // Let's remove successfull tasks
  94249. var currentTasks = this._tasks.slice();
  94250. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  94251. var task = currentTasks_1[_i];
  94252. if (task.taskState === AssetTaskState.DONE) {
  94253. var index = this._tasks.indexOf(task);
  94254. if (index > -1) {
  94255. this._tasks.splice(index, 1);
  94256. }
  94257. }
  94258. }
  94259. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94260. }
  94261. catch (e) {
  94262. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  94263. console.log(e);
  94264. }
  94265. this._isLoading = false;
  94266. this._scene.getEngine().hideLoadingUI();
  94267. }
  94268. };
  94269. AssetsManager.prototype._runTask = function (task) {
  94270. var _this = this;
  94271. var done = function () {
  94272. try {
  94273. if (_this.onTaskSuccess) {
  94274. _this.onTaskSuccess(task);
  94275. }
  94276. _this.onTaskSuccessObservable.notifyObservers(task);
  94277. _this._decreaseWaitingTasksCount(task);
  94278. }
  94279. catch (e) {
  94280. error("Error executing task success callbacks", e);
  94281. }
  94282. };
  94283. var error = function (message, exception) {
  94284. task._setErrorObject(message, exception);
  94285. if (_this.onTaskError) {
  94286. _this.onTaskError(task);
  94287. }
  94288. _this.onTaskErrorObservable.notifyObservers(task);
  94289. _this._decreaseWaitingTasksCount(task);
  94290. };
  94291. task.run(this._scene, done, error);
  94292. };
  94293. /**
  94294. * Reset the {BABYLON.AssetsManager} and remove all tasks
  94295. * @return the current instance of the {BABYLON.AssetsManager}
  94296. */
  94297. AssetsManager.prototype.reset = function () {
  94298. this._isLoading = false;
  94299. this._tasks = new Array();
  94300. return this;
  94301. };
  94302. /**
  94303. * Start the loading process
  94304. * @return the current instance of the {BABYLON.AssetsManager}
  94305. */
  94306. AssetsManager.prototype.load = function () {
  94307. if (this._isLoading) {
  94308. return this;
  94309. }
  94310. this._isLoading = true;
  94311. this._waitingTasksCount = this._tasks.length;
  94312. this._totalTasksCount = this._tasks.length;
  94313. if (this._waitingTasksCount === 0) {
  94314. this._isLoading = false;
  94315. if (this.onFinish) {
  94316. this.onFinish(this._tasks);
  94317. }
  94318. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94319. return this;
  94320. }
  94321. if (this.useDefaultLoadingScreen) {
  94322. this._scene.getEngine().displayLoadingUI();
  94323. }
  94324. for (var index = 0; index < this._tasks.length; index++) {
  94325. var task = this._tasks[index];
  94326. this._runTask(task);
  94327. }
  94328. return this;
  94329. };
  94330. return AssetsManager;
  94331. }());
  94332. BABYLON.AssetsManager = AssetsManager;
  94333. })(BABYLON || (BABYLON = {}));
  94334. //# sourceMappingURL=babylon.assetsManager.js.map
  94335. var BABYLON;
  94336. (function (BABYLON) {
  94337. var serializedGeometries = [];
  94338. var serializeGeometry = function (geometry, serializationGeometries) {
  94339. if (serializedGeometries[geometry.id]) {
  94340. return;
  94341. }
  94342. if (geometry.doNotSerialize) {
  94343. return;
  94344. }
  94345. if (geometry instanceof BABYLON.BoxGeometry) {
  94346. serializationGeometries.boxes.push(geometry.serialize());
  94347. }
  94348. else if (geometry instanceof BABYLON.SphereGeometry) {
  94349. serializationGeometries.spheres.push(geometry.serialize());
  94350. }
  94351. else if (geometry instanceof BABYLON.CylinderGeometry) {
  94352. serializationGeometries.cylinders.push(geometry.serialize());
  94353. }
  94354. else if (geometry instanceof BABYLON.TorusGeometry) {
  94355. serializationGeometries.toruses.push(geometry.serialize());
  94356. }
  94357. else if (geometry instanceof BABYLON.GroundGeometry) {
  94358. serializationGeometries.grounds.push(geometry.serialize());
  94359. }
  94360. else if (geometry instanceof BABYLON.Plane) {
  94361. serializationGeometries.planes.push(geometry.serialize());
  94362. }
  94363. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  94364. serializationGeometries.torusKnots.push(geometry.serialize());
  94365. }
  94366. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  94367. throw new Error("Unknown primitive type");
  94368. }
  94369. else {
  94370. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  94371. }
  94372. serializedGeometries[geometry.id] = true;
  94373. };
  94374. var serializeMesh = function (mesh, serializationScene) {
  94375. var serializationObject = {};
  94376. // Geometry
  94377. var geometry = mesh._geometry;
  94378. if (geometry) {
  94379. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  94380. // 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
  94381. serializeGeometry(geometry, serializationScene.geometries);
  94382. }
  94383. }
  94384. // Custom
  94385. if (mesh.serialize) {
  94386. mesh.serialize(serializationObject);
  94387. }
  94388. return serializationObject;
  94389. };
  94390. var finalizeSingleMesh = function (mesh, serializationObject) {
  94391. //only works if the mesh is already loaded
  94392. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94393. //serialize material
  94394. if (mesh.material) {
  94395. if (mesh.material instanceof BABYLON.StandardMaterial) {
  94396. serializationObject.materials = serializationObject.materials || [];
  94397. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94398. serializationObject.materials.push(mesh.material.serialize());
  94399. }
  94400. }
  94401. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  94402. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  94403. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94404. serializationObject.multiMaterials.push(mesh.material.serialize());
  94405. }
  94406. }
  94407. }
  94408. //serialize geometry
  94409. var geometry = mesh._geometry;
  94410. if (geometry) {
  94411. if (!serializationObject.geometries) {
  94412. serializationObject.geometries = {};
  94413. serializationObject.geometries.boxes = [];
  94414. serializationObject.geometries.spheres = [];
  94415. serializationObject.geometries.cylinders = [];
  94416. serializationObject.geometries.toruses = [];
  94417. serializationObject.geometries.grounds = [];
  94418. serializationObject.geometries.planes = [];
  94419. serializationObject.geometries.torusKnots = [];
  94420. serializationObject.geometries.vertexData = [];
  94421. }
  94422. serializeGeometry(geometry, serializationObject.geometries);
  94423. }
  94424. // Skeletons
  94425. if (mesh.skeleton) {
  94426. serializationObject.skeletons = serializationObject.skeletons || [];
  94427. serializationObject.skeletons.push(mesh.skeleton.serialize());
  94428. }
  94429. //serialize the actual mesh
  94430. serializationObject.meshes = serializationObject.meshes || [];
  94431. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94432. }
  94433. };
  94434. var SceneSerializer = /** @class */ (function () {
  94435. function SceneSerializer() {
  94436. }
  94437. SceneSerializer.ClearCache = function () {
  94438. serializedGeometries = [];
  94439. };
  94440. SceneSerializer.Serialize = function (scene) {
  94441. var serializationObject = {};
  94442. SceneSerializer.ClearCache();
  94443. // Scene
  94444. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  94445. serializationObject.autoClear = scene.autoClear;
  94446. serializationObject.clearColor = scene.clearColor.asArray();
  94447. serializationObject.ambientColor = scene.ambientColor.asArray();
  94448. serializationObject.gravity = scene.gravity.asArray();
  94449. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  94450. serializationObject.workerCollisions = scene.workerCollisions;
  94451. // Fog
  94452. if (scene.fogMode && scene.fogMode !== 0) {
  94453. serializationObject.fogMode = scene.fogMode;
  94454. serializationObject.fogColor = scene.fogColor.asArray();
  94455. serializationObject.fogStart = scene.fogStart;
  94456. serializationObject.fogEnd = scene.fogEnd;
  94457. serializationObject.fogDensity = scene.fogDensity;
  94458. }
  94459. //Physics
  94460. if (scene.isPhysicsEnabled()) {
  94461. var physicEngine = scene.getPhysicsEngine();
  94462. if (physicEngine) {
  94463. serializationObject.physicsEnabled = true;
  94464. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  94465. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  94466. }
  94467. }
  94468. // Metadata
  94469. if (scene.metadata) {
  94470. serializationObject.metadata = scene.metadata;
  94471. }
  94472. // Morph targets
  94473. serializationObject.morphTargetManagers = [];
  94474. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  94475. var abstractMesh = _a[_i];
  94476. var manager = abstractMesh.morphTargetManager;
  94477. if (manager) {
  94478. serializationObject.morphTargetManagers.push(manager.serialize());
  94479. }
  94480. }
  94481. // Lights
  94482. serializationObject.lights = [];
  94483. var index;
  94484. var light;
  94485. for (index = 0; index < scene.lights.length; index++) {
  94486. light = scene.lights[index];
  94487. if (!light.doNotSerialize) {
  94488. serializationObject.lights.push(light.serialize());
  94489. }
  94490. }
  94491. // Cameras
  94492. serializationObject.cameras = [];
  94493. for (index = 0; index < scene.cameras.length; index++) {
  94494. var camera = scene.cameras[index];
  94495. if (!camera.doNotSerialize) {
  94496. serializationObject.cameras.push(camera.serialize());
  94497. }
  94498. }
  94499. if (scene.activeCamera) {
  94500. serializationObject.activeCameraID = scene.activeCamera.id;
  94501. }
  94502. // Animations
  94503. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  94504. // Materials
  94505. serializationObject.materials = [];
  94506. serializationObject.multiMaterials = [];
  94507. var material;
  94508. for (index = 0; index < scene.materials.length; index++) {
  94509. material = scene.materials[index];
  94510. if (!material.doNotSerialize) {
  94511. serializationObject.materials.push(material.serialize());
  94512. }
  94513. }
  94514. // MultiMaterials
  94515. serializationObject.multiMaterials = [];
  94516. for (index = 0; index < scene.multiMaterials.length; index++) {
  94517. var multiMaterial = scene.multiMaterials[index];
  94518. serializationObject.multiMaterials.push(multiMaterial.serialize());
  94519. }
  94520. // Environment texture
  94521. if (scene.environmentTexture) {
  94522. serializationObject.environmentTexture = scene.environmentTexture.name;
  94523. }
  94524. // Skeletons
  94525. serializationObject.skeletons = [];
  94526. for (index = 0; index < scene.skeletons.length; index++) {
  94527. var skeleton = scene.skeletons[index];
  94528. if (!skeleton.doNotSerialize) {
  94529. serializationObject.skeletons.push(skeleton.serialize());
  94530. }
  94531. }
  94532. // Transform nodes
  94533. serializationObject.transformNodes = [];
  94534. for (index = 0; index < scene.transformNodes.length; index++) {
  94535. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  94536. }
  94537. // Geometries
  94538. serializationObject.geometries = {};
  94539. serializationObject.geometries.boxes = [];
  94540. serializationObject.geometries.spheres = [];
  94541. serializationObject.geometries.cylinders = [];
  94542. serializationObject.geometries.toruses = [];
  94543. serializationObject.geometries.grounds = [];
  94544. serializationObject.geometries.planes = [];
  94545. serializationObject.geometries.torusKnots = [];
  94546. serializationObject.geometries.vertexData = [];
  94547. serializedGeometries = [];
  94548. var geometries = scene.getGeometries();
  94549. for (index = 0; index < geometries.length; index++) {
  94550. var geometry = geometries[index];
  94551. if (geometry.isReady()) {
  94552. serializeGeometry(geometry, serializationObject.geometries);
  94553. }
  94554. }
  94555. // Meshes
  94556. serializationObject.meshes = [];
  94557. for (index = 0; index < scene.meshes.length; index++) {
  94558. var abstractMesh = scene.meshes[index];
  94559. if (abstractMesh instanceof BABYLON.Mesh) {
  94560. var mesh = abstractMesh;
  94561. if (!mesh.doNotSerialize) {
  94562. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94563. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94564. }
  94565. }
  94566. }
  94567. }
  94568. // Particles Systems
  94569. serializationObject.particleSystems = [];
  94570. for (index = 0; index < scene.particleSystems.length; index++) {
  94571. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  94572. }
  94573. // Lens flares
  94574. serializationObject.lensFlareSystems = [];
  94575. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  94576. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  94577. }
  94578. // Shadows
  94579. serializationObject.shadowGenerators = [];
  94580. for (index = 0; index < scene.lights.length; index++) {
  94581. light = scene.lights[index];
  94582. var shadowGenerator = light.getShadowGenerator();
  94583. if (shadowGenerator) {
  94584. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  94585. }
  94586. }
  94587. // Action Manager
  94588. if (scene.actionManager) {
  94589. serializationObject.actions = scene.actionManager.serialize("scene");
  94590. }
  94591. // Audio
  94592. serializationObject.sounds = [];
  94593. for (index = 0; index < scene.soundTracks.length; index++) {
  94594. var soundtrack = scene.soundTracks[index];
  94595. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  94596. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  94597. }
  94598. }
  94599. // Effect layers
  94600. serializationObject.effectLayers = [];
  94601. for (index = 0; index < scene.effectLayers.length; index++) {
  94602. var layer = scene.effectLayers[index];
  94603. if (layer.serialize) {
  94604. serializationObject.effectLayers.push(layer.serialize());
  94605. }
  94606. }
  94607. return serializationObject;
  94608. };
  94609. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94610. if (withParents === void 0) { withParents = false; }
  94611. if (withChildren === void 0) { withChildren = false; }
  94612. var serializationObject = {};
  94613. SceneSerializer.ClearCache();
  94614. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94615. if (withParents || withChildren) {
  94616. //deliberate for loop! not for each, appended should be processed as well.
  94617. for (var i = 0; i < toSerialize.length; ++i) {
  94618. if (withChildren) {
  94619. toSerialize[i].getDescendants().forEach(function (node) {
  94620. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94621. toSerialize.push(node);
  94622. }
  94623. });
  94624. }
  94625. //make sure the array doesn't contain the object already
  94626. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94627. toSerialize.push(toSerialize[i].parent);
  94628. }
  94629. }
  94630. }
  94631. toSerialize.forEach(function (mesh) {
  94632. finalizeSingleMesh(mesh, serializationObject);
  94633. });
  94634. return serializationObject;
  94635. };
  94636. return SceneSerializer;
  94637. }());
  94638. BABYLON.SceneSerializer = SceneSerializer;
  94639. })(BABYLON || (BABYLON = {}));
  94640. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94641. var BABYLON;
  94642. (function (BABYLON) {
  94643. var ReflectionProbe = /** @class */ (function () {
  94644. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94645. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94646. var _this = this;
  94647. this.name = name;
  94648. this._viewMatrix = BABYLON.Matrix.Identity();
  94649. this._target = BABYLON.Vector3.Zero();
  94650. this._add = BABYLON.Vector3.Zero();
  94651. this._invertYAxis = false;
  94652. this.position = BABYLON.Vector3.Zero();
  94653. this._scene = scene;
  94654. this._scene.reflectionProbes.push(this);
  94655. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94656. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94657. switch (faceIndex) {
  94658. case 0:
  94659. _this._add.copyFromFloats(1, 0, 0);
  94660. break;
  94661. case 1:
  94662. _this._add.copyFromFloats(-1, 0, 0);
  94663. break;
  94664. case 2:
  94665. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94666. break;
  94667. case 3:
  94668. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94669. break;
  94670. case 4:
  94671. _this._add.copyFromFloats(0, 0, 1);
  94672. break;
  94673. case 5:
  94674. _this._add.copyFromFloats(0, 0, -1);
  94675. break;
  94676. }
  94677. if (_this._attachedMesh) {
  94678. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94679. }
  94680. _this.position.addToRef(_this._add, _this._target);
  94681. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94682. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94683. scene._forcedViewPosition = _this.position;
  94684. });
  94685. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94686. scene._forcedViewPosition = null;
  94687. scene.updateTransformMatrix(true);
  94688. });
  94689. if (scene.activeCamera) {
  94690. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94691. }
  94692. }
  94693. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94694. get: function () {
  94695. return this._renderTargetTexture.samples;
  94696. },
  94697. set: function (value) {
  94698. this._renderTargetTexture.samples = value;
  94699. },
  94700. enumerable: true,
  94701. configurable: true
  94702. });
  94703. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94704. get: function () {
  94705. return this._renderTargetTexture.refreshRate;
  94706. },
  94707. set: function (value) {
  94708. this._renderTargetTexture.refreshRate = value;
  94709. },
  94710. enumerable: true,
  94711. configurable: true
  94712. });
  94713. ReflectionProbe.prototype.getScene = function () {
  94714. return this._scene;
  94715. };
  94716. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94717. get: function () {
  94718. return this._renderTargetTexture;
  94719. },
  94720. enumerable: true,
  94721. configurable: true
  94722. });
  94723. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94724. get: function () {
  94725. return this._renderTargetTexture.renderList;
  94726. },
  94727. enumerable: true,
  94728. configurable: true
  94729. });
  94730. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94731. this._attachedMesh = mesh;
  94732. };
  94733. /**
  94734. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94735. *
  94736. * @param renderingGroupId The rendering group id corresponding to its index
  94737. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94738. */
  94739. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94740. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94741. };
  94742. ReflectionProbe.prototype.dispose = function () {
  94743. var index = this._scene.reflectionProbes.indexOf(this);
  94744. if (index !== -1) {
  94745. // Remove from the scene if found
  94746. this._scene.reflectionProbes.splice(index, 1);
  94747. }
  94748. if (this._renderTargetTexture) {
  94749. this._renderTargetTexture.dispose();
  94750. this._renderTargetTexture = null;
  94751. }
  94752. };
  94753. return ReflectionProbe;
  94754. }());
  94755. BABYLON.ReflectionProbe = ReflectionProbe;
  94756. })(BABYLON || (BABYLON = {}));
  94757. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94758. var BABYLON;
  94759. (function (BABYLON) {
  94760. var Layer = /** @class */ (function () {
  94761. function Layer(name, imgUrl, scene, isBackground, color) {
  94762. this.name = name;
  94763. this.scale = new BABYLON.Vector2(1, 1);
  94764. this.offset = new BABYLON.Vector2(0, 0);
  94765. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94766. this.layerMask = 0x0FFFFFFF;
  94767. this._vertexBuffers = {};
  94768. // Events
  94769. /**
  94770. * An event triggered when the layer is disposed.
  94771. */
  94772. this.onDisposeObservable = new BABYLON.Observable();
  94773. /**
  94774. * An event triggered before rendering the scene
  94775. */
  94776. this.onBeforeRenderObservable = new BABYLON.Observable();
  94777. /**
  94778. * An event triggered after rendering the scene
  94779. */
  94780. this.onAfterRenderObservable = new BABYLON.Observable();
  94781. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94782. this.isBackground = isBackground === undefined ? true : isBackground;
  94783. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94784. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94785. this._scene.layers.push(this);
  94786. var engine = this._scene.getEngine();
  94787. // VBO
  94788. var vertices = [];
  94789. vertices.push(1, 1);
  94790. vertices.push(-1, 1);
  94791. vertices.push(-1, -1);
  94792. vertices.push(1, -1);
  94793. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94794. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94795. this._createIndexBuffer();
  94796. // Effects
  94797. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94798. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94799. }
  94800. Object.defineProperty(Layer.prototype, "onDispose", {
  94801. set: function (callback) {
  94802. if (this._onDisposeObserver) {
  94803. this.onDisposeObservable.remove(this._onDisposeObserver);
  94804. }
  94805. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94806. },
  94807. enumerable: true,
  94808. configurable: true
  94809. });
  94810. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94811. set: function (callback) {
  94812. if (this._onBeforeRenderObserver) {
  94813. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94814. }
  94815. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94816. },
  94817. enumerable: true,
  94818. configurable: true
  94819. });
  94820. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94821. set: function (callback) {
  94822. if (this._onAfterRenderObserver) {
  94823. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94824. }
  94825. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94826. },
  94827. enumerable: true,
  94828. configurable: true
  94829. });
  94830. Layer.prototype._createIndexBuffer = function () {
  94831. var engine = this._scene.getEngine();
  94832. // Indices
  94833. var indices = [];
  94834. indices.push(0);
  94835. indices.push(1);
  94836. indices.push(2);
  94837. indices.push(0);
  94838. indices.push(2);
  94839. indices.push(3);
  94840. this._indexBuffer = engine.createIndexBuffer(indices);
  94841. };
  94842. Layer.prototype._rebuild = function () {
  94843. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94844. if (vb) {
  94845. vb._rebuild();
  94846. }
  94847. this._createIndexBuffer();
  94848. };
  94849. Layer.prototype.render = function () {
  94850. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94851. // Check
  94852. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94853. return;
  94854. var engine = this._scene.getEngine();
  94855. this.onBeforeRenderObservable.notifyObservers(this);
  94856. // Render
  94857. engine.enableEffect(currentEffect);
  94858. engine.setState(false);
  94859. // Texture
  94860. currentEffect.setTexture("textureSampler", this.texture);
  94861. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94862. // Color
  94863. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94864. // Scale / offset
  94865. currentEffect.setVector2("offset", this.offset);
  94866. currentEffect.setVector2("scale", this.scale);
  94867. // VBOs
  94868. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94869. // Draw order
  94870. if (!this.alphaTest) {
  94871. engine.setAlphaMode(this.alphaBlendingMode);
  94872. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94873. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94874. }
  94875. else {
  94876. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94877. }
  94878. this.onAfterRenderObservable.notifyObservers(this);
  94879. };
  94880. Layer.prototype.dispose = function () {
  94881. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94882. if (vertexBuffer) {
  94883. vertexBuffer.dispose();
  94884. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94885. }
  94886. if (this._indexBuffer) {
  94887. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94888. this._indexBuffer = null;
  94889. }
  94890. if (this.texture) {
  94891. this.texture.dispose();
  94892. this.texture = null;
  94893. }
  94894. // Remove from scene
  94895. var index = this._scene.layers.indexOf(this);
  94896. this._scene.layers.splice(index, 1);
  94897. // Callback
  94898. this.onDisposeObservable.notifyObservers(this);
  94899. this.onDisposeObservable.clear();
  94900. this.onAfterRenderObservable.clear();
  94901. this.onBeforeRenderObservable.clear();
  94902. };
  94903. return Layer;
  94904. }());
  94905. BABYLON.Layer = Layer;
  94906. })(BABYLON || (BABYLON = {}));
  94907. //# sourceMappingURL=babylon.layer.js.map
  94908. var BABYLON;
  94909. (function (BABYLON) {
  94910. var TextureTools = /** @class */ (function () {
  94911. function TextureTools() {
  94912. }
  94913. /**
  94914. * Uses the GPU to create a copy texture rescaled at a given size
  94915. * @param texture Texture to copy from
  94916. * @param width Desired width
  94917. * @param height Desired height
  94918. * @return Generated texture
  94919. */
  94920. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94921. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94922. var scene = texture.getScene();
  94923. var engine = scene.getEngine();
  94924. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94925. rtt.wrapU = texture.wrapU;
  94926. rtt.wrapV = texture.wrapV;
  94927. rtt.uOffset = texture.uOffset;
  94928. rtt.vOffset = texture.vOffset;
  94929. rtt.uScale = texture.uScale;
  94930. rtt.vScale = texture.vScale;
  94931. rtt.uAng = texture.uAng;
  94932. rtt.vAng = texture.vAng;
  94933. rtt.wAng = texture.wAng;
  94934. rtt.coordinatesIndex = texture.coordinatesIndex;
  94935. rtt.level = texture.level;
  94936. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94937. rtt._texture.isReady = false;
  94938. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94939. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94940. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94941. passPostProcess.getEffect().executeWhenCompiled(function () {
  94942. passPostProcess.onApply = function (effect) {
  94943. effect.setTexture("textureSampler", texture);
  94944. };
  94945. var internalTexture = rtt.getInternalTexture();
  94946. if (internalTexture) {
  94947. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94948. engine.unBindFramebuffer(internalTexture);
  94949. rtt.disposeFramebufferObjects();
  94950. passPostProcess.dispose();
  94951. internalTexture.isReady = true;
  94952. }
  94953. });
  94954. return rtt;
  94955. };
  94956. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94957. if (!scene._environmentBRDFTexture) {
  94958. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94959. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94960. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94961. scene._environmentBRDFTexture = texture;
  94962. }
  94963. return scene._environmentBRDFTexture;
  94964. };
  94965. 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=";
  94966. return TextureTools;
  94967. }());
  94968. BABYLON.TextureTools = TextureTools;
  94969. })(BABYLON || (BABYLON = {}));
  94970. //# sourceMappingURL=babylon.textureTools.js.map
  94971. var BABYLON;
  94972. (function (BABYLON) {
  94973. var FramingBehavior = /** @class */ (function () {
  94974. function FramingBehavior() {
  94975. this._mode = FramingBehavior.FitFrustumSidesMode;
  94976. this._radiusScale = 1.0;
  94977. this._positionScale = 0.5;
  94978. this._defaultElevation = 0.3;
  94979. this._elevationReturnTime = 1500;
  94980. this._elevationReturnWaitTime = 1000;
  94981. this._zoomStopsAnimation = false;
  94982. this._framingTime = 1500;
  94983. this._isPointerDown = false;
  94984. this._lastInteractionTime = -Infinity;
  94985. // Framing control
  94986. this._animatables = new Array();
  94987. this._betaIsAnimating = false;
  94988. }
  94989. Object.defineProperty(FramingBehavior.prototype, "name", {
  94990. get: function () {
  94991. return "Framing";
  94992. },
  94993. enumerable: true,
  94994. configurable: true
  94995. });
  94996. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94997. /**
  94998. * Gets current mode used by the behavior.
  94999. */
  95000. get: function () {
  95001. return this._mode;
  95002. },
  95003. /**
  95004. * Sets the current mode used by the behavior
  95005. */
  95006. set: function (mode) {
  95007. this._mode = mode;
  95008. },
  95009. enumerable: true,
  95010. configurable: true
  95011. });
  95012. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  95013. /**
  95014. * Gets the scale applied to the radius
  95015. */
  95016. get: function () {
  95017. return this._radiusScale;
  95018. },
  95019. /**
  95020. * Sets the scale applied to the radius (1 by default)
  95021. */
  95022. set: function (radius) {
  95023. this._radiusScale = radius;
  95024. },
  95025. enumerable: true,
  95026. configurable: true
  95027. });
  95028. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  95029. /**
  95030. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  95031. */
  95032. get: function () {
  95033. return this._positionScale;
  95034. },
  95035. /**
  95036. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  95037. */
  95038. set: function (scale) {
  95039. this._positionScale = scale;
  95040. },
  95041. enumerable: true,
  95042. configurable: true
  95043. });
  95044. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  95045. /**
  95046. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  95047. * behaviour is triggered, in radians.
  95048. */
  95049. get: function () {
  95050. return this._defaultElevation;
  95051. },
  95052. /**
  95053. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  95054. * behaviour is triggered, in radians.
  95055. */
  95056. set: function (elevation) {
  95057. this._defaultElevation = elevation;
  95058. },
  95059. enumerable: true,
  95060. configurable: true
  95061. });
  95062. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  95063. /**
  95064. * Gets the time (in milliseconds) taken to return to the default beta position.
  95065. * Negative value indicates camera should not return to default.
  95066. */
  95067. get: function () {
  95068. return this._elevationReturnTime;
  95069. },
  95070. /**
  95071. * Sets the time (in milliseconds) taken to return to the default beta position.
  95072. * Negative value indicates camera should not return to default.
  95073. */
  95074. set: function (speed) {
  95075. this._elevationReturnTime = speed;
  95076. },
  95077. enumerable: true,
  95078. configurable: true
  95079. });
  95080. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  95081. /**
  95082. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95083. */
  95084. get: function () {
  95085. return this._elevationReturnWaitTime;
  95086. },
  95087. /**
  95088. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95089. */
  95090. set: function (time) {
  95091. this._elevationReturnWaitTime = time;
  95092. },
  95093. enumerable: true,
  95094. configurable: true
  95095. });
  95096. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  95097. /**
  95098. * Gets the flag that indicates if user zooming should stop animation.
  95099. */
  95100. get: function () {
  95101. return this._zoomStopsAnimation;
  95102. },
  95103. /**
  95104. * Sets the flag that indicates if user zooming should stop animation.
  95105. */
  95106. set: function (flag) {
  95107. this._zoomStopsAnimation = flag;
  95108. },
  95109. enumerable: true,
  95110. configurable: true
  95111. });
  95112. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  95113. /**
  95114. * Gets the transition time when framing the mesh, in milliseconds
  95115. */
  95116. get: function () {
  95117. return this._framingTime;
  95118. },
  95119. /**
  95120. * Sets the transition time when framing the mesh, in milliseconds
  95121. */
  95122. set: function (time) {
  95123. this._framingTime = time;
  95124. },
  95125. enumerable: true,
  95126. configurable: true
  95127. });
  95128. FramingBehavior.prototype.init = function () {
  95129. // Do notihng
  95130. };
  95131. FramingBehavior.prototype.attach = function (camera) {
  95132. var _this = this;
  95133. this._attachedCamera = camera;
  95134. var scene = this._attachedCamera.getScene();
  95135. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  95136. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95137. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95138. _this._isPointerDown = true;
  95139. return;
  95140. }
  95141. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95142. _this._isPointerDown = false;
  95143. }
  95144. });
  95145. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95146. if (mesh) {
  95147. _this.zoomOnMesh(mesh);
  95148. }
  95149. });
  95150. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95151. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95152. _this._applyUserInteraction();
  95153. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  95154. // back to the default position after a given timeout
  95155. _this._maintainCameraAboveGround();
  95156. });
  95157. };
  95158. FramingBehavior.prototype.detach = function () {
  95159. if (!this._attachedCamera) {
  95160. return;
  95161. }
  95162. var scene = this._attachedCamera.getScene();
  95163. if (this._onPrePointerObservableObserver) {
  95164. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95165. }
  95166. if (this._onAfterCheckInputsObserver) {
  95167. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95168. }
  95169. if (this._onMeshTargetChangedObserver) {
  95170. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95171. }
  95172. this._attachedCamera = null;
  95173. };
  95174. /**
  95175. * Targets the given mesh and updates zoom level accordingly.
  95176. * @param mesh The mesh to target.
  95177. * @param radius Optional. If a cached radius position already exists, overrides default.
  95178. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95179. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95180. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95181. */
  95182. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95183. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95184. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95185. mesh.computeWorldMatrix(true);
  95186. var boundingBox = mesh.getBoundingInfo().boundingBox;
  95187. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  95188. };
  95189. /**
  95190. * Targets the given mesh with its children and updates zoom level accordingly.
  95191. * @param mesh The mesh to target.
  95192. * @param radius Optional. If a cached radius position already exists, overrides default.
  95193. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95194. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95195. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95196. */
  95197. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95198. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95199. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95200. mesh.computeWorldMatrix(true);
  95201. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  95202. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  95203. };
  95204. /**
  95205. * Targets the given meshes with their children and updates zoom level accordingly.
  95206. * @param meshes The mesh to target.
  95207. * @param radius Optional. If a cached radius position already exists, overrides default.
  95208. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95209. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95210. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95211. */
  95212. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  95213. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95214. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95215. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  95216. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  95217. for (var i = 0; i < meshes.length; i++) {
  95218. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  95219. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  95220. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  95221. }
  95222. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  95223. };
  95224. /**
  95225. * Targets the given mesh and updates zoom level accordingly.
  95226. * @param mesh The mesh to target.
  95227. * @param radius Optional. If a cached radius position already exists, overrides default.
  95228. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95229. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95230. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95231. */
  95232. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  95233. var _this = this;
  95234. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95235. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95236. var zoomTarget;
  95237. if (!this._attachedCamera) {
  95238. return;
  95239. }
  95240. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  95241. var bottom = minimumWorld.y;
  95242. var top = maximumWorld.y;
  95243. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  95244. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  95245. if (focusOnOriginXZ) {
  95246. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  95247. }
  95248. else {
  95249. var centerWorld = minimumWorld.add(radiusWorld);
  95250. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  95251. }
  95252. if (!this._vectorTransition) {
  95253. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  95254. }
  95255. this._betaIsAnimating = true;
  95256. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  95257. if (animatable) {
  95258. this._animatables.push(animatable);
  95259. }
  95260. // sets the radius and lower radius bounds
  95261. // Small delta ensures camera is not always at lower zoom limit.
  95262. var radius = 0;
  95263. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  95264. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95265. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  95266. radius = position;
  95267. }
  95268. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95269. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95270. if (this._attachedCamera.lowerRadiusLimit === null) {
  95271. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  95272. }
  95273. }
  95274. // Set sensibilities
  95275. var extend = maximumWorld.subtract(minimumWorld).length();
  95276. this._attachedCamera.panningSensibility = 5000 / extend;
  95277. this._attachedCamera.wheelPrecision = 100 / radius;
  95278. // transition to new radius
  95279. if (!this._radiusTransition) {
  95280. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95281. }
  95282. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  95283. _this.stopAllAnimations();
  95284. if (onAnimationEnd) {
  95285. onAnimationEnd();
  95286. }
  95287. if (_this._attachedCamera) {
  95288. _this._attachedCamera.storeState();
  95289. }
  95290. });
  95291. if (animatable) {
  95292. this._animatables.push(animatable);
  95293. }
  95294. };
  95295. /**
  95296. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  95297. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  95298. * frustum width.
  95299. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  95300. * to fully enclose the mesh in the viewing frustum.
  95301. */
  95302. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  95303. var size = maximumWorld.subtract(minimumWorld);
  95304. var boxVectorGlobalDiagonal = size.length();
  95305. var frustumSlope = this._getFrustumSlope();
  95306. // Formula for setting distance
  95307. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  95308. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  95309. // Horizon distance
  95310. var radius = radiusWithoutFraming * this._radiusScale;
  95311. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  95312. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  95313. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  95314. var camera = this._attachedCamera;
  95315. if (!camera) {
  95316. return 0;
  95317. }
  95318. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95319. // Don't exceed the requested limit
  95320. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  95321. }
  95322. // Don't exceed the upper radius limit
  95323. if (camera.upperRadiusLimit) {
  95324. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  95325. }
  95326. return distance;
  95327. };
  95328. /**
  95329. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  95330. * is automatically returned to its default position (expected to be above ground plane).
  95331. */
  95332. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  95333. var _this = this;
  95334. if (this._elevationReturnTime < 0) {
  95335. return;
  95336. }
  95337. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  95338. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  95339. var limitBeta = Math.PI * 0.5;
  95340. // Bring the camera back up if below the ground plane
  95341. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  95342. this._betaIsAnimating = true;
  95343. //Transition to new position
  95344. this.stopAllAnimations();
  95345. if (!this._betaTransition) {
  95346. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95347. }
  95348. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  95349. _this._clearAnimationLocks();
  95350. _this.stopAllAnimations();
  95351. });
  95352. if (animatabe) {
  95353. this._animatables.push(animatabe);
  95354. }
  95355. }
  95356. };
  95357. /**
  95358. * Returns the frustum slope based on the canvas ratio and camera FOV
  95359. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  95360. */
  95361. FramingBehavior.prototype._getFrustumSlope = function () {
  95362. // Calculate the viewport ratio
  95363. // Aspect Ratio is Height/Width.
  95364. var camera = this._attachedCamera;
  95365. if (!camera) {
  95366. return BABYLON.Vector2.Zero();
  95367. }
  95368. var engine = camera.getScene().getEngine();
  95369. var aspectRatio = engine.getAspectRatio(camera);
  95370. // Camera FOV is the vertical field of view (top-bottom) in radians.
  95371. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  95372. var frustumSlopeY = Math.tan(camera.fov / 2);
  95373. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  95374. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  95375. // along the forward vector.
  95376. var frustumSlopeX = frustumSlopeY * aspectRatio;
  95377. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  95378. };
  95379. /**
  95380. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  95381. */
  95382. FramingBehavior.prototype._clearAnimationLocks = function () {
  95383. this._betaIsAnimating = false;
  95384. };
  95385. /**
  95386. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95387. */
  95388. FramingBehavior.prototype._applyUserInteraction = function () {
  95389. if (this.isUserIsMoving) {
  95390. this._lastInteractionTime = BABYLON.Tools.Now;
  95391. this.stopAllAnimations();
  95392. this._clearAnimationLocks();
  95393. }
  95394. };
  95395. /**
  95396. * Stops and removes all animations that have been applied to the camera
  95397. */
  95398. FramingBehavior.prototype.stopAllAnimations = function () {
  95399. if (this._attachedCamera) {
  95400. this._attachedCamera.animations = [];
  95401. }
  95402. while (this._animatables.length) {
  95403. if (this._animatables[0]) {
  95404. this._animatables[0].onAnimationEnd = null;
  95405. this._animatables[0].stop();
  95406. }
  95407. this._animatables.shift();
  95408. }
  95409. };
  95410. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  95411. /**
  95412. * Gets a value indicating if the user is moving the camera
  95413. */
  95414. get: function () {
  95415. if (!this._attachedCamera) {
  95416. return false;
  95417. }
  95418. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95419. this._attachedCamera.inertialBetaOffset !== 0 ||
  95420. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95421. this._attachedCamera.inertialPanningX !== 0 ||
  95422. this._attachedCamera.inertialPanningY !== 0 ||
  95423. this._isPointerDown;
  95424. },
  95425. enumerable: true,
  95426. configurable: true
  95427. });
  95428. /**
  95429. * The easing function used by animations
  95430. */
  95431. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  95432. /**
  95433. * The easing mode used by animations
  95434. */
  95435. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  95436. // Statics
  95437. /**
  95438. * The camera can move all the way towards the mesh.
  95439. */
  95440. FramingBehavior.IgnoreBoundsSizeMode = 0;
  95441. /**
  95442. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  95443. */
  95444. FramingBehavior.FitFrustumSidesMode = 1;
  95445. return FramingBehavior;
  95446. }());
  95447. BABYLON.FramingBehavior = FramingBehavior;
  95448. })(BABYLON || (BABYLON = {}));
  95449. //# sourceMappingURL=babylon.framingBehavior.js.map
  95450. var BABYLON;
  95451. (function (BABYLON) {
  95452. /**
  95453. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  95454. */
  95455. var BouncingBehavior = /** @class */ (function () {
  95456. function BouncingBehavior() {
  95457. /**
  95458. * The duration of the animation, in milliseconds
  95459. */
  95460. this.transitionDuration = 450;
  95461. /**
  95462. * Length of the distance animated by the transition when lower radius is reached
  95463. */
  95464. this.lowerRadiusTransitionRange = 2;
  95465. /**
  95466. * Length of the distance animated by the transition when upper radius is reached
  95467. */
  95468. this.upperRadiusTransitionRange = -2;
  95469. this._autoTransitionRange = false;
  95470. // Animations
  95471. this._radiusIsAnimating = false;
  95472. this._radiusBounceTransition = null;
  95473. this._animatables = new Array();
  95474. }
  95475. Object.defineProperty(BouncingBehavior.prototype, "name", {
  95476. get: function () {
  95477. return "Bouncing";
  95478. },
  95479. enumerable: true,
  95480. configurable: true
  95481. });
  95482. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  95483. /**
  95484. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95485. */
  95486. get: function () {
  95487. return this._autoTransitionRange;
  95488. },
  95489. /**
  95490. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95491. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  95492. */
  95493. set: function (value) {
  95494. var _this = this;
  95495. if (this._autoTransitionRange === value) {
  95496. return;
  95497. }
  95498. this._autoTransitionRange = value;
  95499. var camera = this._attachedCamera;
  95500. if (!camera) {
  95501. return;
  95502. }
  95503. if (value) {
  95504. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95505. if (!mesh) {
  95506. return;
  95507. }
  95508. mesh.computeWorldMatrix(true);
  95509. var diagonal = mesh.getBoundingInfo().diagonalLength;
  95510. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  95511. _this.upperRadiusTransitionRange = diagonal * 0.05;
  95512. });
  95513. }
  95514. else if (this._onMeshTargetChangedObserver) {
  95515. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95516. }
  95517. },
  95518. enumerable: true,
  95519. configurable: true
  95520. });
  95521. BouncingBehavior.prototype.init = function () {
  95522. // Do notihng
  95523. };
  95524. BouncingBehavior.prototype.attach = function (camera) {
  95525. var _this = this;
  95526. this._attachedCamera = camera;
  95527. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95528. if (!_this._attachedCamera) {
  95529. return;
  95530. }
  95531. // Add the bounce animation to the lower radius limit
  95532. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  95533. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  95534. }
  95535. // Add the bounce animation to the upper radius limit
  95536. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  95537. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  95538. }
  95539. });
  95540. };
  95541. BouncingBehavior.prototype.detach = function () {
  95542. if (!this._attachedCamera) {
  95543. return;
  95544. }
  95545. if (this._onAfterCheckInputsObserver) {
  95546. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95547. }
  95548. if (this._onMeshTargetChangedObserver) {
  95549. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95550. }
  95551. this._attachedCamera = null;
  95552. };
  95553. /**
  95554. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  95555. * @param radiusLimit The limit to check against.
  95556. * @return Bool to indicate if at limit.
  95557. */
  95558. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  95559. if (!this._attachedCamera) {
  95560. return false;
  95561. }
  95562. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  95563. return true;
  95564. }
  95565. return false;
  95566. };
  95567. /**
  95568. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  95569. * @param radiusDelta The delta by which to animate to. Can be negative.
  95570. */
  95571. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  95572. var _this = this;
  95573. if (!this._attachedCamera) {
  95574. return;
  95575. }
  95576. if (!this._radiusBounceTransition) {
  95577. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  95578. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  95579. }
  95580. // Prevent zoom until bounce has completed
  95581. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  95582. this._attachedCamera.wheelPrecision = Infinity;
  95583. this._attachedCamera.inertialRadiusOffset = 0;
  95584. // Animate to the radius limit
  95585. this.stopAllAnimations();
  95586. this._radiusIsAnimating = true;
  95587. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  95588. if (animatable) {
  95589. this._animatables.push(animatable);
  95590. }
  95591. };
  95592. /**
  95593. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  95594. */
  95595. BouncingBehavior.prototype._clearAnimationLocks = function () {
  95596. this._radiusIsAnimating = false;
  95597. if (this._attachedCamera) {
  95598. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  95599. }
  95600. };
  95601. /**
  95602. * Stops and removes all animations that have been applied to the camera
  95603. */
  95604. BouncingBehavior.prototype.stopAllAnimations = function () {
  95605. if (this._attachedCamera) {
  95606. this._attachedCamera.animations = [];
  95607. }
  95608. while (this._animatables.length) {
  95609. this._animatables[0].onAnimationEnd = null;
  95610. this._animatables[0].stop();
  95611. this._animatables.shift();
  95612. }
  95613. };
  95614. /**
  95615. * The easing function used by animations
  95616. */
  95617. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95618. /**
  95619. * The easing mode used by animations
  95620. */
  95621. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95622. return BouncingBehavior;
  95623. }());
  95624. BABYLON.BouncingBehavior = BouncingBehavior;
  95625. })(BABYLON || (BABYLON = {}));
  95626. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95627. var BABYLON;
  95628. (function (BABYLON) {
  95629. var AutoRotationBehavior = /** @class */ (function () {
  95630. function AutoRotationBehavior() {
  95631. this._zoomStopsAnimation = false;
  95632. this._idleRotationSpeed = 0.05;
  95633. this._idleRotationWaitTime = 2000;
  95634. this._idleRotationSpinupTime = 2000;
  95635. this._isPointerDown = false;
  95636. this._lastFrameTime = null;
  95637. this._lastInteractionTime = -Infinity;
  95638. this._cameraRotationSpeed = 0;
  95639. this._lastFrameRadius = 0;
  95640. }
  95641. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95642. get: function () {
  95643. return "AutoRotation";
  95644. },
  95645. enumerable: true,
  95646. configurable: true
  95647. });
  95648. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95649. /**
  95650. * Gets the flag that indicates if user zooming should stop animation.
  95651. */
  95652. get: function () {
  95653. return this._zoomStopsAnimation;
  95654. },
  95655. /**
  95656. * Sets the flag that indicates if user zooming should stop animation.
  95657. */
  95658. set: function (flag) {
  95659. this._zoomStopsAnimation = flag;
  95660. },
  95661. enumerable: true,
  95662. configurable: true
  95663. });
  95664. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95665. /**
  95666. * Gets the default speed at which the camera rotates around the model.
  95667. */
  95668. get: function () {
  95669. return this._idleRotationSpeed;
  95670. },
  95671. /**
  95672. * Sets the default speed at which the camera rotates around the model.
  95673. */
  95674. set: function (speed) {
  95675. this._idleRotationSpeed = speed;
  95676. },
  95677. enumerable: true,
  95678. configurable: true
  95679. });
  95680. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95681. /**
  95682. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95683. */
  95684. get: function () {
  95685. return this._idleRotationWaitTime;
  95686. },
  95687. /**
  95688. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95689. */
  95690. set: function (time) {
  95691. this._idleRotationWaitTime = time;
  95692. },
  95693. enumerable: true,
  95694. configurable: true
  95695. });
  95696. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95697. /**
  95698. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95699. */
  95700. get: function () {
  95701. return this._idleRotationSpinupTime;
  95702. },
  95703. /**
  95704. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95705. */
  95706. set: function (time) {
  95707. this._idleRotationSpinupTime = time;
  95708. },
  95709. enumerable: true,
  95710. configurable: true
  95711. });
  95712. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95713. /**
  95714. * Gets a value indicating if the camera is currently rotating because of this behavior
  95715. */
  95716. get: function () {
  95717. return Math.abs(this._cameraRotationSpeed) > 0;
  95718. },
  95719. enumerable: true,
  95720. configurable: true
  95721. });
  95722. AutoRotationBehavior.prototype.init = function () {
  95723. // Do notihng
  95724. };
  95725. AutoRotationBehavior.prototype.attach = function (camera) {
  95726. var _this = this;
  95727. this._attachedCamera = camera;
  95728. var scene = this._attachedCamera.getScene();
  95729. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95730. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95731. _this._isPointerDown = true;
  95732. return;
  95733. }
  95734. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95735. _this._isPointerDown = false;
  95736. }
  95737. });
  95738. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95739. var now = BABYLON.Tools.Now;
  95740. var dt = 0;
  95741. if (_this._lastFrameTime != null) {
  95742. dt = now - _this._lastFrameTime;
  95743. }
  95744. _this._lastFrameTime = now;
  95745. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95746. _this._applyUserInteraction();
  95747. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95748. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95749. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95750. // Step camera rotation by rotation speed
  95751. if (_this._attachedCamera) {
  95752. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95753. }
  95754. });
  95755. };
  95756. AutoRotationBehavior.prototype.detach = function () {
  95757. if (!this._attachedCamera) {
  95758. return;
  95759. }
  95760. var scene = this._attachedCamera.getScene();
  95761. if (this._onPrePointerObservableObserver) {
  95762. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95763. }
  95764. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95765. this._attachedCamera = null;
  95766. };
  95767. /**
  95768. * Returns true if user is scrolling.
  95769. * @return true if user is scrolling.
  95770. */
  95771. AutoRotationBehavior.prototype._userIsZooming = function () {
  95772. if (!this._attachedCamera) {
  95773. return false;
  95774. }
  95775. return this._attachedCamera.inertialRadiusOffset !== 0;
  95776. };
  95777. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95778. if (!this._attachedCamera) {
  95779. return false;
  95780. }
  95781. var zoomHasHitLimit = false;
  95782. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95783. zoomHasHitLimit = true;
  95784. }
  95785. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95786. this._lastFrameRadius = this._attachedCamera.radius;
  95787. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95788. };
  95789. /**
  95790. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95791. */
  95792. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95793. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95794. this._lastInteractionTime = BABYLON.Tools.Now;
  95795. }
  95796. };
  95797. // Tools
  95798. AutoRotationBehavior.prototype._userIsMoving = function () {
  95799. if (!this._attachedCamera) {
  95800. return false;
  95801. }
  95802. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95803. this._attachedCamera.inertialBetaOffset !== 0 ||
  95804. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95805. this._attachedCamera.inertialPanningX !== 0 ||
  95806. this._attachedCamera.inertialPanningY !== 0 ||
  95807. this._isPointerDown;
  95808. };
  95809. return AutoRotationBehavior;
  95810. }());
  95811. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95812. })(BABYLON || (BABYLON = {}));
  95813. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95814. var BABYLON;
  95815. (function (BABYLON) {
  95816. /**
  95817. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  95818. */
  95819. var PointerDragBehavior = /** @class */ (function () {
  95820. /**
  95821. * Creates a pointer drag behavior that can be attached to a mesh
  95822. * @param options The drag axis or normal of the plane that will be dragged across. pointerObservableScene can be used to listen to drag events from another scene(eg. if the attached mesh is in an overlay scene).
  95823. */
  95824. function PointerDragBehavior(options) {
  95825. this.options = options;
  95826. this._draggingID = -1;
  95827. /**
  95828. * Fires each time the attached mesh is dragged with the pointer
  95829. */
  95830. this.onDragObservable = new BABYLON.Observable();
  95831. /**
  95832. * Fires each time a drag begins (eg. mouse down on mesh)
  95833. */
  95834. this.onDragStartObservable = new BABYLON.Observable();
  95835. /**
  95836. * Fires each time a drag ends (eg. mouse release after drag)
  95837. */
  95838. this.onDragEndObservable = new BABYLON.Observable();
  95839. /**
  95840. * If the attached mesh should be moved when dragged
  95841. */
  95842. this.moveAttached = true;
  95843. /**
  95844. * Mesh with the position where the drag plane should be placed
  95845. */
  95846. this._dragPlaneParent = null;
  95847. var optionCount = 0;
  95848. if (options.dragAxis) {
  95849. optionCount++;
  95850. }
  95851. if (options.dragPlaneNormal) {
  95852. optionCount++;
  95853. }
  95854. if (optionCount > 1) {
  95855. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95856. }
  95857. if (optionCount < 1) {
  95858. throw "At least one drag mode option must be specified";
  95859. }
  95860. }
  95861. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95862. /**
  95863. * The name of the behavior
  95864. */
  95865. get: function () {
  95866. return "PointerDrag";
  95867. },
  95868. enumerable: true,
  95869. configurable: true
  95870. });
  95871. /**
  95872. * Initializes the behavior
  95873. */
  95874. PointerDragBehavior.prototype.init = function () { };
  95875. /**
  95876. * Attaches the drag behavior the passed in mesh
  95877. * @param ownerNode The mesh that will be dragged around once attached
  95878. */
  95879. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95880. var _this = this;
  95881. this._scene = ownerNode.getScene();
  95882. if (!this.options.pointerObservableScene) {
  95883. this.options.pointerObservableScene = this._scene;
  95884. }
  95885. this._attachedNode = ownerNode;
  95886. // Initialize drag plane to not interfere with existing scene
  95887. if (!PointerDragBehavior._planeScene) {
  95888. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95889. this._scene.getEngine().scenes.pop();
  95890. }
  95891. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95892. // State of the drag
  95893. var dragging = false;
  95894. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  95895. var delta = new BABYLON.Vector3(0, 0, 0);
  95896. var pickPredicate = function (m) {
  95897. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95898. };
  95899. this._pointerObserver = this.options.pointerObservableScene.onPrePointerObservable.add(function (pointerInfoPre, eventState) {
  95900. // Check if attached mesh is picked
  95901. var pickInfo = pointerInfoPre.ray ? _this._scene.pickWithRay(pointerInfoPre.ray, pickPredicate) : _this._scene.pick(_this._scene.pointerX, _this._scene.pointerY, pickPredicate);
  95902. if (pickInfo) {
  95903. pickInfo.ray = pointerInfoPre.ray;
  95904. if (!pickInfo.ray) {
  95905. pickInfo.ray = _this.options.pointerObservableScene.createPickingRay(_this._scene.pointerX, _this._scene.pointerY, BABYLON.Matrix.Identity(), _this._scene.activeCamera);
  95906. }
  95907. if (pickInfo.hit) {
  95908. eventState.skipNextObservers = true;
  95909. }
  95910. }
  95911. if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95912. if (!dragging && pickInfo && pickInfo.hit && pickInfo.pickedMesh && pickInfo.ray) {
  95913. _this._updateDragPlanePosition(pickInfo.ray);
  95914. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  95915. if (pickedPoint) {
  95916. dragging = true;
  95917. _this._draggingID = pointerInfoPre.event.pointerId;
  95918. lastPosition.copyFrom(pickedPoint);
  95919. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  95920. }
  95921. }
  95922. }
  95923. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERUP) {
  95924. if (_this._draggingID == pointerInfoPre.event.pointerId) {
  95925. dragging = false;
  95926. _this._draggingID = -1;
  95927. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  95928. }
  95929. }
  95930. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95931. if (_this._draggingID == pointerInfoPre.event.pointerId && dragging && pickInfo && pickInfo.ray) {
  95932. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  95933. _this._updateDragPlanePosition(pickInfo.ray);
  95934. if (pickedPoint) {
  95935. // depending on the drag mode option drag accordingly
  95936. if (_this.options.dragAxis) {
  95937. //get the closest point on the dragaxis from the selected mesh to the picked point location
  95938. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  95939. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  95940. }
  95941. else {
  95942. pickedPoint.subtractToRef(lastPosition, delta);
  95943. }
  95944. if (_this.moveAttached) {
  95945. _this._attachedNode.position.addInPlace(delta);
  95946. }
  95947. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  95948. lastPosition.copyFrom(pickedPoint);
  95949. }
  95950. }
  95951. }
  95952. });
  95953. };
  95954. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95955. var _this = this;
  95956. if (!ray) {
  95957. return null;
  95958. }
  95959. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95960. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95961. return pickResult.pickedPoint;
  95962. }
  95963. else {
  95964. return null;
  95965. }
  95966. };
  95967. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95968. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  95969. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  95970. if (this.options.dragAxis) {
  95971. var camPos = ray.origin;
  95972. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95973. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  95974. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  95975. // Get perpendicular line from direction to camera and drag axis
  95976. var lineA = pointB.subtract(pointA);
  95977. var lineB = pointC.subtract(pointA);
  95978. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  95979. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95980. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  95981. this._dragPlane.position.copyFrom(pointA);
  95982. this._dragPlane.lookAt(pointA.add(norm));
  95983. }
  95984. else if (this.options.dragPlaneNormal) {
  95985. this._dragPlane.position.copyFrom(pointA);
  95986. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  95987. }
  95988. this._dragPlane.computeWorldMatrix(true);
  95989. };
  95990. /**
  95991. * Detaches the behavior from the mesh
  95992. */
  95993. PointerDragBehavior.prototype.detach = function () {
  95994. if (this._pointerObserver) {
  95995. this._scene.onPrePointerObservable.remove(this._pointerObserver);
  95996. }
  95997. };
  95998. return PointerDragBehavior;
  95999. }());
  96000. BABYLON.PointerDragBehavior = PointerDragBehavior;
  96001. })(BABYLON || (BABYLON = {}));
  96002. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  96003. var BABYLON;
  96004. (function (BABYLON) {
  96005. var NullEngineOptions = /** @class */ (function () {
  96006. function NullEngineOptions() {
  96007. this.renderWidth = 512;
  96008. this.renderHeight = 256;
  96009. this.textureSize = 512;
  96010. this.deterministicLockstep = false;
  96011. this.lockstepMaxSteps = 4;
  96012. }
  96013. return NullEngineOptions;
  96014. }());
  96015. BABYLON.NullEngineOptions = NullEngineOptions;
  96016. /**
  96017. * The null engine class provides support for headless version of babylon.js.
  96018. * This can be used in server side scenario or for testing purposes
  96019. */
  96020. var NullEngine = /** @class */ (function (_super) {
  96021. __extends(NullEngine, _super);
  96022. function NullEngine(options) {
  96023. if (options === void 0) { options = new NullEngineOptions(); }
  96024. var _this = _super.call(this, null) || this;
  96025. if (options.deterministicLockstep === undefined) {
  96026. options.deterministicLockstep = false;
  96027. }
  96028. if (options.lockstepMaxSteps === undefined) {
  96029. options.lockstepMaxSteps = 4;
  96030. }
  96031. _this._options = options;
  96032. // Init caps
  96033. // We consider we are on a webgl1 capable device
  96034. _this._caps = new BABYLON.EngineCapabilities();
  96035. _this._caps.maxTexturesImageUnits = 16;
  96036. _this._caps.maxVertexTextureImageUnits = 16;
  96037. _this._caps.maxTextureSize = 512;
  96038. _this._caps.maxCubemapTextureSize = 512;
  96039. _this._caps.maxRenderTextureSize = 512;
  96040. _this._caps.maxVertexAttribs = 16;
  96041. _this._caps.maxVaryingVectors = 16;
  96042. _this._caps.maxFragmentUniformVectors = 16;
  96043. _this._caps.maxVertexUniformVectors = 16;
  96044. // Extensions
  96045. _this._caps.standardDerivatives = false;
  96046. _this._caps.astc = null;
  96047. _this._caps.s3tc = null;
  96048. _this._caps.pvrtc = null;
  96049. _this._caps.etc1 = null;
  96050. _this._caps.etc2 = null;
  96051. _this._caps.textureAnisotropicFilterExtension = null;
  96052. _this._caps.maxAnisotropy = 0;
  96053. _this._caps.uintIndices = false;
  96054. _this._caps.fragmentDepthSupported = false;
  96055. _this._caps.highPrecisionShaderSupported = true;
  96056. _this._caps.colorBufferFloat = false;
  96057. _this._caps.textureFloat = false;
  96058. _this._caps.textureFloatLinearFiltering = false;
  96059. _this._caps.textureFloatRender = false;
  96060. _this._caps.textureHalfFloat = false;
  96061. _this._caps.textureHalfFloatLinearFiltering = false;
  96062. _this._caps.textureHalfFloatRender = false;
  96063. _this._caps.textureLOD = false;
  96064. _this._caps.drawBuffersExtension = false;
  96065. _this._caps.depthTextureExtension = false;
  96066. _this._caps.vertexArrayObject = false;
  96067. _this._caps.instancedArrays = false;
  96068. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  96069. // Wrappers
  96070. if (typeof URL === "undefined") {
  96071. URL = {
  96072. createObjectURL: function () { },
  96073. revokeObjectURL: function () { }
  96074. };
  96075. }
  96076. if (typeof Blob === "undefined") {
  96077. Blob = function () { };
  96078. }
  96079. return _this;
  96080. }
  96081. NullEngine.prototype.isDeterministicLockStep = function () {
  96082. return this._options.deterministicLockstep;
  96083. };
  96084. NullEngine.prototype.getLockstepMaxSteps = function () {
  96085. return this._options.lockstepMaxSteps;
  96086. };
  96087. NullEngine.prototype.getHardwareScalingLevel = function () {
  96088. return 1.0;
  96089. };
  96090. NullEngine.prototype.createVertexBuffer = function (vertices) {
  96091. return {
  96092. capacity: 0,
  96093. references: 1,
  96094. is32Bits: false
  96095. };
  96096. };
  96097. NullEngine.prototype.createIndexBuffer = function (indices) {
  96098. return {
  96099. capacity: 0,
  96100. references: 1,
  96101. is32Bits: false
  96102. };
  96103. };
  96104. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  96105. if (stencil === void 0) { stencil = false; }
  96106. };
  96107. NullEngine.prototype.getRenderWidth = function (useScreen) {
  96108. if (useScreen === void 0) { useScreen = false; }
  96109. if (!useScreen && this._currentRenderTarget) {
  96110. return this._currentRenderTarget.width;
  96111. }
  96112. return this._options.renderWidth;
  96113. };
  96114. NullEngine.prototype.getRenderHeight = function (useScreen) {
  96115. if (useScreen === void 0) { useScreen = false; }
  96116. if (!useScreen && this._currentRenderTarget) {
  96117. return this._currentRenderTarget.height;
  96118. }
  96119. return this._options.renderHeight;
  96120. };
  96121. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  96122. this._cachedViewport = viewport;
  96123. };
  96124. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  96125. return {
  96126. transformFeedback: null,
  96127. __SPECTOR_rebuildProgram: null
  96128. };
  96129. };
  96130. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  96131. return [];
  96132. };
  96133. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  96134. return [];
  96135. };
  96136. NullEngine.prototype.bindSamplers = function (effect) {
  96137. this._currentEffect = null;
  96138. };
  96139. NullEngine.prototype.enableEffect = function (effect) {
  96140. this._currentEffect = effect;
  96141. if (effect.onBind) {
  96142. effect.onBind(effect);
  96143. }
  96144. effect.onBindObservable.notifyObservers(effect);
  96145. };
  96146. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  96147. if (zOffset === void 0) { zOffset = 0; }
  96148. if (reverseSide === void 0) { reverseSide = false; }
  96149. };
  96150. NullEngine.prototype.setIntArray = function (uniform, array) {
  96151. };
  96152. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  96153. };
  96154. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  96155. };
  96156. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  96157. };
  96158. NullEngine.prototype.setFloatArray = function (uniform, array) {
  96159. };
  96160. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  96161. };
  96162. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  96163. };
  96164. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  96165. };
  96166. NullEngine.prototype.setArray = function (uniform, array) {
  96167. };
  96168. NullEngine.prototype.setArray2 = function (uniform, array) {
  96169. };
  96170. NullEngine.prototype.setArray3 = function (uniform, array) {
  96171. };
  96172. NullEngine.prototype.setArray4 = function (uniform, array) {
  96173. };
  96174. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  96175. };
  96176. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  96177. };
  96178. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  96179. };
  96180. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  96181. };
  96182. NullEngine.prototype.setFloat = function (uniform, value) {
  96183. };
  96184. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  96185. };
  96186. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  96187. };
  96188. NullEngine.prototype.setBool = function (uniform, bool) {
  96189. };
  96190. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  96191. };
  96192. NullEngine.prototype.setColor3 = function (uniform, color3) {
  96193. };
  96194. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  96195. };
  96196. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  96197. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  96198. if (this._alphaMode === mode) {
  96199. return;
  96200. }
  96201. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  96202. if (!noDepthWriteChange) {
  96203. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  96204. }
  96205. this._alphaMode = mode;
  96206. };
  96207. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  96208. };
  96209. NullEngine.prototype.wipeCaches = function (bruteForce) {
  96210. if (this.preventCacheWipeBetweenFrames) {
  96211. return;
  96212. }
  96213. this.resetTextureCache();
  96214. this._currentEffect = null;
  96215. if (bruteForce) {
  96216. this._currentProgram = null;
  96217. this._stencilState.reset();
  96218. this._depthCullingState.reset();
  96219. this._alphaState.reset();
  96220. }
  96221. this._cachedVertexBuffers = null;
  96222. this._cachedIndexBuffer = null;
  96223. this._cachedEffectForVertexBuffers = null;
  96224. };
  96225. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  96226. };
  96227. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  96228. };
  96229. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  96230. };
  96231. NullEngine.prototype._createTexture = function () {
  96232. return {};
  96233. };
  96234. NullEngine.prototype._releaseTexture = function (texture) {
  96235. };
  96236. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  96237. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96238. if (onLoad === void 0) { onLoad = null; }
  96239. if (onError === void 0) { onError = null; }
  96240. if (buffer === void 0) { buffer = null; }
  96241. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  96242. var url = String(urlArg);
  96243. texture.url = url;
  96244. texture.generateMipMaps = !noMipmap;
  96245. texture.samplingMode = samplingMode;
  96246. texture.invertY = invertY;
  96247. texture.baseWidth = this._options.textureSize;
  96248. texture.baseHeight = this._options.textureSize;
  96249. texture.width = this._options.textureSize;
  96250. texture.height = this._options.textureSize;
  96251. if (format) {
  96252. texture.format = format;
  96253. }
  96254. texture.isReady = true;
  96255. if (onLoad) {
  96256. onLoad();
  96257. }
  96258. this._internalTexturesCache.push(texture);
  96259. return texture;
  96260. };
  96261. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  96262. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  96263. if (options !== undefined && typeof options === "object") {
  96264. fullOptions.generateMipMaps = options.generateMipMaps;
  96265. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  96266. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  96267. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  96268. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  96269. }
  96270. else {
  96271. fullOptions.generateMipMaps = options;
  96272. fullOptions.generateDepthBuffer = true;
  96273. fullOptions.generateStencilBuffer = false;
  96274. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96275. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  96276. }
  96277. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  96278. var width = size.width || size;
  96279. var height = size.height || size;
  96280. texture._depthStencilBuffer = {};
  96281. texture._framebuffer = {};
  96282. texture.baseWidth = width;
  96283. texture.baseHeight = height;
  96284. texture.width = width;
  96285. texture.height = height;
  96286. texture.isReady = true;
  96287. texture.samples = 1;
  96288. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  96289. texture.samplingMode = fullOptions.samplingMode;
  96290. texture.type = fullOptions.type;
  96291. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  96292. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  96293. this._internalTexturesCache.push(texture);
  96294. return texture;
  96295. };
  96296. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  96297. texture.samplingMode = samplingMode;
  96298. };
  96299. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  96300. if (this._currentRenderTarget) {
  96301. this.unBindFramebuffer(this._currentRenderTarget);
  96302. }
  96303. this._currentRenderTarget = texture;
  96304. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  96305. if (this._cachedViewport && !forceFullscreenViewport) {
  96306. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  96307. }
  96308. };
  96309. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  96310. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  96311. this._currentRenderTarget = null;
  96312. if (onBeforeUnbind) {
  96313. if (texture._MSAAFramebuffer) {
  96314. this._currentFramebuffer = texture._framebuffer;
  96315. }
  96316. onBeforeUnbind();
  96317. }
  96318. this._currentFramebuffer = null;
  96319. };
  96320. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  96321. var vbo = {
  96322. capacity: 1,
  96323. references: 1,
  96324. is32Bits: false
  96325. };
  96326. return vbo;
  96327. };
  96328. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  96329. if (offset === void 0) { offset = 0; }
  96330. };
  96331. /**
  96332. * Updates a dynamic vertex buffer.
  96333. * @param vertexBuffer the vertex buffer to update
  96334. * @param data the data used to update the vertex buffer
  96335. * @param byteOffset the byte offset of the data (optional)
  96336. * @param byteLength the byte length of the data (optional)
  96337. */
  96338. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  96339. };
  96340. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  96341. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  96342. this._boundTexturesCache[this._activeChannel] = texture;
  96343. }
  96344. };
  96345. NullEngine.prototype._bindTexture = function (channel, texture) {
  96346. if (channel < 0) {
  96347. return;
  96348. }
  96349. this._bindTextureDirectly(0, texture);
  96350. };
  96351. NullEngine.prototype._releaseBuffer = function (buffer) {
  96352. buffer.references--;
  96353. if (buffer.references === 0) {
  96354. return true;
  96355. }
  96356. return false;
  96357. };
  96358. NullEngine.prototype.releaseEffects = function () {
  96359. };
  96360. return NullEngine;
  96361. }(BABYLON.Engine));
  96362. BABYLON.NullEngine = NullEngine;
  96363. })(BABYLON || (BABYLON = {}));
  96364. //# sourceMappingURL=babylon.nullEngine.js.map
  96365. var BABYLON;
  96366. (function (BABYLON) {
  96367. /**
  96368. * This class can be used to get instrumentation data from a Babylon engine
  96369. */
  96370. var EngineInstrumentation = /** @class */ (function () {
  96371. function EngineInstrumentation(engine) {
  96372. this.engine = engine;
  96373. this._captureGPUFrameTime = false;
  96374. this._gpuFrameTime = new BABYLON.PerfCounter();
  96375. this._captureShaderCompilationTime = false;
  96376. this._shaderCompilationTime = new BABYLON.PerfCounter();
  96377. // Observers
  96378. this._onBeginFrameObserver = null;
  96379. this._onEndFrameObserver = null;
  96380. this._onBeforeShaderCompilationObserver = null;
  96381. this._onAfterShaderCompilationObserver = null;
  96382. }
  96383. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  96384. // Properties
  96385. /**
  96386. * Gets the perf counter used for GPU frame time
  96387. */
  96388. get: function () {
  96389. return this._gpuFrameTime;
  96390. },
  96391. enumerable: true,
  96392. configurable: true
  96393. });
  96394. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  96395. /**
  96396. * Gets the GPU frame time capture status
  96397. */
  96398. get: function () {
  96399. return this._captureGPUFrameTime;
  96400. },
  96401. /**
  96402. * Enable or disable the GPU frame time capture
  96403. */
  96404. set: function (value) {
  96405. var _this = this;
  96406. if (value === this._captureGPUFrameTime) {
  96407. return;
  96408. }
  96409. this._captureGPUFrameTime = value;
  96410. if (value) {
  96411. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  96412. if (!_this._gpuFrameTimeToken) {
  96413. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  96414. }
  96415. });
  96416. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  96417. if (!_this._gpuFrameTimeToken) {
  96418. return;
  96419. }
  96420. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  96421. if (time > -1) {
  96422. _this._gpuFrameTimeToken = null;
  96423. _this._gpuFrameTime.fetchNewFrame();
  96424. _this._gpuFrameTime.addCount(time, true);
  96425. }
  96426. });
  96427. }
  96428. else {
  96429. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96430. this._onBeginFrameObserver = null;
  96431. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96432. this._onEndFrameObserver = null;
  96433. }
  96434. },
  96435. enumerable: true,
  96436. configurable: true
  96437. });
  96438. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  96439. /**
  96440. * Gets the perf counter used for shader compilation time
  96441. */
  96442. get: function () {
  96443. return this._shaderCompilationTime;
  96444. },
  96445. enumerable: true,
  96446. configurable: true
  96447. });
  96448. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  96449. /**
  96450. * Gets the shader compilation time capture status
  96451. */
  96452. get: function () {
  96453. return this._captureShaderCompilationTime;
  96454. },
  96455. /**
  96456. * Enable or disable the shader compilation time capture
  96457. */
  96458. set: function (value) {
  96459. var _this = this;
  96460. if (value === this._captureShaderCompilationTime) {
  96461. return;
  96462. }
  96463. this._captureShaderCompilationTime = value;
  96464. if (value) {
  96465. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  96466. _this._shaderCompilationTime.fetchNewFrame();
  96467. _this._shaderCompilationTime.beginMonitoring();
  96468. });
  96469. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  96470. _this._shaderCompilationTime.endMonitoring();
  96471. });
  96472. }
  96473. else {
  96474. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96475. this._onBeforeShaderCompilationObserver = null;
  96476. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96477. this._onAfterShaderCompilationObserver = null;
  96478. }
  96479. },
  96480. enumerable: true,
  96481. configurable: true
  96482. });
  96483. EngineInstrumentation.prototype.dispose = function () {
  96484. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96485. this._onBeginFrameObserver = null;
  96486. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96487. this._onEndFrameObserver = null;
  96488. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96489. this._onBeforeShaderCompilationObserver = null;
  96490. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96491. this._onAfterShaderCompilationObserver = null;
  96492. this.engine = null;
  96493. };
  96494. return EngineInstrumentation;
  96495. }());
  96496. BABYLON.EngineInstrumentation = EngineInstrumentation;
  96497. })(BABYLON || (BABYLON = {}));
  96498. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  96499. var BABYLON;
  96500. (function (BABYLON) {
  96501. /**
  96502. * This class can be used to get instrumentation data from a Babylon engine
  96503. */
  96504. var SceneInstrumentation = /** @class */ (function () {
  96505. function SceneInstrumentation(scene) {
  96506. var _this = this;
  96507. this.scene = scene;
  96508. this._captureActiveMeshesEvaluationTime = false;
  96509. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  96510. this._captureRenderTargetsRenderTime = false;
  96511. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  96512. this._captureFrameTime = false;
  96513. this._frameTime = new BABYLON.PerfCounter();
  96514. this._captureRenderTime = false;
  96515. this._renderTime = new BABYLON.PerfCounter();
  96516. this._captureInterFrameTime = false;
  96517. this._interFrameTime = new BABYLON.PerfCounter();
  96518. this._captureParticlesRenderTime = false;
  96519. this._particlesRenderTime = new BABYLON.PerfCounter();
  96520. this._captureSpritesRenderTime = false;
  96521. this._spritesRenderTime = new BABYLON.PerfCounter();
  96522. this._capturePhysicsTime = false;
  96523. this._physicsTime = new BABYLON.PerfCounter();
  96524. this._captureAnimationsTime = false;
  96525. this._animationsTime = new BABYLON.PerfCounter();
  96526. // Observers
  96527. this._onBeforeActiveMeshesEvaluationObserver = null;
  96528. this._onAfterActiveMeshesEvaluationObserver = null;
  96529. this._onBeforeRenderTargetsRenderObserver = null;
  96530. this._onAfterRenderTargetsRenderObserver = null;
  96531. this._onAfterRenderObserver = null;
  96532. this._onBeforeDrawPhaseObserver = null;
  96533. this._onAfterDrawPhaseObserver = null;
  96534. this._onBeforeAnimationsObserver = null;
  96535. this._onBeforeParticlesRenderingObserver = null;
  96536. this._onAfterParticlesRenderingObserver = null;
  96537. this._onBeforeSpritesRenderingObserver = null;
  96538. this._onAfterSpritesRenderingObserver = null;
  96539. this._onBeforePhysicsObserver = null;
  96540. this._onAfterPhysicsObserver = null;
  96541. this._onAfterAnimationsObserver = null;
  96542. // Before render
  96543. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  96544. if (_this._captureActiveMeshesEvaluationTime) {
  96545. _this._activeMeshesEvaluationTime.fetchNewFrame();
  96546. }
  96547. if (_this._captureRenderTargetsRenderTime) {
  96548. _this._renderTargetsRenderTime.fetchNewFrame();
  96549. }
  96550. if (_this._captureFrameTime) {
  96551. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  96552. _this._frameTime.beginMonitoring();
  96553. }
  96554. if (_this._captureInterFrameTime) {
  96555. _this._interFrameTime.endMonitoring();
  96556. }
  96557. if (_this._captureParticlesRenderTime) {
  96558. _this._particlesRenderTime.fetchNewFrame();
  96559. }
  96560. if (_this._captureSpritesRenderTime) {
  96561. _this._spritesRenderTime.fetchNewFrame();
  96562. }
  96563. if (_this._captureAnimationsTime) {
  96564. _this._animationsTime.beginMonitoring();
  96565. }
  96566. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  96567. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  96568. });
  96569. // After render
  96570. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  96571. if (_this._captureFrameTime) {
  96572. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  96573. _this._frameTime.endMonitoring();
  96574. }
  96575. if (_this._captureRenderTime) {
  96576. _this._renderTime.endMonitoring(false);
  96577. }
  96578. if (_this._captureInterFrameTime) {
  96579. _this._interFrameTime.beginMonitoring();
  96580. }
  96581. });
  96582. }
  96583. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  96584. // Properties
  96585. /**
  96586. * Gets the perf counter used for active meshes evaluation time
  96587. */
  96588. get: function () {
  96589. return this._activeMeshesEvaluationTime;
  96590. },
  96591. enumerable: true,
  96592. configurable: true
  96593. });
  96594. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  96595. /**
  96596. * Gets the active meshes evaluation time capture status
  96597. */
  96598. get: function () {
  96599. return this._captureActiveMeshesEvaluationTime;
  96600. },
  96601. /**
  96602. * Enable or disable the active meshes evaluation time capture
  96603. */
  96604. set: function (value) {
  96605. var _this = this;
  96606. if (value === this._captureActiveMeshesEvaluationTime) {
  96607. return;
  96608. }
  96609. this._captureActiveMeshesEvaluationTime = value;
  96610. if (value) {
  96611. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  96612. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  96613. _this._activeMeshesEvaluationTime.beginMonitoring();
  96614. });
  96615. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  96616. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  96617. _this._activeMeshesEvaluationTime.endMonitoring();
  96618. });
  96619. }
  96620. else {
  96621. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96622. this._onBeforeActiveMeshesEvaluationObserver = null;
  96623. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96624. this._onAfterActiveMeshesEvaluationObserver = null;
  96625. }
  96626. },
  96627. enumerable: true,
  96628. configurable: true
  96629. });
  96630. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  96631. /**
  96632. * Gets the perf counter used for render targets render time
  96633. */
  96634. get: function () {
  96635. return this._renderTargetsRenderTime;
  96636. },
  96637. enumerable: true,
  96638. configurable: true
  96639. });
  96640. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  96641. /**
  96642. * Gets the render targets render time capture status
  96643. */
  96644. get: function () {
  96645. return this._captureRenderTargetsRenderTime;
  96646. },
  96647. /**
  96648. * Enable or disable the render targets render time capture
  96649. */
  96650. set: function (value) {
  96651. var _this = this;
  96652. if (value === this._captureRenderTargetsRenderTime) {
  96653. return;
  96654. }
  96655. this._captureRenderTargetsRenderTime = value;
  96656. if (value) {
  96657. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  96658. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  96659. _this._renderTargetsRenderTime.beginMonitoring();
  96660. });
  96661. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  96662. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  96663. _this._renderTargetsRenderTime.endMonitoring(false);
  96664. });
  96665. }
  96666. else {
  96667. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96668. this._onBeforeRenderTargetsRenderObserver = null;
  96669. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96670. this._onAfterRenderTargetsRenderObserver = null;
  96671. }
  96672. },
  96673. enumerable: true,
  96674. configurable: true
  96675. });
  96676. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  96677. /**
  96678. * Gets the perf counter used for particles render time
  96679. */
  96680. get: function () {
  96681. return this._particlesRenderTime;
  96682. },
  96683. enumerable: true,
  96684. configurable: true
  96685. });
  96686. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  96687. /**
  96688. * Gets the particles render time capture status
  96689. */
  96690. get: function () {
  96691. return this._captureParticlesRenderTime;
  96692. },
  96693. /**
  96694. * Enable or disable the particles render time capture
  96695. */
  96696. set: function (value) {
  96697. var _this = this;
  96698. if (value === this._captureParticlesRenderTime) {
  96699. return;
  96700. }
  96701. this._captureParticlesRenderTime = value;
  96702. if (value) {
  96703. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  96704. BABYLON.Tools.StartPerformanceCounter("Particles");
  96705. _this._particlesRenderTime.beginMonitoring();
  96706. });
  96707. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  96708. BABYLON.Tools.EndPerformanceCounter("Particles");
  96709. _this._particlesRenderTime.endMonitoring(false);
  96710. });
  96711. }
  96712. else {
  96713. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96714. this._onBeforeParticlesRenderingObserver = null;
  96715. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96716. this._onAfterParticlesRenderingObserver = null;
  96717. }
  96718. },
  96719. enumerable: true,
  96720. configurable: true
  96721. });
  96722. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  96723. /**
  96724. * Gets the perf counter used for sprites render time
  96725. */
  96726. get: function () {
  96727. return this._spritesRenderTime;
  96728. },
  96729. enumerable: true,
  96730. configurable: true
  96731. });
  96732. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  96733. /**
  96734. * Gets the sprites render time capture status
  96735. */
  96736. get: function () {
  96737. return this._captureSpritesRenderTime;
  96738. },
  96739. /**
  96740. * Enable or disable the sprites render time capture
  96741. */
  96742. set: function (value) {
  96743. var _this = this;
  96744. if (value === this._captureSpritesRenderTime) {
  96745. return;
  96746. }
  96747. this._captureSpritesRenderTime = value;
  96748. if (value) {
  96749. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  96750. BABYLON.Tools.StartPerformanceCounter("Sprites");
  96751. _this._spritesRenderTime.beginMonitoring();
  96752. });
  96753. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  96754. BABYLON.Tools.EndPerformanceCounter("Sprites");
  96755. _this._spritesRenderTime.endMonitoring(false);
  96756. });
  96757. }
  96758. else {
  96759. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96760. this._onBeforeSpritesRenderingObserver = null;
  96761. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96762. this._onAfterSpritesRenderingObserver = null;
  96763. }
  96764. },
  96765. enumerable: true,
  96766. configurable: true
  96767. });
  96768. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  96769. /**
  96770. * Gets the perf counter used for physics time
  96771. */
  96772. get: function () {
  96773. return this._physicsTime;
  96774. },
  96775. enumerable: true,
  96776. configurable: true
  96777. });
  96778. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  96779. /**
  96780. * Gets the physics time capture status
  96781. */
  96782. get: function () {
  96783. return this._capturePhysicsTime;
  96784. },
  96785. /**
  96786. * Enable or disable the physics time capture
  96787. */
  96788. set: function (value) {
  96789. var _this = this;
  96790. if (value === this._capturePhysicsTime) {
  96791. return;
  96792. }
  96793. this._capturePhysicsTime = value;
  96794. if (value) {
  96795. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  96796. BABYLON.Tools.StartPerformanceCounter("Physics");
  96797. _this._physicsTime.beginMonitoring();
  96798. });
  96799. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  96800. BABYLON.Tools.EndPerformanceCounter("Physics");
  96801. _this._physicsTime.endMonitoring();
  96802. });
  96803. }
  96804. else {
  96805. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96806. this._onBeforePhysicsObserver = null;
  96807. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96808. this._onAfterPhysicsObserver = null;
  96809. }
  96810. },
  96811. enumerable: true,
  96812. configurable: true
  96813. });
  96814. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  96815. /**
  96816. * Gets the perf counter used for animations time
  96817. */
  96818. get: function () {
  96819. return this._animationsTime;
  96820. },
  96821. enumerable: true,
  96822. configurable: true
  96823. });
  96824. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  96825. /**
  96826. * Gets the animations time capture status
  96827. */
  96828. get: function () {
  96829. return this._captureAnimationsTime;
  96830. },
  96831. /**
  96832. * Enable or disable the animations time capture
  96833. */
  96834. set: function (value) {
  96835. var _this = this;
  96836. if (value === this._captureAnimationsTime) {
  96837. return;
  96838. }
  96839. this._captureAnimationsTime = value;
  96840. if (value) {
  96841. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96842. _this._animationsTime.endMonitoring();
  96843. });
  96844. }
  96845. else {
  96846. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96847. this._onAfterAnimationsObserver = null;
  96848. }
  96849. },
  96850. enumerable: true,
  96851. configurable: true
  96852. });
  96853. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96854. /**
  96855. * Gets the perf counter used for frame time capture
  96856. */
  96857. get: function () {
  96858. return this._frameTime;
  96859. },
  96860. enumerable: true,
  96861. configurable: true
  96862. });
  96863. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96864. /**
  96865. * Gets the frame time capture status
  96866. */
  96867. get: function () {
  96868. return this._captureFrameTime;
  96869. },
  96870. /**
  96871. * Enable or disable the frame time capture
  96872. */
  96873. set: function (value) {
  96874. this._captureFrameTime = value;
  96875. },
  96876. enumerable: true,
  96877. configurable: true
  96878. });
  96879. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96880. /**
  96881. * Gets the perf counter used for inter-frames time capture
  96882. */
  96883. get: function () {
  96884. return this._interFrameTime;
  96885. },
  96886. enumerable: true,
  96887. configurable: true
  96888. });
  96889. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96890. /**
  96891. * Gets the inter-frames time capture status
  96892. */
  96893. get: function () {
  96894. return this._captureInterFrameTime;
  96895. },
  96896. /**
  96897. * Enable or disable the inter-frames time capture
  96898. */
  96899. set: function (value) {
  96900. this._captureInterFrameTime = value;
  96901. },
  96902. enumerable: true,
  96903. configurable: true
  96904. });
  96905. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96906. /**
  96907. * Gets the perf counter used for render time capture
  96908. */
  96909. get: function () {
  96910. return this._renderTime;
  96911. },
  96912. enumerable: true,
  96913. configurable: true
  96914. });
  96915. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96916. /**
  96917. * Gets the render time capture status
  96918. */
  96919. get: function () {
  96920. return this._captureRenderTime;
  96921. },
  96922. /**
  96923. * Enable or disable the render time capture
  96924. */
  96925. set: function (value) {
  96926. var _this = this;
  96927. if (value === this._captureRenderTime) {
  96928. return;
  96929. }
  96930. this._captureRenderTime = value;
  96931. if (value) {
  96932. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96933. _this._renderTime.beginMonitoring();
  96934. BABYLON.Tools.StartPerformanceCounter("Main render");
  96935. });
  96936. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96937. _this._renderTime.endMonitoring(false);
  96938. BABYLON.Tools.EndPerformanceCounter("Main render");
  96939. });
  96940. }
  96941. else {
  96942. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96943. this._onBeforeDrawPhaseObserver = null;
  96944. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96945. this._onAfterDrawPhaseObserver = null;
  96946. }
  96947. },
  96948. enumerable: true,
  96949. configurable: true
  96950. });
  96951. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96952. /**
  96953. * Gets the perf counter used for draw calls
  96954. */
  96955. get: function () {
  96956. return this.scene.getEngine()._drawCalls;
  96957. },
  96958. enumerable: true,
  96959. configurable: true
  96960. });
  96961. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96962. /**
  96963. * Gets the perf counter used for texture collisions
  96964. */
  96965. get: function () {
  96966. return this.scene.getEngine()._textureCollisions;
  96967. },
  96968. enumerable: true,
  96969. configurable: true
  96970. });
  96971. SceneInstrumentation.prototype.dispose = function () {
  96972. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96973. this._onAfterRenderObserver = null;
  96974. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96975. this._onBeforeActiveMeshesEvaluationObserver = null;
  96976. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96977. this._onAfterActiveMeshesEvaluationObserver = null;
  96978. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96979. this._onBeforeRenderTargetsRenderObserver = null;
  96980. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96981. this._onAfterRenderTargetsRenderObserver = null;
  96982. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96983. this._onBeforeAnimationsObserver = null;
  96984. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96985. this._onBeforeParticlesRenderingObserver = null;
  96986. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96987. this._onAfterParticlesRenderingObserver = null;
  96988. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96989. this._onBeforeSpritesRenderingObserver = null;
  96990. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96991. this._onAfterSpritesRenderingObserver = null;
  96992. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96993. this._onBeforeDrawPhaseObserver = null;
  96994. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96995. this._onAfterDrawPhaseObserver = null;
  96996. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96997. this._onBeforePhysicsObserver = null;
  96998. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96999. this._onAfterPhysicsObserver = null;
  97000. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  97001. this._onAfterAnimationsObserver = null;
  97002. this.scene = null;
  97003. };
  97004. return SceneInstrumentation;
  97005. }());
  97006. BABYLON.SceneInstrumentation = SceneInstrumentation;
  97007. })(BABYLON || (BABYLON = {}));
  97008. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  97009. var BABYLON;
  97010. (function (BABYLON) {
  97011. /**
  97012. * @hidden
  97013. **/
  97014. var _TimeToken = /** @class */ (function () {
  97015. function _TimeToken() {
  97016. this._timeElapsedQueryEnded = false;
  97017. }
  97018. return _TimeToken;
  97019. }());
  97020. BABYLON._TimeToken = _TimeToken;
  97021. })(BABYLON || (BABYLON = {}));
  97022. //# sourceMappingURL=babylon.timeToken.js.map
  97023. var BABYLON;
  97024. (function (BABYLON) {
  97025. /**
  97026. * Background material defines definition.
  97027. * @hidden Mainly internal Use
  97028. */
  97029. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  97030. __extends(BackgroundMaterialDefines, _super);
  97031. /**
  97032. * Constructor of the defines.
  97033. */
  97034. function BackgroundMaterialDefines() {
  97035. var _this = _super.call(this) || this;
  97036. /**
  97037. * True if the diffuse texture is in use.
  97038. */
  97039. _this.DIFFUSE = false;
  97040. /**
  97041. * The direct UV channel to use.
  97042. */
  97043. _this.DIFFUSEDIRECTUV = 0;
  97044. /**
  97045. * True if the diffuse texture is in gamma space.
  97046. */
  97047. _this.GAMMADIFFUSE = false;
  97048. /**
  97049. * True if the diffuse texture has opacity in the alpha channel.
  97050. */
  97051. _this.DIFFUSEHASALPHA = false;
  97052. /**
  97053. * True if you want the material to fade to transparent at grazing angle.
  97054. */
  97055. _this.OPACITYFRESNEL = false;
  97056. /**
  97057. * True if an extra blur needs to be added in the reflection.
  97058. */
  97059. _this.REFLECTIONBLUR = false;
  97060. /**
  97061. * True if you want the material to fade to reflection at grazing angle.
  97062. */
  97063. _this.REFLECTIONFRESNEL = false;
  97064. /**
  97065. * True if you want the material to falloff as far as you move away from the scene center.
  97066. */
  97067. _this.REFLECTIONFALLOFF = false;
  97068. /**
  97069. * False if the current Webgl implementation does not support the texture lod extension.
  97070. */
  97071. _this.TEXTURELODSUPPORT = false;
  97072. /**
  97073. * True to ensure the data are premultiplied.
  97074. */
  97075. _this.PREMULTIPLYALPHA = false;
  97076. /**
  97077. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  97078. */
  97079. _this.USERGBCOLOR = false;
  97080. /**
  97081. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  97082. * stays aligned with the desired configuration.
  97083. */
  97084. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  97085. /**
  97086. * True to add noise in order to reduce the banding effect.
  97087. */
  97088. _this.NOISE = false;
  97089. /**
  97090. * is the reflection texture in BGR color scheme?
  97091. * Mainly used to solve a bug in ios10 video tag
  97092. */
  97093. _this.REFLECTIONBGR = false;
  97094. _this.IMAGEPROCESSING = false;
  97095. _this.VIGNETTE = false;
  97096. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  97097. _this.VIGNETTEBLENDMODEOPAQUE = false;
  97098. _this.TONEMAPPING = false;
  97099. _this.CONTRAST = false;
  97100. _this.COLORCURVES = false;
  97101. _this.COLORGRADING = false;
  97102. _this.COLORGRADING3D = false;
  97103. _this.SAMPLER3DGREENDEPTH = false;
  97104. _this.SAMPLER3DBGRMAP = false;
  97105. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  97106. _this.EXPOSURE = false;
  97107. // Reflection.
  97108. _this.REFLECTION = false;
  97109. _this.REFLECTIONMAP_3D = false;
  97110. _this.REFLECTIONMAP_SPHERICAL = false;
  97111. _this.REFLECTIONMAP_PLANAR = false;
  97112. _this.REFLECTIONMAP_CUBIC = false;
  97113. _this.REFLECTIONMAP_PROJECTION = false;
  97114. _this.REFLECTIONMAP_SKYBOX = false;
  97115. _this.REFLECTIONMAP_EXPLICIT = false;
  97116. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97117. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97118. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97119. _this.INVERTCUBICMAP = false;
  97120. _this.REFLECTIONMAP_OPPOSITEZ = false;
  97121. _this.LODINREFLECTIONALPHA = false;
  97122. _this.GAMMAREFLECTION = false;
  97123. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  97124. // Default BJS.
  97125. _this.MAINUV1 = false;
  97126. _this.MAINUV2 = false;
  97127. _this.UV1 = false;
  97128. _this.UV2 = false;
  97129. _this.CLIPPLANE = false;
  97130. _this.POINTSIZE = false;
  97131. _this.FOG = false;
  97132. _this.NORMAL = false;
  97133. _this.NUM_BONE_INFLUENCERS = 0;
  97134. _this.BonesPerMesh = 0;
  97135. _this.INSTANCES = false;
  97136. _this.SHADOWFLOAT = false;
  97137. _this.rebuild();
  97138. return _this;
  97139. }
  97140. return BackgroundMaterialDefines;
  97141. }(BABYLON.MaterialDefines));
  97142. /**
  97143. * Background material used to create an efficient environement around your scene.
  97144. */
  97145. var BackgroundMaterial = /** @class */ (function (_super) {
  97146. __extends(BackgroundMaterial, _super);
  97147. /**
  97148. * Instantiates a Background Material in the given scene
  97149. * @param name The friendly name of the material
  97150. * @param scene The scene to add the material to
  97151. */
  97152. function BackgroundMaterial(name, scene) {
  97153. var _this = _super.call(this, name, scene) || this;
  97154. /**
  97155. * Key light Color (multiply against the environement texture)
  97156. */
  97157. _this.primaryColor = BABYLON.Color3.White();
  97158. _this._primaryColorShadowLevel = 0;
  97159. _this._primaryColorHighlightLevel = 0;
  97160. /**
  97161. * Reflection Texture used in the material.
  97162. * Should be author in a specific way for the best result (refer to the documentation).
  97163. */
  97164. _this.reflectionTexture = null;
  97165. /**
  97166. * Reflection Texture level of blur.
  97167. *
  97168. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  97169. * texture twice.
  97170. */
  97171. _this.reflectionBlur = 0;
  97172. /**
  97173. * Diffuse Texture used in the material.
  97174. * Should be author in a specific way for the best result (refer to the documentation).
  97175. */
  97176. _this.diffuseTexture = null;
  97177. _this._shadowLights = null;
  97178. /**
  97179. * Specify the list of lights casting shadow on the material.
  97180. * All scene shadow lights will be included if null.
  97181. */
  97182. _this.shadowLights = null;
  97183. /**
  97184. * Helps adjusting the shadow to a softer level if required.
  97185. * 0 means black shadows and 1 means no shadows.
  97186. */
  97187. _this.shadowLevel = 0;
  97188. /**
  97189. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  97190. * It is usually zero but might be interesting to modify according to your setup.
  97191. */
  97192. _this.sceneCenter = BABYLON.Vector3.Zero();
  97193. /**
  97194. * This helps specifying that the material is falling off to the sky box at grazing angle.
  97195. * This helps ensuring a nice transition when the camera goes under the ground.
  97196. */
  97197. _this.opacityFresnel = true;
  97198. /**
  97199. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  97200. * This helps adding a mirror texture on the ground.
  97201. */
  97202. _this.reflectionFresnel = false;
  97203. /**
  97204. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  97205. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  97206. */
  97207. _this.reflectionFalloffDistance = 0.0;
  97208. /**
  97209. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  97210. */
  97211. _this.reflectionAmount = 1.0;
  97212. /**
  97213. * This specifies the weight of the reflection at grazing angle.
  97214. */
  97215. _this.reflectionReflectance0 = 0.05;
  97216. /**
  97217. * This specifies the weight of the reflection at a perpendicular point of view.
  97218. */
  97219. _this.reflectionReflectance90 = 0.5;
  97220. /**
  97221. * Helps to directly use the maps channels instead of their level.
  97222. */
  97223. _this.useRGBColor = true;
  97224. /**
  97225. * This helps reducing the banding effect that could occur on the background.
  97226. */
  97227. _this.enableNoise = false;
  97228. _this._fovMultiplier = 1.0;
  97229. /**
  97230. * Enable the FOV adjustment feature controlled by fovMultiplier.
  97231. */
  97232. _this.useEquirectangularFOV = false;
  97233. _this._maxSimultaneousLights = 4;
  97234. /**
  97235. * Number of Simultaneous lights allowed on the material.
  97236. */
  97237. _this.maxSimultaneousLights = 4;
  97238. /**
  97239. * Keep track of the image processing observer to allow dispose and replace.
  97240. */
  97241. _this._imageProcessingObserver = null;
  97242. /**
  97243. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  97244. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  97245. */
  97246. _this.switchToBGR = false;
  97247. // Temp values kept as cache in the material.
  97248. _this._renderTargets = new BABYLON.SmartArray(16);
  97249. _this._reflectionControls = BABYLON.Vector4.Zero();
  97250. _this._white = BABYLON.Color3.White();
  97251. _this._primaryShadowColor = BABYLON.Color3.Black();
  97252. _this._primaryHighlightColor = BABYLON.Color3.Black();
  97253. // Setup the default processing configuration to the scene.
  97254. _this._attachImageProcessingConfiguration(null);
  97255. _this.getRenderTargetTextures = function () {
  97256. _this._renderTargets.reset();
  97257. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  97258. _this._renderTargets.push(_this._diffuseTexture);
  97259. }
  97260. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  97261. _this._renderTargets.push(_this._reflectionTexture);
  97262. }
  97263. return _this._renderTargets;
  97264. };
  97265. return _this;
  97266. }
  97267. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  97268. /**
  97269. * Experimental Internal Use Only.
  97270. *
  97271. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  97272. * This acts as a helper to set the primary color to a more "human friendly" value.
  97273. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  97274. * output color as close as possible from the chosen value.
  97275. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  97276. * part of lighting setup.)
  97277. */
  97278. get: function () {
  97279. return this.__perceptualColor;
  97280. },
  97281. set: function (value) {
  97282. this.__perceptualColor = value;
  97283. this._computePrimaryColorFromPerceptualColor();
  97284. this._markAllSubMeshesAsLightsDirty();
  97285. },
  97286. enumerable: true,
  97287. configurable: true
  97288. });
  97289. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  97290. /**
  97291. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  97292. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  97293. */
  97294. get: function () {
  97295. return this._primaryColorShadowLevel;
  97296. },
  97297. set: function (value) {
  97298. this._primaryColorShadowLevel = value;
  97299. this._computePrimaryColors();
  97300. this._markAllSubMeshesAsLightsDirty();
  97301. },
  97302. enumerable: true,
  97303. configurable: true
  97304. });
  97305. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  97306. /**
  97307. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  97308. * The primary color is used at the level chosen to define what the white area would look.
  97309. */
  97310. get: function () {
  97311. return this._primaryColorHighlightLevel;
  97312. },
  97313. set: function (value) {
  97314. this._primaryColorHighlightLevel = value;
  97315. this._computePrimaryColors();
  97316. this._markAllSubMeshesAsLightsDirty();
  97317. },
  97318. enumerable: true,
  97319. configurable: true
  97320. });
  97321. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  97322. /**
  97323. * Sets the reflection reflectance fresnel values according to the default standard
  97324. * empirically know to work well :-)
  97325. */
  97326. set: function (value) {
  97327. var reflectionWeight = value;
  97328. if (reflectionWeight < 0.5) {
  97329. reflectionWeight = reflectionWeight * 2.0;
  97330. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  97331. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  97332. }
  97333. else {
  97334. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  97335. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  97336. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  97337. }
  97338. },
  97339. enumerable: true,
  97340. configurable: true
  97341. });
  97342. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  97343. /**
  97344. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97345. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  97346. * Recommended to be keep at 1.0 except for special cases.
  97347. */
  97348. get: function () {
  97349. return this._fovMultiplier;
  97350. },
  97351. set: function (value) {
  97352. if (isNaN(value)) {
  97353. value = 1.0;
  97354. }
  97355. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  97356. },
  97357. enumerable: true,
  97358. configurable: true
  97359. });
  97360. /**
  97361. * Attaches a new image processing configuration to the PBR Material.
  97362. * @param configuration (if null the scene configuration will be use)
  97363. */
  97364. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  97365. var _this = this;
  97366. if (configuration === this._imageProcessingConfiguration) {
  97367. return;
  97368. }
  97369. // Detaches observer.
  97370. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97371. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97372. }
  97373. // Pick the scene configuration if needed.
  97374. if (!configuration) {
  97375. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  97376. }
  97377. else {
  97378. this._imageProcessingConfiguration = configuration;
  97379. }
  97380. // Attaches observer.
  97381. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  97382. _this._computePrimaryColorFromPerceptualColor();
  97383. _this._markAllSubMeshesAsImageProcessingDirty();
  97384. });
  97385. };
  97386. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  97387. /**
  97388. * Gets the image processing configuration used either in this material.
  97389. */
  97390. get: function () {
  97391. return this._imageProcessingConfiguration;
  97392. },
  97393. /**
  97394. * Sets the Default image processing configuration used either in the this material.
  97395. *
  97396. * If sets to null, the scene one is in use.
  97397. */
  97398. set: function (value) {
  97399. this._attachImageProcessingConfiguration(value);
  97400. // Ensure the effect will be rebuilt.
  97401. this._markAllSubMeshesAsTexturesDirty();
  97402. },
  97403. enumerable: true,
  97404. configurable: true
  97405. });
  97406. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  97407. /**
  97408. * Gets wether the color curves effect is enabled.
  97409. */
  97410. get: function () {
  97411. return this.imageProcessingConfiguration.colorCurvesEnabled;
  97412. },
  97413. /**
  97414. * Sets wether the color curves effect is enabled.
  97415. */
  97416. set: function (value) {
  97417. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  97418. },
  97419. enumerable: true,
  97420. configurable: true
  97421. });
  97422. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  97423. /**
  97424. * Gets wether the color grading effect is enabled.
  97425. */
  97426. get: function () {
  97427. return this.imageProcessingConfiguration.colorGradingEnabled;
  97428. },
  97429. /**
  97430. * Gets wether the color grading effect is enabled.
  97431. */
  97432. set: function (value) {
  97433. this.imageProcessingConfiguration.colorGradingEnabled = value;
  97434. },
  97435. enumerable: true,
  97436. configurable: true
  97437. });
  97438. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  97439. /**
  97440. * Gets wether tonemapping is enabled or not.
  97441. */
  97442. get: function () {
  97443. return this._imageProcessingConfiguration.toneMappingEnabled;
  97444. },
  97445. /**
  97446. * Sets wether tonemapping is enabled or not
  97447. */
  97448. set: function (value) {
  97449. this._imageProcessingConfiguration.toneMappingEnabled = value;
  97450. },
  97451. enumerable: true,
  97452. configurable: true
  97453. });
  97454. ;
  97455. ;
  97456. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  97457. /**
  97458. * The camera exposure used on this material.
  97459. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97460. * This corresponds to a photographic exposure.
  97461. */
  97462. get: function () {
  97463. return this._imageProcessingConfiguration.exposure;
  97464. },
  97465. /**
  97466. * The camera exposure used on this material.
  97467. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97468. * This corresponds to a photographic exposure.
  97469. */
  97470. set: function (value) {
  97471. this._imageProcessingConfiguration.exposure = value;
  97472. },
  97473. enumerable: true,
  97474. configurable: true
  97475. });
  97476. ;
  97477. ;
  97478. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  97479. /**
  97480. * Gets The camera contrast used on this material.
  97481. */
  97482. get: function () {
  97483. return this._imageProcessingConfiguration.contrast;
  97484. },
  97485. /**
  97486. * Sets The camera contrast used on this material.
  97487. */
  97488. set: function (value) {
  97489. this._imageProcessingConfiguration.contrast = value;
  97490. },
  97491. enumerable: true,
  97492. configurable: true
  97493. });
  97494. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  97495. /**
  97496. * Gets the Color Grading 2D Lookup Texture.
  97497. */
  97498. get: function () {
  97499. return this._imageProcessingConfiguration.colorGradingTexture;
  97500. },
  97501. /**
  97502. * Sets the Color Grading 2D Lookup Texture.
  97503. */
  97504. set: function (value) {
  97505. this.imageProcessingConfiguration.colorGradingTexture = value;
  97506. },
  97507. enumerable: true,
  97508. configurable: true
  97509. });
  97510. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  97511. /**
  97512. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97513. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97514. * 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;
  97515. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97516. */
  97517. get: function () {
  97518. return this.imageProcessingConfiguration.colorCurves;
  97519. },
  97520. /**
  97521. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97522. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97523. * 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;
  97524. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97525. */
  97526. set: function (value) {
  97527. this.imageProcessingConfiguration.colorCurves = value;
  97528. },
  97529. enumerable: true,
  97530. configurable: true
  97531. });
  97532. /**
  97533. * The entire material has been created in order to prevent overdraw.
  97534. * @returns false
  97535. */
  97536. BackgroundMaterial.prototype.needAlphaTesting = function () {
  97537. return true;
  97538. };
  97539. /**
  97540. * The entire material has been created in order to prevent overdraw.
  97541. * @returns true if blending is enable
  97542. */
  97543. BackgroundMaterial.prototype.needAlphaBlending = function () {
  97544. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  97545. };
  97546. /**
  97547. * Checks wether the material is ready to be rendered for a given mesh.
  97548. * @param mesh The mesh to render
  97549. * @param subMesh The submesh to check against
  97550. * @param useInstances Specify wether or not the material is used with instances
  97551. * @returns true if all the dependencies are ready (Textures, Effects...)
  97552. */
  97553. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  97554. var _this = this;
  97555. if (useInstances === void 0) { useInstances = false; }
  97556. if (subMesh.effect && this.isFrozen) {
  97557. if (this._wasPreviouslyReady) {
  97558. return true;
  97559. }
  97560. }
  97561. if (!subMesh._materialDefines) {
  97562. subMesh._materialDefines = new BackgroundMaterialDefines();
  97563. }
  97564. var scene = this.getScene();
  97565. var defines = subMesh._materialDefines;
  97566. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  97567. if (defines._renderId === scene.getRenderId()) {
  97568. return true;
  97569. }
  97570. }
  97571. var engine = scene.getEngine();
  97572. // Lights
  97573. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  97574. defines._needNormals = true;
  97575. // Textures
  97576. if (defines._areTexturesDirty) {
  97577. defines._needUVs = false;
  97578. if (scene.texturesEnabled) {
  97579. if (scene.getEngine().getCaps().textureLOD) {
  97580. defines.TEXTURELODSUPPORT = true;
  97581. }
  97582. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97583. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  97584. return false;
  97585. }
  97586. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  97587. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  97588. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  97589. defines.OPACITYFRESNEL = this._opacityFresnel;
  97590. }
  97591. else {
  97592. defines.DIFFUSE = false;
  97593. defines.DIFFUSEHASALPHA = false;
  97594. defines.GAMMADIFFUSE = false;
  97595. defines.OPACITYFRESNEL = false;
  97596. }
  97597. var reflectionTexture = this._reflectionTexture;
  97598. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97599. if (!reflectionTexture.isReadyOrNotBlocking()) {
  97600. return false;
  97601. }
  97602. defines.REFLECTION = true;
  97603. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  97604. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  97605. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  97606. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  97607. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  97608. defines.REFLECTIONBGR = this.switchToBGR;
  97609. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  97610. defines.INVERTCUBICMAP = true;
  97611. }
  97612. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  97613. switch (reflectionTexture.coordinatesMode) {
  97614. case BABYLON.Texture.EXPLICIT_MODE:
  97615. defines.REFLECTIONMAP_EXPLICIT = true;
  97616. break;
  97617. case BABYLON.Texture.PLANAR_MODE:
  97618. defines.REFLECTIONMAP_PLANAR = true;
  97619. break;
  97620. case BABYLON.Texture.PROJECTION_MODE:
  97621. defines.REFLECTIONMAP_PROJECTION = true;
  97622. break;
  97623. case BABYLON.Texture.SKYBOX_MODE:
  97624. defines.REFLECTIONMAP_SKYBOX = true;
  97625. break;
  97626. case BABYLON.Texture.SPHERICAL_MODE:
  97627. defines.REFLECTIONMAP_SPHERICAL = true;
  97628. break;
  97629. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  97630. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  97631. break;
  97632. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  97633. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  97634. break;
  97635. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  97636. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  97637. break;
  97638. case BABYLON.Texture.CUBIC_MODE:
  97639. case BABYLON.Texture.INVCUBIC_MODE:
  97640. default:
  97641. defines.REFLECTIONMAP_CUBIC = true;
  97642. break;
  97643. }
  97644. if (this.reflectionFresnel) {
  97645. defines.REFLECTIONFRESNEL = true;
  97646. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  97647. this._reflectionControls.x = this.reflectionAmount;
  97648. this._reflectionControls.y = this.reflectionReflectance0;
  97649. this._reflectionControls.z = this.reflectionReflectance90;
  97650. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  97651. }
  97652. else {
  97653. defines.REFLECTIONFRESNEL = false;
  97654. defines.REFLECTIONFALLOFF = false;
  97655. }
  97656. }
  97657. else {
  97658. defines.REFLECTION = false;
  97659. defines.REFLECTIONFRESNEL = false;
  97660. defines.REFLECTIONFALLOFF = false;
  97661. defines.REFLECTIONBLUR = false;
  97662. defines.REFLECTIONMAP_3D = false;
  97663. defines.REFLECTIONMAP_SPHERICAL = false;
  97664. defines.REFLECTIONMAP_PLANAR = false;
  97665. defines.REFLECTIONMAP_CUBIC = false;
  97666. defines.REFLECTIONMAP_PROJECTION = false;
  97667. defines.REFLECTIONMAP_SKYBOX = false;
  97668. defines.REFLECTIONMAP_EXPLICIT = false;
  97669. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97670. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97671. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97672. defines.INVERTCUBICMAP = false;
  97673. defines.REFLECTIONMAP_OPPOSITEZ = false;
  97674. defines.LODINREFLECTIONALPHA = false;
  97675. defines.GAMMAREFLECTION = false;
  97676. }
  97677. }
  97678. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  97679. defines.USERGBCOLOR = this._useRGBColor;
  97680. defines.NOISE = this._enableNoise;
  97681. }
  97682. if (defines._areLightsDirty) {
  97683. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  97684. }
  97685. if (defines._areImageProcessingDirty) {
  97686. if (!this._imageProcessingConfiguration.isReady()) {
  97687. return false;
  97688. }
  97689. this._imageProcessingConfiguration.prepareDefines(defines);
  97690. }
  97691. // Misc.
  97692. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  97693. // Values that need to be evaluated on every frame
  97694. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  97695. // Attribs
  97696. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  97697. if (mesh) {
  97698. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97699. mesh.createNormals(true);
  97700. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  97701. }
  97702. }
  97703. }
  97704. // Get correct effect
  97705. if (defines.isDirty) {
  97706. defines.markAsProcessed();
  97707. scene.resetCachedMaterial();
  97708. // Fallbacks
  97709. var fallbacks = new BABYLON.EffectFallbacks();
  97710. if (defines.FOG) {
  97711. fallbacks.addFallback(0, "FOG");
  97712. }
  97713. if (defines.POINTSIZE) {
  97714. fallbacks.addFallback(1, "POINTSIZE");
  97715. }
  97716. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  97717. if (defines.NUM_BONE_INFLUENCERS > 0) {
  97718. fallbacks.addCPUSkinningFallback(0, mesh);
  97719. }
  97720. //Attributes
  97721. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97722. if (defines.NORMAL) {
  97723. attribs.push(BABYLON.VertexBuffer.NormalKind);
  97724. }
  97725. if (defines.UV1) {
  97726. attribs.push(BABYLON.VertexBuffer.UVKind);
  97727. }
  97728. if (defines.UV2) {
  97729. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97730. }
  97731. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  97732. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  97733. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  97734. "vFogInfos", "vFogColor", "pointSize",
  97735. "vClipPlane", "mBones",
  97736. "vPrimaryColor", "vPrimaryColorShadow",
  97737. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  97738. "shadowLevel", "alpha",
  97739. "vBackgroundCenter", "vReflectionControl",
  97740. "vDiffuseInfos", "diffuseMatrix",
  97741. ];
  97742. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  97743. var uniformBuffers = ["Material", "Scene"];
  97744. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  97745. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  97746. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  97747. uniformsNames: uniforms,
  97748. uniformBuffersNames: uniformBuffers,
  97749. samplers: samplers,
  97750. defines: defines,
  97751. maxSimultaneousLights: this._maxSimultaneousLights
  97752. });
  97753. var onCompiled = function (effect) {
  97754. if (_this.onCompiled) {
  97755. _this.onCompiled(effect);
  97756. }
  97757. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  97758. };
  97759. var join = defines.toString();
  97760. subMesh.setEffect(scene.getEngine().createEffect("background", {
  97761. attributes: attribs,
  97762. uniformsNames: uniforms,
  97763. uniformBuffersNames: uniformBuffers,
  97764. samplers: samplers,
  97765. defines: join,
  97766. fallbacks: fallbacks,
  97767. onCompiled: onCompiled,
  97768. onError: this.onError,
  97769. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  97770. }, engine), defines);
  97771. this.buildUniformLayout();
  97772. }
  97773. if (!subMesh.effect || !subMesh.effect.isReady()) {
  97774. return false;
  97775. }
  97776. defines._renderId = scene.getRenderId();
  97777. this._wasPreviouslyReady = true;
  97778. return true;
  97779. };
  97780. /**
  97781. * Compute the primary color according to the chosen perceptual color.
  97782. */
  97783. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  97784. if (!this.__perceptualColor) {
  97785. return;
  97786. }
  97787. this._primaryColor.copyFrom(this.__perceptualColor);
  97788. // Revert gamma space.
  97789. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  97790. // Revert image processing configuration.
  97791. if (this._imageProcessingConfiguration) {
  97792. // Revert Exposure.
  97793. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  97794. }
  97795. this._computePrimaryColors();
  97796. };
  97797. /**
  97798. * Compute the highlights and shadow colors according to their chosen levels.
  97799. */
  97800. BackgroundMaterial.prototype._computePrimaryColors = function () {
  97801. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  97802. return;
  97803. }
  97804. // Find the highlight color based on the configuration.
  97805. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  97806. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  97807. // Find the shadow color based on the configuration.
  97808. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  97809. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  97810. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  97811. };
  97812. /**
  97813. * Build the uniform buffer used in the material.
  97814. */
  97815. BackgroundMaterial.prototype.buildUniformLayout = function () {
  97816. // Order is important !
  97817. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  97818. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  97819. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  97820. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  97821. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  97822. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  97823. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  97824. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  97825. this._uniformBuffer.addUniform("pointSize", 1);
  97826. this._uniformBuffer.addUniform("shadowLevel", 1);
  97827. this._uniformBuffer.addUniform("alpha", 1);
  97828. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97829. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97830. this._uniformBuffer.create();
  97831. };
  97832. /**
  97833. * Unbind the material.
  97834. */
  97835. BackgroundMaterial.prototype.unbind = function () {
  97836. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97837. this._uniformBuffer.setTexture("diffuseSampler", null);
  97838. }
  97839. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97840. this._uniformBuffer.setTexture("reflectionSampler", null);
  97841. }
  97842. _super.prototype.unbind.call(this);
  97843. };
  97844. /**
  97845. * Bind only the world matrix to the material.
  97846. * @param world The world matrix to bind.
  97847. */
  97848. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97849. this._activeEffect.setMatrix("world", world);
  97850. };
  97851. /**
  97852. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97853. * @param world The world matrix to bind.
  97854. * @param subMesh The submesh to bind for.
  97855. */
  97856. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97857. var scene = this.getScene();
  97858. var defines = subMesh._materialDefines;
  97859. if (!defines) {
  97860. return;
  97861. }
  97862. var effect = subMesh.effect;
  97863. if (!effect) {
  97864. return;
  97865. }
  97866. this._activeEffect = effect;
  97867. // Matrices
  97868. this.bindOnlyWorldMatrix(world);
  97869. // Bones
  97870. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97871. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97872. if (mustRebind) {
  97873. this._uniformBuffer.bindToEffect(effect, "Material");
  97874. this.bindViewProjection(effect);
  97875. var reflectionTexture = this._reflectionTexture;
  97876. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97877. // Texture uniforms
  97878. if (scene.texturesEnabled) {
  97879. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97880. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97881. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97882. }
  97883. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97884. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97885. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97886. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97887. }
  97888. }
  97889. if (this.shadowLevel > 0) {
  97890. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97891. }
  97892. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97893. // Point size
  97894. if (this.pointsCloud) {
  97895. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97896. }
  97897. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97898. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97899. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97900. }
  97901. else {
  97902. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97903. }
  97904. }
  97905. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97906. // Textures
  97907. if (scene.texturesEnabled) {
  97908. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97909. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97910. }
  97911. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97912. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97913. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97914. }
  97915. else if (!defines.REFLECTIONBLUR) {
  97916. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97917. }
  97918. else {
  97919. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97920. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97921. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97922. }
  97923. if (defines.REFLECTIONFRESNEL) {
  97924. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97925. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97926. }
  97927. }
  97928. }
  97929. // Clip plane
  97930. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97931. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97932. }
  97933. if (mustRebind || !this.isFrozen) {
  97934. if (scene.lightsEnabled) {
  97935. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97936. }
  97937. // View
  97938. this.bindView(effect);
  97939. // Fog
  97940. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97941. // image processing
  97942. this._imageProcessingConfiguration.bind(this._activeEffect);
  97943. }
  97944. this._uniformBuffer.update();
  97945. this._afterBind(mesh);
  97946. };
  97947. /**
  97948. * Dispose the material.
  97949. * @param forceDisposeEffect Force disposal of the associated effect.
  97950. * @param forceDisposeTextures Force disposal of the associated textures.
  97951. */
  97952. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97953. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97954. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97955. if (forceDisposeTextures) {
  97956. if (this.diffuseTexture) {
  97957. this.diffuseTexture.dispose();
  97958. }
  97959. if (this.reflectionTexture) {
  97960. this.reflectionTexture.dispose();
  97961. }
  97962. }
  97963. this._renderTargets.dispose();
  97964. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97965. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97966. }
  97967. _super.prototype.dispose.call(this, forceDisposeEffect);
  97968. };
  97969. /**
  97970. * Clones the material.
  97971. * @param name The cloned name.
  97972. * @returns The cloned material.
  97973. */
  97974. BackgroundMaterial.prototype.clone = function (name) {
  97975. var _this = this;
  97976. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97977. };
  97978. /**
  97979. * Serializes the current material to its JSON representation.
  97980. * @returns The JSON representation.
  97981. */
  97982. BackgroundMaterial.prototype.serialize = function () {
  97983. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97984. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97985. return serializationObject;
  97986. };
  97987. /**
  97988. * Gets the class name of the material
  97989. * @returns "BackgroundMaterial"
  97990. */
  97991. BackgroundMaterial.prototype.getClassName = function () {
  97992. return "BackgroundMaterial";
  97993. };
  97994. /**
  97995. * Parse a JSON input to create back a background material.
  97996. * @param source The JSON data to parse
  97997. * @param scene The scene to create the parsed material in
  97998. * @param rootUrl The root url of the assets the material depends upon
  97999. * @returns the instantiated BackgroundMaterial.
  98000. */
  98001. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  98002. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  98003. };
  98004. /**
  98005. * Standard reflectance value at parallel view angle.
  98006. */
  98007. BackgroundMaterial.StandardReflectance0 = 0.05;
  98008. /**
  98009. * Standard reflectance value at grazing angle.
  98010. */
  98011. BackgroundMaterial.StandardReflectance90 = 0.5;
  98012. __decorate([
  98013. BABYLON.serializeAsColor3()
  98014. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  98015. __decorate([
  98016. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  98017. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  98018. __decorate([
  98019. BABYLON.serializeAsColor3()
  98020. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  98021. __decorate([
  98022. BABYLON.serialize()
  98023. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  98024. __decorate([
  98025. BABYLON.serialize()
  98026. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  98027. __decorate([
  98028. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  98029. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  98030. __decorate([
  98031. BABYLON.serializeAsTexture()
  98032. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  98033. __decorate([
  98034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98035. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  98036. __decorate([
  98037. BABYLON.serialize()
  98038. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  98039. __decorate([
  98040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98041. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  98042. __decorate([
  98043. BABYLON.serializeAsTexture()
  98044. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  98045. __decorate([
  98046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98047. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  98048. __decorate([
  98049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98050. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  98051. __decorate([
  98052. BABYLON.serialize()
  98053. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  98054. __decorate([
  98055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98056. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  98057. __decorate([
  98058. BABYLON.serializeAsVector3()
  98059. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  98060. __decorate([
  98061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98062. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  98063. __decorate([
  98064. BABYLON.serialize()
  98065. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  98066. __decorate([
  98067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98068. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  98069. __decorate([
  98070. BABYLON.serialize()
  98071. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  98072. __decorate([
  98073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98074. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  98075. __decorate([
  98076. BABYLON.serialize()
  98077. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  98078. __decorate([
  98079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98080. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  98081. __decorate([
  98082. BABYLON.serialize()
  98083. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  98084. __decorate([
  98085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98086. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  98087. __decorate([
  98088. BABYLON.serialize()
  98089. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  98090. __decorate([
  98091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98092. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  98093. __decorate([
  98094. BABYLON.serialize()
  98095. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  98096. __decorate([
  98097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98098. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  98099. __decorate([
  98100. BABYLON.serialize()
  98101. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  98102. __decorate([
  98103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98104. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  98105. __decorate([
  98106. BABYLON.serialize()
  98107. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  98108. __decorate([
  98109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98110. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  98111. __decorate([
  98112. BABYLON.serialize()
  98113. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  98114. __decorate([
  98115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98116. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  98117. __decorate([
  98118. BABYLON.serializeAsImageProcessingConfiguration()
  98119. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  98120. return BackgroundMaterial;
  98121. }(BABYLON.PushMaterial));
  98122. BABYLON.BackgroundMaterial = BackgroundMaterial;
  98123. })(BABYLON || (BABYLON = {}));
  98124. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  98125. var __assign = (this && this.__assign) || Object.assign || function(t) {
  98126. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98127. s = arguments[i];
  98128. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98129. t[p] = s[p];
  98130. }
  98131. return t;
  98132. };
  98133. var BABYLON;
  98134. (function (BABYLON) {
  98135. /**
  98136. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  98137. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  98138. * It also helps with the default setup of your imageProcessing configuration.
  98139. */
  98140. var EnvironmentHelper = /** @class */ (function () {
  98141. /**
  98142. * constructor
  98143. * @param options
  98144. * @param scene The scene to add the material to
  98145. */
  98146. function EnvironmentHelper(options, scene) {
  98147. var _this = this;
  98148. this._errorHandler = function (message, exception) {
  98149. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  98150. };
  98151. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  98152. this._scene = scene;
  98153. this.onErrorObservable = new BABYLON.Observable();
  98154. this._setupBackground();
  98155. this._setupImageProcessing();
  98156. }
  98157. /**
  98158. * Creates the default options for the helper.
  98159. */
  98160. EnvironmentHelper._getDefaultOptions = function () {
  98161. return {
  98162. createGround: true,
  98163. groundSize: 15,
  98164. groundTexture: this._groundTextureCDNUrl,
  98165. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98166. groundOpacity: 0.9,
  98167. enableGroundShadow: true,
  98168. groundShadowLevel: 0.5,
  98169. enableGroundMirror: false,
  98170. groundMirrorSizeRatio: 0.3,
  98171. groundMirrorBlurKernel: 64,
  98172. groundMirrorAmount: 1,
  98173. groundMirrorFresnelWeight: 1,
  98174. groundMirrorFallOffDistance: 0,
  98175. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  98176. groundYBias: 0.00001,
  98177. createSkybox: true,
  98178. skyboxSize: 20,
  98179. skyboxTexture: this._skyboxTextureCDNUrl,
  98180. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98181. backgroundYRotation: 0,
  98182. sizeAuto: true,
  98183. rootPosition: BABYLON.Vector3.Zero(),
  98184. setupImageProcessing: true,
  98185. environmentTexture: this._environmentTextureCDNUrl,
  98186. cameraExposure: 0.8,
  98187. cameraContrast: 1.2,
  98188. toneMappingEnabled: true,
  98189. };
  98190. };
  98191. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  98192. /**
  98193. * Gets the root mesh created by the helper.
  98194. */
  98195. get: function () {
  98196. return this._rootMesh;
  98197. },
  98198. enumerable: true,
  98199. configurable: true
  98200. });
  98201. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  98202. /**
  98203. * Gets the skybox created by the helper.
  98204. */
  98205. get: function () {
  98206. return this._skybox;
  98207. },
  98208. enumerable: true,
  98209. configurable: true
  98210. });
  98211. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  98212. /**
  98213. * Gets the skybox texture created by the helper.
  98214. */
  98215. get: function () {
  98216. return this._skyboxTexture;
  98217. },
  98218. enumerable: true,
  98219. configurable: true
  98220. });
  98221. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  98222. /**
  98223. * Gets the skybox material created by the helper.
  98224. */
  98225. get: function () {
  98226. return this._skyboxMaterial;
  98227. },
  98228. enumerable: true,
  98229. configurable: true
  98230. });
  98231. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  98232. /**
  98233. * Gets the ground mesh created by the helper.
  98234. */
  98235. get: function () {
  98236. return this._ground;
  98237. },
  98238. enumerable: true,
  98239. configurable: true
  98240. });
  98241. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  98242. /**
  98243. * Gets the ground texture created by the helper.
  98244. */
  98245. get: function () {
  98246. return this._groundTexture;
  98247. },
  98248. enumerable: true,
  98249. configurable: true
  98250. });
  98251. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  98252. /**
  98253. * Gets the ground mirror created by the helper.
  98254. */
  98255. get: function () {
  98256. return this._groundMirror;
  98257. },
  98258. enumerable: true,
  98259. configurable: true
  98260. });
  98261. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  98262. /**
  98263. * Gets the ground mirror render list to helps pushing the meshes
  98264. * you wish in the ground reflection.
  98265. */
  98266. get: function () {
  98267. if (this._groundMirror) {
  98268. return this._groundMirror.renderList;
  98269. }
  98270. return null;
  98271. },
  98272. enumerable: true,
  98273. configurable: true
  98274. });
  98275. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  98276. /**
  98277. * Gets the ground material created by the helper.
  98278. */
  98279. get: function () {
  98280. return this._groundMaterial;
  98281. },
  98282. enumerable: true,
  98283. configurable: true
  98284. });
  98285. /**
  98286. * Updates the background according to the new options
  98287. * @param options
  98288. */
  98289. EnvironmentHelper.prototype.updateOptions = function (options) {
  98290. var newOptions = __assign({}, this._options, options);
  98291. if (this._ground && !newOptions.createGround) {
  98292. this._ground.dispose();
  98293. this._ground = null;
  98294. }
  98295. if (this._groundMaterial && !newOptions.createGround) {
  98296. this._groundMaterial.dispose();
  98297. this._groundMaterial = null;
  98298. }
  98299. if (this._groundTexture) {
  98300. if (this._options.groundTexture != newOptions.groundTexture) {
  98301. this._groundTexture.dispose();
  98302. this._groundTexture = null;
  98303. }
  98304. }
  98305. if (this._skybox && !newOptions.createSkybox) {
  98306. this._skybox.dispose();
  98307. this._skybox = null;
  98308. }
  98309. if (this._skyboxMaterial && !newOptions.createSkybox) {
  98310. this._skyboxMaterial.dispose();
  98311. this._skyboxMaterial = null;
  98312. }
  98313. if (this._skyboxTexture) {
  98314. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  98315. this._skyboxTexture.dispose();
  98316. this._skyboxTexture = null;
  98317. }
  98318. }
  98319. if (this._groundMirror && !newOptions.enableGroundMirror) {
  98320. this._groundMirror.dispose();
  98321. this._groundMirror = null;
  98322. }
  98323. if (this._scene.environmentTexture) {
  98324. if (this._options.environmentTexture != newOptions.environmentTexture) {
  98325. this._scene.environmentTexture.dispose();
  98326. }
  98327. }
  98328. this._options = newOptions;
  98329. this._setupBackground();
  98330. this._setupImageProcessing();
  98331. };
  98332. /**
  98333. * Sets the primary color of all the available elements.
  98334. * @param color the main color to affect to the ground and the background
  98335. */
  98336. EnvironmentHelper.prototype.setMainColor = function (color) {
  98337. if (this.groundMaterial) {
  98338. this.groundMaterial.primaryColor = color;
  98339. }
  98340. if (this.skyboxMaterial) {
  98341. this.skyboxMaterial.primaryColor = color;
  98342. }
  98343. if (this.groundMirror) {
  98344. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  98345. }
  98346. };
  98347. /**
  98348. * Setup the image processing according to the specified options.
  98349. */
  98350. EnvironmentHelper.prototype._setupImageProcessing = function () {
  98351. if (this._options.setupImageProcessing) {
  98352. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  98353. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  98354. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  98355. this._setupEnvironmentTexture();
  98356. }
  98357. };
  98358. /**
  98359. * Setup the environment texture according to the specified options.
  98360. */
  98361. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  98362. if (this._scene.environmentTexture) {
  98363. return;
  98364. }
  98365. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  98366. this._scene.environmentTexture = this._options.environmentTexture;
  98367. return;
  98368. }
  98369. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  98370. this._scene.environmentTexture = environmentTexture;
  98371. };
  98372. /**
  98373. * Setup the background according to the specified options.
  98374. */
  98375. EnvironmentHelper.prototype._setupBackground = function () {
  98376. if (!this._rootMesh) {
  98377. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  98378. }
  98379. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  98380. var sceneSize = this._getSceneSize();
  98381. if (this._options.createGround) {
  98382. this._setupGround(sceneSize);
  98383. this._setupGroundMaterial();
  98384. this._setupGroundDiffuseTexture();
  98385. if (this._options.enableGroundMirror) {
  98386. this._setupGroundMirrorTexture(sceneSize);
  98387. }
  98388. this._setupMirrorInGroundMaterial();
  98389. }
  98390. if (this._options.createSkybox) {
  98391. this._setupSkybox(sceneSize);
  98392. this._setupSkyboxMaterial();
  98393. this._setupSkyboxReflectionTexture();
  98394. }
  98395. this._rootMesh.position.x = sceneSize.rootPosition.x;
  98396. this._rootMesh.position.z = sceneSize.rootPosition.z;
  98397. this._rootMesh.position.y = sceneSize.rootPosition.y;
  98398. };
  98399. /**
  98400. * Get the scene sizes according to the setup.
  98401. */
  98402. EnvironmentHelper.prototype._getSceneSize = function () {
  98403. var _this = this;
  98404. var groundSize = this._options.groundSize;
  98405. var skyboxSize = this._options.skyboxSize;
  98406. var rootPosition = this._options.rootPosition;
  98407. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  98408. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98409. }
  98410. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  98411. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  98412. });
  98413. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98414. if (this._options.sizeAuto) {
  98415. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  98416. this._scene.activeCamera.upperRadiusLimit) {
  98417. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  98418. skyboxSize = groundSize;
  98419. }
  98420. var sceneDiagonalLenght = sceneDiagonal.length();
  98421. if (sceneDiagonalLenght > groundSize) {
  98422. groundSize = sceneDiagonalLenght * 2;
  98423. skyboxSize = groundSize;
  98424. }
  98425. // 10 % bigger.
  98426. groundSize *= 1.1;
  98427. skyboxSize *= 1.5;
  98428. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  98429. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  98430. }
  98431. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98432. };
  98433. /**
  98434. * Setup the ground according to the specified options.
  98435. */
  98436. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  98437. var _this = this;
  98438. if (!this._ground) {
  98439. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  98440. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  98441. this._ground.parent = this._rootMesh;
  98442. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  98443. }
  98444. this._ground.receiveShadows = this._options.enableGroundShadow;
  98445. };
  98446. /**
  98447. * Setup the ground material according to the specified options.
  98448. */
  98449. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  98450. if (!this._groundMaterial) {
  98451. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  98452. }
  98453. this._groundMaterial.alpha = this._options.groundOpacity;
  98454. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  98455. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  98456. this._groundMaterial.primaryColor = this._options.groundColor;
  98457. this._groundMaterial.useRGBColor = false;
  98458. this._groundMaterial.enableNoise = true;
  98459. if (this._ground) {
  98460. this._ground.material = this._groundMaterial;
  98461. }
  98462. };
  98463. /**
  98464. * Setup the ground diffuse texture according to the specified options.
  98465. */
  98466. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  98467. if (!this._groundMaterial) {
  98468. return;
  98469. }
  98470. if (this._groundTexture) {
  98471. return;
  98472. }
  98473. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  98474. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  98475. return;
  98476. }
  98477. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98478. diffuseTexture.gammaSpace = false;
  98479. diffuseTexture.hasAlpha = true;
  98480. this._groundMaterial.diffuseTexture = diffuseTexture;
  98481. };
  98482. /**
  98483. * Setup the ground mirror texture according to the specified options.
  98484. */
  98485. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  98486. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98487. if (!this._groundMirror) {
  98488. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  98489. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  98490. this._groundMirror.anisotropicFilteringLevel = 1;
  98491. this._groundMirror.wrapU = wrapping;
  98492. this._groundMirror.wrapV = wrapping;
  98493. this._groundMirror.gammaSpace = false;
  98494. if (this._groundMirror.renderList) {
  98495. for (var i = 0; i < this._scene.meshes.length; i++) {
  98496. var mesh = this._scene.meshes[i];
  98497. if (mesh !== this._ground &&
  98498. mesh !== this._skybox &&
  98499. mesh !== this._rootMesh) {
  98500. this._groundMirror.renderList.push(mesh);
  98501. }
  98502. }
  98503. }
  98504. }
  98505. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  98506. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  98507. };
  98508. /**
  98509. * Setup the ground to receive the mirror texture.
  98510. */
  98511. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  98512. if (this._groundMaterial) {
  98513. this._groundMaterial.reflectionTexture = this._groundMirror;
  98514. this._groundMaterial.reflectionFresnel = true;
  98515. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  98516. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  98517. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  98518. }
  98519. };
  98520. /**
  98521. * Setup the skybox according to the specified options.
  98522. */
  98523. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  98524. var _this = this;
  98525. if (!this._skybox) {
  98526. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  98527. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  98528. }
  98529. this._skybox.parent = this._rootMesh;
  98530. };
  98531. /**
  98532. * Setup the skybox material according to the specified options.
  98533. */
  98534. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  98535. if (!this._skybox) {
  98536. return;
  98537. }
  98538. if (!this._skyboxMaterial) {
  98539. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  98540. }
  98541. this._skyboxMaterial.useRGBColor = false;
  98542. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  98543. this._skyboxMaterial.enableNoise = true;
  98544. this._skybox.material = this._skyboxMaterial;
  98545. };
  98546. /**
  98547. * Setup the skybox reflection texture according to the specified options.
  98548. */
  98549. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  98550. if (!this._skyboxMaterial) {
  98551. return;
  98552. }
  98553. if (this._skyboxTexture) {
  98554. return;
  98555. }
  98556. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  98557. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  98558. return;
  98559. }
  98560. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98561. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  98562. this._skyboxTexture.gammaSpace = false;
  98563. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  98564. };
  98565. /**
  98566. * Dispose all the elements created by the Helper.
  98567. */
  98568. EnvironmentHelper.prototype.dispose = function () {
  98569. if (this._groundMaterial) {
  98570. this._groundMaterial.dispose(true, true);
  98571. }
  98572. if (this._skyboxMaterial) {
  98573. this._skyboxMaterial.dispose(true, true);
  98574. }
  98575. this._rootMesh.dispose(false);
  98576. };
  98577. /**
  98578. * Default ground texture URL.
  98579. */
  98580. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  98581. /**
  98582. * Default skybox texture URL.
  98583. */
  98584. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  98585. /**
  98586. * Default environment texture URL.
  98587. */
  98588. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  98589. return EnvironmentHelper;
  98590. }());
  98591. BABYLON.EnvironmentHelper = EnvironmentHelper;
  98592. })(BABYLON || (BABYLON = {}));
  98593. //# sourceMappingURL=babylon.environmentHelper.js.map
  98594. var BABYLON;
  98595. (function (BABYLON) {
  98596. /**
  98597. * This class is made for on one-liner static method to help creating particle systems.
  98598. */
  98599. var ParticleHelper = /** @class */ (function () {
  98600. function ParticleHelper() {
  98601. }
  98602. /**
  98603. * This is the main static method (one-liner) of this helper to create different particle systems.
  98604. * @param type This string represents the type to the particle system to create
  98605. * @param emitter The object where the particle system will start to emit from.
  98606. * @param scene The scene where the particle system should live.
  98607. * @param gpu If the system will use gpu.
  98608. * @returns the ParticleSystem created.
  98609. */
  98610. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  98611. var _this = this;
  98612. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  98613. if (gpu === void 0) { gpu = false; }
  98614. return new Promise(function (resolve, reject) {
  98615. if (scene) {
  98616. _this._scene = scene;
  98617. }
  98618. else {
  98619. return reject("A particle system need a scene.");
  98620. }
  98621. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  98622. return reject("Particle system with GPU is not supported.");
  98623. }
  98624. _this._emitter = emitter;
  98625. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  98626. var newData = JSON.parse(data.toString());
  98627. return resolve(_this._createSystem(newData));
  98628. }, undefined, undefined, undefined, function (req, exception) {
  98629. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  98630. });
  98631. });
  98632. };
  98633. ParticleHelper._createSystem = function (data) {
  98634. // Create a particle system
  98635. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  98636. // Texture of each particle
  98637. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  98638. // Where the particles come from
  98639. system.emitter = this._emitter; // the starting object, the emitter
  98640. // Colors of all particles
  98641. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  98642. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  98643. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  98644. // Size of each particle (random between...
  98645. system.minSize = data.minSize;
  98646. system.maxSize = data.maxSize;
  98647. // Life time of each particle (random between...
  98648. system.minLifeTime = data.minLifeTime;
  98649. system.maxLifeTime = data.maxLifeTime;
  98650. // Emission rate
  98651. system.emitRate = data.emitRate;
  98652. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  98653. system.blendMode = data.blendMode;
  98654. // Set the gravity of all particles
  98655. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  98656. // Angular speed, in radians
  98657. system.minAngularSpeed = data.minAngularSpeed;
  98658. system.maxAngularSpeed = data.maxAngularSpeed;
  98659. // Speed
  98660. system.minEmitPower = data.minEmitPower;
  98661. system.maxEmitPower = data.maxEmitPower;
  98662. system.updateSpeed = data.updateSpeed;
  98663. switch (data.emitterType) {
  98664. case "box":
  98665. if (!data.direction1 || !data.direction2) {
  98666. throw new Error("Directions are missing in this particle system.");
  98667. }
  98668. if (!data.minEmitBox || !data.maxEmitBox) {
  98669. throw new Error("EmitBox is missing in this particle system.");
  98670. }
  98671. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  98672. break;
  98673. case "sphere":
  98674. system.createSphereEmitter(data.radius);
  98675. break;
  98676. case "directed_sphere":
  98677. if (!data.direction1 || !data.direction2) {
  98678. throw new Error("Directions are missing in this particle system.");
  98679. }
  98680. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  98681. break;
  98682. case "cone":
  98683. system.createConeEmitter(data.radius, data.angle);
  98684. break;
  98685. default:
  98686. break;
  98687. }
  98688. return system;
  98689. };
  98690. /**
  98691. * Base Assets URL.
  98692. */
  98693. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  98694. return ParticleHelper;
  98695. }());
  98696. BABYLON.ParticleHelper = ParticleHelper;
  98697. })(BABYLON || (BABYLON = {}));
  98698. //# sourceMappingURL=babylon.particleHelper.js.map
  98699. var BABYLON;
  98700. (function (BABYLON) {
  98701. /**
  98702. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  98703. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  98704. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  98705. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  98706. */
  98707. var VideoDome = /** @class */ (function (_super) {
  98708. __extends(VideoDome, _super);
  98709. /**
  98710. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  98711. * @param name Element's name, child elements will append suffixes for their own names.
  98712. * @param urlsOrVideo
  98713. * @param options An object containing optional or exposed sub element properties:
  98714. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  98715. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  98716. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  98717. * @param options **loop=true** Automatically loop video on end.
  98718. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  98719. */
  98720. function VideoDome(name, urlsOrVideo, options, scene) {
  98721. var _this = _super.call(this, name, scene) || this;
  98722. // set defaults and manage values
  98723. name = name || "videoDome";
  98724. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  98725. options.clickToPlay = Boolean(options.clickToPlay);
  98726. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  98727. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  98728. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  98729. // create
  98730. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  98731. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  98732. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  98733. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  98734. flat: false,
  98735. radius: options.size,
  98736. subdivisions: options.resolution,
  98737. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  98738. }, scene);
  98739. // configure material
  98740. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  98741. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  98742. material.reflectionTexture = _this._videoTexture;
  98743. material.useEquirectangularFOV = true;
  98744. material.fovMultiplier = 1.0;
  98745. // configure mesh
  98746. _this._mesh.material = material;
  98747. _this._mesh.parent = _this;
  98748. // optional configuration
  98749. if (options.clickToPlay) {
  98750. scene.onPointerUp = function () {
  98751. _this._videoTexture.video.play();
  98752. };
  98753. }
  98754. return _this;
  98755. }
  98756. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  98757. /**
  98758. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98759. * Also see the options.resolution property.
  98760. */
  98761. get: function () {
  98762. return this._material.fovMultiplier;
  98763. },
  98764. set: function (value) {
  98765. this._material.fovMultiplier = value;
  98766. },
  98767. enumerable: true,
  98768. configurable: true
  98769. });
  98770. /**
  98771. * Releases resources associated with this node.
  98772. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  98773. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  98774. */
  98775. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  98776. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  98777. this._videoTexture.dispose();
  98778. this._mesh.dispose();
  98779. this._material.dispose();
  98780. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  98781. };
  98782. return VideoDome;
  98783. }(BABYLON.Node));
  98784. BABYLON.VideoDome = VideoDome;
  98785. })(BABYLON || (BABYLON = {}));
  98786. //# sourceMappingURL=babylon.videoDome.js.map
  98787. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nin vec2 angle;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\nvec2 cornerPos=offset*size;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform vec2 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  98788. 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};"};
  98789. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  98790. globalObject["BABYLON"] = BABYLON;
  98791. //backwards compatibility
  98792. if(typeof earcut !== 'undefined') {
  98793. globalObject["Earcut"] = {
  98794. earcut: earcut
  98795. };
  98796. }
  98797. return BABYLON;
  98798. });
  98799. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25)))
  98800. /***/ }),
  98801. /* 1 */
  98802. /***/ (function(module, exports, __webpack_require__) {
  98803. (function (global, factory) {
  98804. true ? module.exports = factory() :
  98805. typeof define === 'function' && define.amd ? define(factory) :
  98806. (global.deepmerge = factory());
  98807. }(this, (function () { 'use strict';
  98808. var isMergeableObject = function isMergeableObject(value) {
  98809. return isNonNullObject(value)
  98810. && !isSpecial(value)
  98811. };
  98812. function isNonNullObject(value) {
  98813. return !!value && typeof value === 'object'
  98814. }
  98815. function isSpecial(value) {
  98816. var stringValue = Object.prototype.toString.call(value);
  98817. return stringValue === '[object RegExp]'
  98818. || stringValue === '[object Date]'
  98819. || isReactElement(value)
  98820. }
  98821. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  98822. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  98823. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  98824. function isReactElement(value) {
  98825. return value.$$typeof === REACT_ELEMENT_TYPE
  98826. }
  98827. function emptyTarget(val) {
  98828. return Array.isArray(val) ? [] : {}
  98829. }
  98830. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  98831. var clone = !optionsArgument || optionsArgument.clone !== false;
  98832. return (clone && isMergeableObject(value))
  98833. ? deepmerge(emptyTarget(value), value, optionsArgument)
  98834. : value
  98835. }
  98836. function defaultArrayMerge(target, source, optionsArgument) {
  98837. return target.concat(source).map(function(element) {
  98838. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  98839. })
  98840. }
  98841. function mergeObject(target, source, optionsArgument) {
  98842. var destination = {};
  98843. if (isMergeableObject(target)) {
  98844. Object.keys(target).forEach(function(key) {
  98845. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  98846. });
  98847. }
  98848. Object.keys(source).forEach(function(key) {
  98849. if (!isMergeableObject(source[key]) || !target[key]) {
  98850. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  98851. } else {
  98852. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  98853. }
  98854. });
  98855. return destination
  98856. }
  98857. function deepmerge(target, source, optionsArgument) {
  98858. var sourceIsArray = Array.isArray(source);
  98859. var targetIsArray = Array.isArray(target);
  98860. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  98861. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  98862. if (!sourceAndTargetTypesMatch) {
  98863. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  98864. } else if (sourceIsArray) {
  98865. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  98866. return arrayMerge(target, source, optionsArgument)
  98867. } else {
  98868. return mergeObject(target, source, optionsArgument)
  98869. }
  98870. }
  98871. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  98872. if (!Array.isArray(array)) {
  98873. throw new Error('first argument should be an array')
  98874. }
  98875. return array.reduce(function(prev, next) {
  98876. return deepmerge(prev, next, optionsArgument)
  98877. }, {})
  98878. };
  98879. var deepmerge_1 = deepmerge;
  98880. return deepmerge_1;
  98881. })));
  98882. /***/ }),
  98883. /* 2 */
  98884. /***/ (function(module, exports, __webpack_require__) {
  98885. "use strict";
  98886. Object.defineProperty(exports, "__esModule", { value: true });
  98887. /**
  98888. * Is the provided string a URL?
  98889. *
  98890. * @param urlToCheck the url to inspect
  98891. */
  98892. function isUrl(urlToCheck) {
  98893. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  98894. return true;
  98895. }
  98896. return false;
  98897. }
  98898. exports.isUrl = isUrl;
  98899. /**
  98900. * Convert a string from kebab-case to camelCase
  98901. * @param s string to convert
  98902. */
  98903. function kebabToCamel(s) {
  98904. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  98905. }
  98906. exports.kebabToCamel = kebabToCamel;
  98907. //https://gist.github.com/youssman/745578062609e8acac9f
  98908. /**
  98909. * Convert a string from camelCase to kebab-case
  98910. * @param str string to convert
  98911. */
  98912. function camelToKebab(str) {
  98913. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  98914. }
  98915. exports.camelToKebab = camelToKebab;
  98916. /**
  98917. * This will extend an object with configuration values.
  98918. * What it practically does it take the keys from the configuration and set them on the object.
  98919. * I the configuration is a tree, it will traverse into the tree.
  98920. * @param object the object to extend
  98921. * @param config the configuration object that will extend the object
  98922. */
  98923. function extendClassWithConfig(object, config) {
  98924. if (!config)
  98925. return;
  98926. Object.keys(config).forEach(function (key) {
  98927. if (key in object && typeof object[key] !== 'function') {
  98928. // if (typeof object[key] === 'function') return;
  98929. // if it is an object, iterate internally until reaching basic types
  98930. if (typeof object[key] === 'object') {
  98931. extendClassWithConfig(object[key], config[key]);
  98932. }
  98933. else {
  98934. if (config[key] !== undefined) {
  98935. object[key] = config[key];
  98936. }
  98937. }
  98938. }
  98939. });
  98940. }
  98941. exports.extendClassWithConfig = extendClassWithConfig;
  98942. /***/ }),
  98943. /* 3 */
  98944. /***/ (function(module, exports, __webpack_require__) {
  98945. "use strict";
  98946. Object.defineProperty(exports, "__esModule", { value: true });
  98947. var babylonjs_1 = __webpack_require__(0);
  98948. var helper_1 = __webpack_require__(2);
  98949. /**
  98950. * This is a simple HTML mapper.
  98951. * This mapper parses a single HTML element and returns the configuration from its attributes.
  98952. * it parses numbers and boolean values to the corresponding variable types.
  98953. * The following HTML element:
  98954. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  98955. *
  98956. * {
  98957. * test: 1, //a number!
  98958. * randomFlag: boolean, //camelCase and boolean
  98959. * a: {
  98960. * string: {
  98961. * object: "test" //dot-separated object levels
  98962. * }
  98963. * }
  98964. * }
  98965. */
  98966. var HTMLMapper = /** @class */ (function () {
  98967. function HTMLMapper() {
  98968. }
  98969. /**
  98970. * Map a specific element and get configuration from it
  98971. * @param element the HTML element to analyze.
  98972. */
  98973. HTMLMapper.prototype.map = function (element) {
  98974. var config = {};
  98975. var _loop_1 = function (attrIdx) {
  98976. var attr = element.attributes.item(attrIdx);
  98977. if (!attr) {
  98978. return "continue";
  98979. }
  98980. // map "object.property" to the right configuration place.
  98981. var split = attr.nodeName.split('.');
  98982. split.reduce(function (currentConfig, key, idx) {
  98983. //convert html-style to json-style
  98984. var camelKey = helper_1.kebabToCamel(key);
  98985. if (idx === split.length - 1) {
  98986. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  98987. if (val === "true") {
  98988. val = true;
  98989. }
  98990. else if (val === "false") {
  98991. val = false;
  98992. }
  98993. else {
  98994. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  98995. if (isnum) {
  98996. var number = parseFloat(val);
  98997. if (!isNaN(number)) {
  98998. val = number;
  98999. }
  99000. }
  99001. }
  99002. currentConfig[camelKey] = val;
  99003. }
  99004. else {
  99005. currentConfig[camelKey] = currentConfig[camelKey] || {};
  99006. }
  99007. return currentConfig[camelKey];
  99008. }, config);
  99009. };
  99010. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  99011. _loop_1(attrIdx);
  99012. }
  99013. return config;
  99014. };
  99015. return HTMLMapper;
  99016. }());
  99017. /**
  99018. * A simple string-to-JSON mapper.
  99019. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  99020. */
  99021. var JSONMapper = /** @class */ (function () {
  99022. function JSONMapper() {
  99023. }
  99024. JSONMapper.prototype.map = function (rawSource) {
  99025. return JSON.parse(rawSource);
  99026. };
  99027. return JSONMapper;
  99028. }());
  99029. /**
  99030. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  99031. * DOM elements and attributes.
  99032. */
  99033. var DOMMapper = /** @class */ (function () {
  99034. function DOMMapper() {
  99035. }
  99036. /**
  99037. * The mapping function that will convert HTML data to a viewer configuration object
  99038. * @param baseElement the baseElement from which to start traversing
  99039. * @returns a ViewerCOnfiguration object from the provided HTML Element
  99040. */
  99041. DOMMapper.prototype.map = function (baseElement) {
  99042. var htmlMapper = new HTMLMapper();
  99043. var config = htmlMapper.map(baseElement);
  99044. var traverseChildren = function (element, partConfig) {
  99045. var children = element.children;
  99046. if (children.length) {
  99047. for (var i = 0; i < children.length; ++i) {
  99048. var item = children.item(i);
  99049. // use the HTML Mapper to read configuration from a single element
  99050. var configMapped = htmlMapper.map(item);
  99051. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  99052. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  99053. partConfig[key] = [];
  99054. }
  99055. else {
  99056. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  99057. partConfig.push(configMapped);
  99058. }
  99059. else if (partConfig[key]) {
  99060. //exists already! probably an array
  99061. element.setAttribute('array', 'true');
  99062. var oldItem = partConfig[key];
  99063. partConfig = [oldItem, configMapped];
  99064. }
  99065. else {
  99066. partConfig[key] = configMapped;
  99067. }
  99068. }
  99069. traverseChildren(item, partConfig[key] || configMapped);
  99070. }
  99071. }
  99072. return partConfig;
  99073. };
  99074. traverseChildren(baseElement, config);
  99075. return config;
  99076. };
  99077. return DOMMapper;
  99078. }());
  99079. /**
  99080. * The MapperManager manages the different implemented mappers.
  99081. * It allows the user to register new mappers as well and use them to parse their own configuration data
  99082. */
  99083. var MapperManager = /** @class */ (function () {
  99084. function MapperManager() {
  99085. this._mappers = {
  99086. "html": new HTMLMapper(),
  99087. "json": new JSONMapper(),
  99088. "dom": new DOMMapper()
  99089. };
  99090. }
  99091. /**
  99092. * Get a specific configuration mapper.
  99093. *
  99094. * @param type the name of the mapper to load
  99095. */
  99096. MapperManager.prototype.getMapper = function (type) {
  99097. if (!this._mappers[type]) {
  99098. babylonjs_1.Tools.Error("No mapper defined for " + type);
  99099. }
  99100. return this._mappers[type];
  99101. };
  99102. /**
  99103. * Use this functio to register your own configuration mapper.
  99104. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  99105. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  99106. * @param mapper The implemented mapper
  99107. */
  99108. MapperManager.prototype.registerMapper = function (type, mapper) {
  99109. this._mappers[type] = mapper;
  99110. };
  99111. /**
  99112. * Dispose the mapper manager and all of its mappers.
  99113. */
  99114. MapperManager.prototype.dispose = function () {
  99115. this._mappers = {};
  99116. };
  99117. /**
  99118. * The default mapper is the JSON mapper.
  99119. */
  99120. MapperManager.DefaultMapper = 'json';
  99121. return MapperManager;
  99122. }());
  99123. exports.MapperManager = MapperManager;
  99124. /**
  99125. * mapperManager is a singleton of the type MapperManager.
  99126. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  99127. * or indirectly with using BabylonViewer.disposeAll()
  99128. */
  99129. exports.mapperManager = new MapperManager();
  99130. /***/ }),
  99131. /* 4 */
  99132. /***/ (function(module, exports, __webpack_require__) {
  99133. "use strict";
  99134. Object.defineProperty(exports, "__esModule", { value: true });
  99135. var babylonjs_1 = __webpack_require__(0);
  99136. var modelAnimation_1 = __webpack_require__(30);
  99137. var deepmerge = __webpack_require__(1);
  99138. var helper_1 = __webpack_require__(2);
  99139. /**
  99140. * The current state of the model
  99141. */
  99142. var ModelState;
  99143. (function (ModelState) {
  99144. ModelState[ModelState["INIT"] = 0] = "INIT";
  99145. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  99146. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  99147. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  99148. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  99149. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  99150. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  99151. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  99152. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  99153. /**
  99154. * The viewer model is a container for all assets representing a sngle loaded model.
  99155. */
  99156. var ViewerModel = /** @class */ (function () {
  99157. function ViewerModel(_viewer, modelConfiguration) {
  99158. var _this = this;
  99159. this._viewer = _viewer;
  99160. /**
  99161. * the list of meshes that are a part of this model
  99162. */
  99163. this._meshes = [];
  99164. /**
  99165. * ParticleSystems connected to this model
  99166. */
  99167. this.particleSystems = [];
  99168. /**
  99169. * Skeletons defined in this model
  99170. */
  99171. this.skeletons = [];
  99172. this._loaderDone = false;
  99173. this._animatables = [];
  99174. this._frameRate = 60;
  99175. this._shadowsRenderedAfterLoad = false;
  99176. this.onLoadedObservable = new babylonjs_1.Observable();
  99177. this.onLoadErrorObservable = new babylonjs_1.Observable();
  99178. this.onLoadProgressObservable = new babylonjs_1.Observable();
  99179. this.onCompleteObservable = new babylonjs_1.Observable();
  99180. this.onAfterConfigure = new babylonjs_1.Observable();
  99181. this.state = ModelState.INIT;
  99182. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", this._viewer.sceneManager.scene);
  99183. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", this._viewer.sceneManager.scene);
  99184. this._pivotMesh.parent = this.rootMesh;
  99185. // rotate 180, gltf fun
  99186. this._pivotMesh.rotation.y += Math.PI;
  99187. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99188. this._animations = [];
  99189. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  99190. this._modelConfiguration = deepmerge(this._viewer.configuration.model || {}, modelConfiguration);
  99191. this._viewer.sceneManager.models.push(this);
  99192. this._viewer.onModelAddedObservable.notifyObservers(this);
  99193. if (this._modelConfiguration.entryAnimation) {
  99194. this.rootMesh.setEnabled(false);
  99195. }
  99196. this.onLoadedObservable.add(function () {
  99197. _this.updateConfiguration(_this._modelConfiguration);
  99198. _this._viewer.onModelLoadedObservable.notifyObservers(_this);
  99199. _this._initAnimations();
  99200. });
  99201. this.onCompleteObservable.add(function () {
  99202. _this.state = ModelState.COMPLETE;
  99203. });
  99204. }
  99205. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  99206. get: function () {
  99207. return this._shadowsRenderedAfterLoad;
  99208. },
  99209. set: function (rendered) {
  99210. if (!rendered) {
  99211. throw new Error("can only be enabled");
  99212. }
  99213. else {
  99214. this._shadowsRenderedAfterLoad = rendered;
  99215. }
  99216. },
  99217. enumerable: true,
  99218. configurable: true
  99219. });
  99220. Object.defineProperty(ViewerModel.prototype, "enabled", {
  99221. /**
  99222. * Is this model enabled?
  99223. */
  99224. get: function () {
  99225. return this.rootMesh.isEnabled();
  99226. },
  99227. /**
  99228. * Set whether this model is enabled or not.
  99229. */
  99230. set: function (enable) {
  99231. this.rootMesh.setEnabled(enable);
  99232. },
  99233. enumerable: true,
  99234. configurable: true
  99235. });
  99236. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  99237. set: function (done) {
  99238. this._loaderDone = done;
  99239. this._checkCompleteState();
  99240. },
  99241. enumerable: true,
  99242. configurable: true
  99243. });
  99244. ViewerModel.prototype._checkCompleteState = function () {
  99245. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  99246. this._modelComplete();
  99247. }
  99248. };
  99249. /**
  99250. * Get the viewer showing this model
  99251. */
  99252. ViewerModel.prototype.getViewer = function () {
  99253. return this._viewer;
  99254. };
  99255. /**
  99256. * Add a mesh to this model.
  99257. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  99258. *
  99259. * @param mesh the new mesh to add
  99260. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  99261. */
  99262. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  99263. if (!mesh.parent) {
  99264. mesh.parent = this._pivotMesh;
  99265. }
  99266. mesh.receiveShadows = !!this.configuration.receiveShadows;
  99267. this._meshes.push(mesh);
  99268. if (triggerLoaded) {
  99269. return this.onLoadedObservable.notifyObserversWithPromise(this);
  99270. }
  99271. };
  99272. Object.defineProperty(ViewerModel.prototype, "meshes", {
  99273. /**
  99274. * get the list of meshes (excluding the root mesh)
  99275. */
  99276. get: function () {
  99277. return this._meshes;
  99278. },
  99279. enumerable: true,
  99280. configurable: true
  99281. });
  99282. Object.defineProperty(ViewerModel.prototype, "configuration", {
  99283. /**
  99284. * Get the model's configuration
  99285. */
  99286. get: function () {
  99287. return this._modelConfiguration;
  99288. },
  99289. /**
  99290. * (Re-)set the model's entire configuration
  99291. * @param newConfiguration the new configuration to replace the new one
  99292. */
  99293. set: function (newConfiguration) {
  99294. this._modelConfiguration = newConfiguration;
  99295. this._configureModel();
  99296. },
  99297. enumerable: true,
  99298. configurable: true
  99299. });
  99300. /**
  99301. * Update the current configuration with new values.
  99302. * Configuration will not be overwritten, but merged with the new configuration.
  99303. * Priority is to the new configuration
  99304. * @param newConfiguration the configuration to be merged into the current configuration;
  99305. */
  99306. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  99307. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  99308. this._configureModel();
  99309. };
  99310. ViewerModel.prototype._initAnimations = function () {
  99311. var _this = this;
  99312. // check if this is not a gltf loader and init the animations
  99313. if (this.skeletons.length) {
  99314. this.skeletons.forEach(function (skeleton, idx) {
  99315. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.sceneManager.scene);
  99316. skeleton.getAnimatables().forEach(function (a) {
  99317. if (a.animations[0]) {
  99318. ag.addTargetedAnimation(a.animations[0], a);
  99319. }
  99320. });
  99321. _this.addAnimationGroup(ag);
  99322. });
  99323. }
  99324. var completeCallback = function () {
  99325. };
  99326. if (this._modelConfiguration.animation) {
  99327. if (this._modelConfiguration.animation.playOnce) {
  99328. this._animations.forEach(function (a) {
  99329. a.playMode = 0 /* ONCE */;
  99330. });
  99331. }
  99332. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  99333. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  99334. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  99335. completeCallback = function () {
  99336. _this.playAnimation(animationName_1);
  99337. };
  99338. }
  99339. }
  99340. this._enterScene(completeCallback);
  99341. };
  99342. /**
  99343. * Animates the model from the current position to the default position
  99344. * @param completeCallback A function to call when the animation has completed
  99345. */
  99346. ViewerModel.prototype._enterScene = function (completeCallback) {
  99347. var _this = this;
  99348. var callback = function () {
  99349. _this.state = ModelState.ENTRYDONE;
  99350. _this._viewer.sceneManager.animationBlendingEnabled = true;
  99351. _this._checkCompleteState();
  99352. if (completeCallback)
  99353. completeCallback();
  99354. };
  99355. if (!this._entryAnimation) {
  99356. callback();
  99357. return;
  99358. }
  99359. this.rootMesh.setEnabled(true);
  99360. // disable blending for the sake of the entry animation;
  99361. this._viewer.sceneManager.animationBlendingEnabled = false;
  99362. this._applyAnimation(this._entryAnimation, true, callback);
  99363. };
  99364. /**
  99365. * Animates the model from the current position to the exit-screen position
  99366. * @param completeCallback A function to call when the animation has completed
  99367. */
  99368. ViewerModel.prototype._exitScene = function (completeCallback) {
  99369. if (!this._exitAnimation) {
  99370. completeCallback();
  99371. return;
  99372. }
  99373. this._applyAnimation(this._exitAnimation, false, completeCallback);
  99374. };
  99375. ViewerModel.prototype._modelComplete = function () {
  99376. var _this = this;
  99377. //reapply material defines to be sure:
  99378. var meshes = this._pivotMesh.getChildMeshes(false);
  99379. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  99380. _this._applyModelMaterialConfiguration(mesh.material);
  99381. });
  99382. this.state = ModelState.COMPLETE;
  99383. this.onCompleteObservable.notifyObservers(this);
  99384. };
  99385. /**
  99386. * Add a new animation group to this model.
  99387. * @param animationGroup the new animation group to be added
  99388. */
  99389. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  99390. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  99391. };
  99392. /**
  99393. * Get the ModelAnimation array
  99394. */
  99395. ViewerModel.prototype.getAnimations = function () {
  99396. return this._animations;
  99397. };
  99398. /**
  99399. * Get the animations' names. Using the names you can play a specific animation.
  99400. */
  99401. ViewerModel.prototype.getAnimationNames = function () {
  99402. return this._animations.map(function (a) { return a.name; });
  99403. };
  99404. /**
  99405. * Get an animation by the provided name. Used mainly when playing n animation.
  99406. * @param name the name of the animation to find
  99407. */
  99408. ViewerModel.prototype._getAnimationByName = function (name) {
  99409. // can't use .find, noe available on IE
  99410. var filtered = this._animations.filter(function (a) { return a.name === name; });
  99411. // what the next line means - if two animations have the same name, they will not be returned!
  99412. if (filtered.length === 1) {
  99413. return filtered[0];
  99414. }
  99415. else {
  99416. return null;
  99417. }
  99418. };
  99419. /**
  99420. * Choose an initialized animation using its name and start playing it
  99421. * @param name the name of the animation to play
  99422. * @returns The model aniamtion to be played.
  99423. */
  99424. ViewerModel.prototype.playAnimation = function (name) {
  99425. var animation = this.setCurrentAnimationByName(name);
  99426. if (animation) {
  99427. animation.start();
  99428. }
  99429. return animation;
  99430. };
  99431. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  99432. var animation = this._getAnimationByName(name);
  99433. if (animation) {
  99434. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  99435. this.currentAnimation.stop();
  99436. }
  99437. this.currentAnimation = animation;
  99438. return animation;
  99439. }
  99440. else {
  99441. throw new Error("animation not found - " + name);
  99442. }
  99443. };
  99444. ViewerModel.prototype._configureModel = function () {
  99445. var _this = this;
  99446. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  99447. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  99448. var updateMeshesWithNoParent = function (variable, value, param) {
  99449. meshesWithNoParent.forEach(function (mesh) {
  99450. if (param) {
  99451. mesh[variable][param] = value;
  99452. }
  99453. else {
  99454. mesh[variable] = value;
  99455. }
  99456. });
  99457. };
  99458. var updateXYZ = function (variable, configValues) {
  99459. if (configValues.x !== undefined) {
  99460. updateMeshesWithNoParent(variable, configValues.x, 'x');
  99461. }
  99462. if (configValues.y !== undefined) {
  99463. updateMeshesWithNoParent(variable, configValues.y, 'y');
  99464. }
  99465. if (configValues.z !== undefined) {
  99466. updateMeshesWithNoParent(variable, configValues.z, 'z');
  99467. }
  99468. if (configValues.w !== undefined) {
  99469. updateMeshesWithNoParent(variable, configValues.w, 'w');
  99470. }
  99471. };
  99472. if (this._modelConfiguration.normalize) {
  99473. var center = false;
  99474. var unitSize = false;
  99475. var parentIndex = void 0;
  99476. if (this._modelConfiguration.normalize === true) {
  99477. center = true;
  99478. unitSize = true;
  99479. }
  99480. else {
  99481. center = !!this._modelConfiguration.normalize.center;
  99482. unitSize = !!this._modelConfiguration.normalize.unitSize;
  99483. parentIndex = this._modelConfiguration.normalize.parentIndex;
  99484. }
  99485. var meshesToNormalize = [];
  99486. if (parentIndex !== undefined) {
  99487. meshesToNormalize.push(this._meshes[parentIndex]);
  99488. }
  99489. else {
  99490. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  99491. }
  99492. if (unitSize) {
  99493. meshesToNormalize.forEach(function (mesh) {
  99494. mesh.normalizeToUnitCube(true);
  99495. mesh.computeWorldMatrix(true);
  99496. });
  99497. }
  99498. if (center) {
  99499. meshesToNormalize.forEach(function (mesh) {
  99500. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  99501. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  99502. var halfSizeVec = sizeVec.scale(0.5);
  99503. var center = boundingInfo.min.add(halfSizeVec);
  99504. mesh.position = center.scale(-1);
  99505. mesh.position.y += halfSizeVec.y;
  99506. // Recompute Info.
  99507. mesh.computeWorldMatrix(true);
  99508. });
  99509. }
  99510. }
  99511. else {
  99512. // if centered, should be done here
  99513. }
  99514. // position?
  99515. if (this._modelConfiguration.position) {
  99516. updateXYZ('position', this._modelConfiguration.position);
  99517. }
  99518. if (this._modelConfiguration.rotation) {
  99519. //quaternion?
  99520. if (this._modelConfiguration.rotation.w) {
  99521. meshesWithNoParent.forEach(function (mesh) {
  99522. if (!mesh.rotationQuaternion) {
  99523. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  99524. }
  99525. });
  99526. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  99527. }
  99528. else {
  99529. updateXYZ('rotation', this._modelConfiguration.rotation);
  99530. }
  99531. }
  99532. if (this._modelConfiguration.rotationOffsetAxis) {
  99533. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  99534. meshesWithNoParent.forEach(function (m) {
  99535. if (_this._modelConfiguration.rotationOffsetAngle) {
  99536. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  99537. }
  99538. });
  99539. }
  99540. if (this._modelConfiguration.scaling) {
  99541. updateXYZ('scaling', this._modelConfiguration.scaling);
  99542. }
  99543. if (this._modelConfiguration.castShadow) {
  99544. this._meshes.forEach(function (mesh) {
  99545. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  99546. });
  99547. }
  99548. var meshes = this._pivotMesh.getChildMeshes(false);
  99549. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  99550. _this._applyModelMaterialConfiguration(mesh.material);
  99551. });
  99552. if (this._modelConfiguration.entryAnimation) {
  99553. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  99554. }
  99555. if (this._modelConfiguration.exitAnimation) {
  99556. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  99557. }
  99558. this.onAfterConfigure.notifyObservers(this);
  99559. };
  99560. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  99561. var anim = {
  99562. time: 0.5
  99563. };
  99564. if (animConfig.scaling) {
  99565. anim.scaling = babylonjs_1.Vector3.Zero();
  99566. }
  99567. if (animConfig.easingFunction !== undefined) {
  99568. anim.easingFunction = animConfig.easingFunction;
  99569. }
  99570. if (animConfig.easingMode !== undefined) {
  99571. anim.easingMode = animConfig.easingMode;
  99572. }
  99573. helper_1.extendClassWithConfig(anim, animConfig);
  99574. return anim;
  99575. };
  99576. /**
  99577. * Apply a material configuration to a material
  99578. * @param material Material to apply configuration to
  99579. */
  99580. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  99581. if (!this._modelConfiguration.material)
  99582. return;
  99583. helper_1.extendClassWithConfig(material, this._modelConfiguration.material);
  99584. if (material instanceof babylonjs_1.PBRMaterial) {
  99585. if (this._modelConfiguration.material.directIntensity !== undefined) {
  99586. material.directIntensity = this._modelConfiguration.material.directIntensity;
  99587. }
  99588. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  99589. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  99590. }
  99591. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  99592. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  99593. }
  99594. if (this._modelConfiguration.material.directEnabled !== undefined) {
  99595. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  99596. }
  99597. if (this._viewer.sceneManager.reflectionColor) {
  99598. material.reflectionColor = this._viewer.sceneManager.reflectionColor;
  99599. }
  99600. }
  99601. else if (material instanceof babylonjs_1.MultiMaterial) {
  99602. for (var i = 0; i < material.subMaterials.length; i++) {
  99603. var subMaterial = material.subMaterials[i];
  99604. if (subMaterial) {
  99605. this._applyModelMaterialConfiguration(subMaterial);
  99606. }
  99607. }
  99608. }
  99609. };
  99610. /**
  99611. * Start entry/exit animation given an animation configuration
  99612. * @param animationConfiguration Entry/Exit animation configuration
  99613. * @param isEntry Pass true if the animation is an entry animation
  99614. * @param completeCallback Callback to execute when the animation completes
  99615. */
  99616. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  99617. var animations = [];
  99618. //scale
  99619. if (animationConfiguration.scaling) {
  99620. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  99621. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  99622. if (!scaleStart.equals(scaleEnd)) {
  99623. this.rootMesh.scaling = scaleStart;
  99624. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  99625. animations.push(this._scaleTransition);
  99626. }
  99627. }
  99628. //Start the animation(s)
  99629. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  99630. completeCallback(); });
  99631. };
  99632. /**
  99633. * Begin @animations with the specified @easingFunction
  99634. * @param animations The BABYLON Animations to begin
  99635. * @param duration of transition, in seconds
  99636. * @param easingFunction An easing function to apply
  99637. * @param easingMode A easing mode to apply to the easingFunction
  99638. * @param onAnimationEnd Call back trigger at the end of the animation.
  99639. */
  99640. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  99641. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  99642. if (easingFunction) {
  99643. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  99644. var animation = animations_1[_i];
  99645. easingFunction.setEasingMode(easingMode);
  99646. animation.setEasingFunction(easingFunction);
  99647. }
  99648. }
  99649. //Stop any current animations before starting the new one - merging not yet supported.
  99650. this.stopAllAnimations();
  99651. this.rootMesh.animations = animations;
  99652. if (this._viewer.sceneManager.scene.beginAnimation) {
  99653. var animatable = this._viewer.sceneManager.scene.beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  99654. if (onAnimationEnd) {
  99655. onAnimationEnd();
  99656. }
  99657. });
  99658. this._animatables.push(animatable);
  99659. }
  99660. };
  99661. /**
  99662. * Sets key values on an Animation from first to last frame.
  99663. * @param animation The Babylon animation object to set keys on
  99664. * @param startValue The value of the first key
  99665. * @param endValue The value of the last key
  99666. * @param duration The duration of the animation, used to determine the end frame
  99667. */
  99668. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  99669. animation.setKeys([
  99670. {
  99671. frame: 0,
  99672. value: startValue
  99673. },
  99674. {
  99675. frame: this._frameRate * duration,
  99676. value: endValue
  99677. }
  99678. ]);
  99679. };
  99680. /**
  99681. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  99682. * @param easingFunctionID The enum of the easing funtion to create
  99683. * @return The newly created Babylon easing function object
  99684. */
  99685. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  99686. var easingFunction;
  99687. switch (easingFunctionID) {
  99688. case 1 /* CircleEase */:
  99689. easingFunction = new babylonjs_1.CircleEase();
  99690. break;
  99691. case 2 /* BackEase */:
  99692. easingFunction = new babylonjs_1.BackEase(0.3);
  99693. break;
  99694. case 3 /* BounceEase */:
  99695. easingFunction = new babylonjs_1.BounceEase();
  99696. break;
  99697. case 4 /* CubicEase */:
  99698. easingFunction = new babylonjs_1.CubicEase();
  99699. break;
  99700. case 5 /* ElasticEase */:
  99701. easingFunction = new babylonjs_1.ElasticEase();
  99702. break;
  99703. case 6 /* ExponentialEase */:
  99704. easingFunction = new babylonjs_1.ExponentialEase();
  99705. break;
  99706. case 7 /* PowerEase */:
  99707. easingFunction = new babylonjs_1.PowerEase();
  99708. break;
  99709. case 8 /* QuadraticEase */:
  99710. easingFunction = new babylonjs_1.QuadraticEase();
  99711. break;
  99712. case 9 /* QuarticEase */:
  99713. easingFunction = new babylonjs_1.QuarticEase();
  99714. break;
  99715. case 10 /* QuinticEase */:
  99716. easingFunction = new babylonjs_1.QuinticEase();
  99717. break;
  99718. case 11 /* SineEase */:
  99719. easingFunction = new babylonjs_1.SineEase();
  99720. break;
  99721. default:
  99722. babylonjs_1.Tools.Log("No ease function found");
  99723. break;
  99724. }
  99725. return easingFunction;
  99726. };
  99727. /**
  99728. * Stops and removes all animations that have been applied to the model
  99729. */
  99730. ViewerModel.prototype.stopAllAnimations = function () {
  99731. if (this.rootMesh) {
  99732. this.rootMesh.animations = [];
  99733. }
  99734. if (this.currentAnimation) {
  99735. this.currentAnimation.stop();
  99736. }
  99737. while (this._animatables.length) {
  99738. this._animatables[0].onAnimationEnd = null;
  99739. this._animatables[0].stop();
  99740. this._animatables.shift();
  99741. }
  99742. };
  99743. /**
  99744. * Will remove this model from the viewer (but NOT dispose it).
  99745. */
  99746. ViewerModel.prototype.remove = function () {
  99747. this.stopAllAnimations();
  99748. this._viewer.sceneManager.models.splice(this._viewer.sceneManager.models.indexOf(this), 1);
  99749. // hide it
  99750. this.rootMesh.isVisible = false;
  99751. this._viewer.onModelRemovedObservable.notifyObservers(this);
  99752. };
  99753. /**
  99754. * Dispose this model, including all of its associated assets.
  99755. */
  99756. ViewerModel.prototype.dispose = function () {
  99757. this.remove();
  99758. this.onAfterConfigure.clear();
  99759. this.onLoadedObservable.clear();
  99760. this.onLoadErrorObservable.clear();
  99761. this.onLoadProgressObservable.clear();
  99762. if (this.loader && this.loader.name === "gltf") {
  99763. this.loader.dispose();
  99764. }
  99765. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  99766. this.particleSystems.length = 0;
  99767. this.skeletons.forEach(function (s) { return s.dispose(); });
  99768. this.skeletons.length = 0;
  99769. this._animations.forEach(function (ag) { return ag.dispose(); });
  99770. this._animations.length = 0;
  99771. this.rootMesh.dispose(false, true);
  99772. };
  99773. return ViewerModel;
  99774. }());
  99775. exports.ViewerModel = ViewerModel;
  99776. /***/ }),
  99777. /* 5 */
  99778. /***/ (function(module, exports, __webpack_require__) {
  99779. "use strict";
  99780. Object.defineProperty(exports, "__esModule", { value: true });
  99781. var babylonjs_1 = __webpack_require__(0);
  99782. /**
  99783. * Receives Telemetry events and raises events to the API
  99784. */
  99785. var TelemetryManager = /** @class */ (function () {
  99786. function TelemetryManager() {
  99787. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  99788. this._event = this._eventEnabled;
  99789. }
  99790. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  99791. /**
  99792. * Receives a telemetry event
  99793. * @param event The name of the Telemetry event
  99794. * @param details An additional value, or an object containing a list of property/value pairs
  99795. */
  99796. get: function () {
  99797. return this._event;
  99798. },
  99799. enumerable: true,
  99800. configurable: true
  99801. });
  99802. /**
  99803. * Log a Telemetry event for errors raised on the WebGL context.
  99804. * @param engine The Babylon engine with the WebGL context.
  99805. */
  99806. TelemetryManager.prototype.flushWebGLErrors = function (viewer) {
  99807. var engine = viewer.engine;
  99808. if (!engine) {
  99809. return;
  99810. }
  99811. var logErrors = true;
  99812. while (logErrors) {
  99813. var gl = engine._gl;
  99814. if (gl && gl.getError) {
  99815. var error = gl.getError();
  99816. if (error === gl.NO_ERROR) {
  99817. logErrors = false;
  99818. }
  99819. else {
  99820. this.broadcast("WebGL Error", viewer, { error: error });
  99821. }
  99822. }
  99823. else {
  99824. logErrors = false;
  99825. }
  99826. }
  99827. };
  99828. Object.defineProperty(TelemetryManager.prototype, "enable", {
  99829. /**
  99830. * Enable or disable telemetry events
  99831. * @param enabled Boolan, true if events are enabled
  99832. */
  99833. set: function (enabled) {
  99834. if (enabled) {
  99835. this._event = this._eventEnabled;
  99836. }
  99837. else {
  99838. this._event = this._eventDisabled;
  99839. }
  99840. },
  99841. enumerable: true,
  99842. configurable: true
  99843. });
  99844. /**
  99845. * Called on event when disabled, typically do nothing here
  99846. */
  99847. TelemetryManager.prototype._eventDisabled = function () {
  99848. // nothing to do
  99849. };
  99850. /**
  99851. * Called on event when enabled
  99852. * @param event - The name of the Telemetry event
  99853. * @param details An additional value, or an object containing a list of property/value pairs
  99854. */
  99855. TelemetryManager.prototype._eventEnabled = function (event, viewer, details) {
  99856. var telemetryData = {
  99857. viewer: viewer,
  99858. event: event,
  99859. session: this.session,
  99860. date: new Date(),
  99861. now: window.performance ? window.performance.now() : Date.now(),
  99862. detail: null
  99863. };
  99864. if (typeof details === "object") {
  99865. for (var attr in details) {
  99866. if (details.hasOwnProperty(attr)) {
  99867. telemetryData[attr] = details[attr];
  99868. }
  99869. }
  99870. }
  99871. else if (details) {
  99872. telemetryData.detail = details;
  99873. }
  99874. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  99875. };
  99876. Object.defineProperty(TelemetryManager.prototype, "session", {
  99877. /**
  99878. * Returns the current session ID or creates one if it doesn't exixt
  99879. * @return The current session ID
  99880. */
  99881. get: function () {
  99882. if (!this._currentSessionId) {
  99883. //String + Timestamp + Random Integer
  99884. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  99885. }
  99886. return this._currentSessionId;
  99887. },
  99888. enumerable: true,
  99889. configurable: true
  99890. });
  99891. /**
  99892. * Disposes the telemetry manager
  99893. */
  99894. TelemetryManager.prototype.dispose = function () {
  99895. this.onEventBroadcastedObservable.clear();
  99896. delete this.onEventBroadcastedObservable;
  99897. };
  99898. return TelemetryManager;
  99899. }());
  99900. exports.TelemetryManager = TelemetryManager;
  99901. exports.telemetryManager = new TelemetryManager();
  99902. /***/ }),
  99903. /* 6 */
  99904. /***/ (function(module, exports, __webpack_require__) {
  99905. "use strict";
  99906. function __export(m) {
  99907. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  99908. }
  99909. Object.defineProperty(exports, "__esModule", { value: true });
  99910. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  99911. var mappers_1 = __webpack_require__(3);
  99912. exports.mapperManager = mappers_1.mapperManager;
  99913. var globals_1 = __webpack_require__(7);
  99914. exports.viewerGlobals = globals_1.viewerGlobals;
  99915. var viewerManager_1 = __webpack_require__(8);
  99916. exports.viewerManager = viewerManager_1.viewerManager;
  99917. var defaultViewer_1 = __webpack_require__(9);
  99918. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  99919. var viewer_1 = __webpack_require__(10);
  99920. exports.AbstractViewer = viewer_1.AbstractViewer;
  99921. var telemetryManager_1 = __webpack_require__(5);
  99922. exports.telemetryManager = telemetryManager_1.telemetryManager;
  99923. var modelLoader_1 = __webpack_require__(22);
  99924. exports.ModelLoader = modelLoader_1.ModelLoader;
  99925. var viewerModel_1 = __webpack_require__(4);
  99926. exports.ViewerModel = viewerModel_1.ViewerModel;
  99927. exports.ModelState = viewerModel_1.ModelState;
  99928. /**
  99929. * BabylonJS Viewer
  99930. *
  99931. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  99932. */
  99933. var BABYLON = __webpack_require__(0);
  99934. exports.BABYLON = BABYLON;
  99935. // load needed modules.
  99936. __webpack_require__(23);
  99937. __webpack_require__(56);
  99938. var initializer_1 = __webpack_require__(57);
  99939. exports.InitTags = initializer_1.InitTags;
  99940. // promise polyfill, if needed!
  99941. BABYLON.PromisePolyfill.Apply();
  99942. initializer_1.initListeners();
  99943. //deprectaed, here for backwards compatibility
  99944. var disableInit = globals_1.viewerGlobals.disableInit;
  99945. exports.disableInit = disableInit;
  99946. /**
  99947. * Dispose all viewers currently registered
  99948. */
  99949. function disposeAll() {
  99950. viewerManager_1.viewerManager.dispose();
  99951. mappers_1.mapperManager.dispose();
  99952. telemetryManager_1.telemetryManager.dispose();
  99953. }
  99954. exports.disposeAll = disposeAll;
  99955. var Version = BABYLON.Engine.Version;
  99956. exports.Version = Version;
  99957. console.log("Babylon.js viewer (v" + Version + ")");
  99958. // export publicliy all configuration interfaces
  99959. __export(__webpack_require__(21));
  99960. /***/ }),
  99961. /* 7 */
  99962. /***/ (function(module, exports, __webpack_require__) {
  99963. "use strict";
  99964. Object.defineProperty(exports, "__esModule", { value: true });
  99965. var ViewerGlobals = /** @class */ (function () {
  99966. function ViewerGlobals() {
  99967. this.disableInit = false;
  99968. this.disableWebGL2Support = false;
  99969. }
  99970. return ViewerGlobals;
  99971. }());
  99972. exports.ViewerGlobals = ViewerGlobals;
  99973. exports.viewerGlobals = new ViewerGlobals();
  99974. /***/ }),
  99975. /* 8 */
  99976. /***/ (function(module, exports, __webpack_require__) {
  99977. "use strict";
  99978. Object.defineProperty(exports, "__esModule", { value: true });
  99979. var babylonjs_1 = __webpack_require__(0);
  99980. /**
  99981. * The viewer manager is the container for all viewers currently registered on this page.
  99982. * It is possible to have more than one viewer on a single page.
  99983. */
  99984. var ViewerManager = /** @class */ (function () {
  99985. function ViewerManager() {
  99986. this._viewers = {};
  99987. this.onViewerAddedObservable = new babylonjs_1.Observable();
  99988. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  99989. }
  99990. /**
  99991. * Adding a new viewer to the viewer manager and start tracking it.
  99992. * @param viewer the viewer to add
  99993. */
  99994. ViewerManager.prototype.addViewer = function (viewer) {
  99995. this._viewers[viewer.getBaseId()] = viewer;
  99996. this._onViewerAdded(viewer);
  99997. };
  99998. /**
  99999. * remove a viewer from the viewer manager
  100000. * @param viewer the viewer to remove
  100001. */
  100002. ViewerManager.prototype.removeViewer = function (viewer) {
  100003. var id = viewer.getBaseId();
  100004. delete this._viewers[id];
  100005. this.onViewerRemovedObservable.notifyObservers(id);
  100006. };
  100007. /**
  100008. * 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)
  100009. * @param id the id of the HTMl element (or the viewer's, if none provided)
  100010. */
  100011. ViewerManager.prototype.getViewerById = function (id) {
  100012. return this._viewers[id];
  100013. };
  100014. /**
  100015. * Get a viewer using a container element
  100016. * @param element the HTML element to search viewers associated with
  100017. */
  100018. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  100019. for (var id in this._viewers) {
  100020. if (this._viewers[id].containerElement === element) {
  100021. return this.getViewerById(id);
  100022. }
  100023. }
  100024. };
  100025. /**
  100026. * Get a promise that will fullfil when this viewer was initialized.
  100027. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  100028. * you will get the viewer after everything was already configured.
  100029. * @param id the viewer id to find
  100030. */
  100031. ViewerManager.prototype.getViewerPromiseById = function (id) {
  100032. var _this = this;
  100033. return new Promise(function (resolve, reject) {
  100034. var localViewer = _this.getViewerById(id);
  100035. if (localViewer) {
  100036. return resolve(localViewer);
  100037. }
  100038. var viewerFunction = function (viewer) {
  100039. if (viewer.getBaseId() === id) {
  100040. resolve(viewer);
  100041. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  100042. }
  100043. };
  100044. _this.onViewerAddedObservable.add(viewerFunction);
  100045. });
  100046. };
  100047. ViewerManager.prototype._onViewerAdded = function (viewer) {
  100048. this.onViewerAdded && this.onViewerAdded(viewer);
  100049. this.onViewerAddedObservable.notifyObservers(viewer);
  100050. };
  100051. /**
  100052. * dispose the manager and all of its associated viewers
  100053. */
  100054. ViewerManager.prototype.dispose = function () {
  100055. delete this._onViewerAdded;
  100056. for (var id in this._viewers) {
  100057. this._viewers[id].dispose();
  100058. }
  100059. this.onViewerAddedObservable.clear();
  100060. this.onViewerRemovedObservable.clear();
  100061. };
  100062. return ViewerManager;
  100063. }());
  100064. exports.ViewerManager = ViewerManager;
  100065. exports.viewerManager = new ViewerManager();
  100066. /***/ }),
  100067. /* 9 */
  100068. /***/ (function(module, exports, __webpack_require__) {
  100069. "use strict";
  100070. var __extends = (this && this.__extends) || (function () {
  100071. var extendStatics = Object.setPrototypeOf ||
  100072. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  100073. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  100074. return function (d, b) {
  100075. extendStatics(d, b);
  100076. function __() { this.constructor = d; }
  100077. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  100078. };
  100079. })();
  100080. Object.defineProperty(exports, "__esModule", { value: true });
  100081. var viewer_1 = __webpack_require__(10);
  100082. var babylonjs_1 = __webpack_require__(0);
  100083. /**
  100084. * The Default viewer is the default implementation of the AbstractViewer.
  100085. * It uses the templating system to render a new canvas and controls.
  100086. */
  100087. var DefaultViewer = /** @class */ (function (_super) {
  100088. __extends(DefaultViewer, _super);
  100089. /**
  100090. * Create a new default viewer
  100091. * @param containerElement the element in which the templates will be rendered
  100092. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  100093. */
  100094. function DefaultViewer(containerElement, initialConfiguration) {
  100095. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  100096. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  100097. _this.containerElement = containerElement;
  100098. _this._handlePointerDown = function (event) {
  100099. var pointerDown = event.event;
  100100. if (pointerDown.button !== 0)
  100101. return;
  100102. var element = event.event.target;
  100103. if (!element) {
  100104. return;
  100105. }
  100106. var parentClasses = element.parentElement.classList;
  100107. switch (element.id) {
  100108. case "speed-button":
  100109. case "types-button":
  100110. if (parentClasses.contains("open")) {
  100111. parentClasses.remove("open");
  100112. }
  100113. else {
  100114. parentClasses.add("open");
  100115. }
  100116. break;
  100117. case "play-pause-button":
  100118. _this._togglePlayPause();
  100119. break;
  100120. case "label-option-button":
  100121. var label = element.dataset["value"];
  100122. if (label) {
  100123. _this._updateAnimationType(label);
  100124. }
  100125. break;
  100126. case "speed-option-button":
  100127. if (!_this._currentAnimation) {
  100128. return;
  100129. }
  100130. var speed = element.dataset["value"];
  100131. if (speed)
  100132. _this._updateAnimationSpeed(speed);
  100133. break;
  100134. case "progress-wrapper":
  100135. _this._resumePlay = !_this._isAnimationPaused;
  100136. if (_this._resumePlay) {
  100137. _this._togglePlayPause(true);
  100138. }
  100139. break;
  100140. case "fullscreen-button":
  100141. _this.toggleFullscreen();
  100142. default:
  100143. return;
  100144. }
  100145. };
  100146. /**
  100147. * Plays or Pauses animation
  100148. */
  100149. _this._togglePlayPause = function (noUiUpdate) {
  100150. if (!_this._currentAnimation) {
  100151. return;
  100152. }
  100153. if (_this._isAnimationPaused) {
  100154. _this._currentAnimation.restart();
  100155. }
  100156. else {
  100157. _this._currentAnimation.pause();
  100158. }
  100159. _this._isAnimationPaused = !_this._isAnimationPaused;
  100160. if (noUiUpdate)
  100161. return;
  100162. var navbar = _this.templateManager.getTemplate('navBar');
  100163. if (!navbar)
  100164. return;
  100165. navbar.updateParams({
  100166. paused: _this._isAnimationPaused,
  100167. });
  100168. };
  100169. /**
  100170. * Control progress bar position based on animation current frame
  100171. */
  100172. _this._updateProgressBar = function () {
  100173. var navbar = _this.templateManager.getTemplate('navBar');
  100174. if (!navbar)
  100175. return;
  100176. var progressSlider = navbar.parent.querySelector("input#progress-wrapper");
  100177. if (progressSlider && _this._currentAnimation) {
  100178. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  100179. var currentValue = progressSlider.valueAsNumber;
  100180. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  100181. progressSlider.value = '' + progress;
  100182. }
  100183. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  100184. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  100185. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  100186. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  100187. }
  100188. }
  100189. else {
  100190. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  100191. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  100192. _this._oldIdleRotationValue = 0;
  100193. }
  100194. }
  100195. }
  100196. };
  100197. /**
  100198. * Update Current Animation Speed
  100199. */
  100200. _this._updateAnimationSpeed = function (speed, paramsObject) {
  100201. var navbar = _this.templateManager.getTemplate('navBar');
  100202. if (!navbar)
  100203. return;
  100204. if (speed && _this._currentAnimation) {
  100205. _this._currentAnimation.speedRatio = parseFloat(speed);
  100206. if (!_this._isAnimationPaused) {
  100207. _this._currentAnimation.restart();
  100208. }
  100209. if (paramsObject) {
  100210. paramsObject.selectedSpeed = speed + "x";
  100211. }
  100212. else {
  100213. navbar.updateParams({
  100214. selectedSpeed: speed + "x",
  100215. });
  100216. }
  100217. }
  100218. };
  100219. /**
  100220. * Update Current Animation Type
  100221. */
  100222. _this._updateAnimationType = function (label, paramsObject) {
  100223. var navbar = _this.templateManager.getTemplate('navBar');
  100224. if (!navbar)
  100225. return;
  100226. if (label) {
  100227. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  100228. }
  100229. if (paramsObject) {
  100230. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  100231. paramsObject.selectedAnimationName = label;
  100232. }
  100233. else {
  100234. navbar.updateParams({
  100235. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  100236. selectedAnimationName: label
  100237. });
  100238. }
  100239. _this._updateAnimationSpeed("1.0", paramsObject);
  100240. };
  100241. /**
  100242. * Toggle fullscreen of the entire viewer
  100243. */
  100244. _this.toggleFullscreen = function () {
  100245. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  100246. var viewerElement = viewerTemplate && viewerTemplate.parent;
  100247. if (viewerElement) {
  100248. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  100249. if (!fullscreenElement) {
  100250. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  100251. requestFullScreen.call(viewerElement);
  100252. }
  100253. else {
  100254. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  100255. exitFullscreen.call(document);
  100256. }
  100257. }
  100258. };
  100259. _this._onModelLoaded = function (model) {
  100260. _this._configureTemplate(model);
  100261. // with a short timeout, making sure everything is there already.
  100262. var hideLoadingDelay = 20;
  100263. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  100264. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  100265. }
  100266. setTimeout(function () {
  100267. _this.sceneManager.scene.executeWhenReady(function () {
  100268. _this.hideLoadingScreen();
  100269. });
  100270. }, hideLoadingDelay);
  100271. return;
  100272. };
  100273. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  100274. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  100275. _this._configureLights(data.newConfiguration, data.model);
  100276. });
  100277. return _this;
  100278. }
  100279. /**
  100280. * This will be executed when the templates initialize.
  100281. */
  100282. DefaultViewer.prototype._onTemplatesLoaded = function () {
  100283. var _this = this;
  100284. this.showLoadingScreen();
  100285. // navbar
  100286. this._initNavbar();
  100287. // close overlay button
  100288. var closeButton = document.getElementById('close-button');
  100289. if (closeButton) {
  100290. closeButton.addEventListener('pointerdown', function () {
  100291. _this.hideOverlayScreen();
  100292. });
  100293. }
  100294. if (this.configuration.templates && this.configuration.templates.viewer) {
  100295. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  100296. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  100297. }, function () {
  100298. }, function () {
  100299. }, function () {
  100300. }, function () {
  100301. }, function (file) {
  100302. _this.loadModel(file);
  100303. }, function () {
  100304. });
  100305. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  100306. }
  100307. }
  100308. return _super.prototype._onTemplatesLoaded.call(this);
  100309. };
  100310. DefaultViewer.prototype._dropped = function (evt) {
  100311. };
  100312. DefaultViewer.prototype._initNavbar = function () {
  100313. var _this = this;
  100314. var navbar = this.templateManager.getTemplate('navBar');
  100315. if (navbar) {
  100316. this.onFrameRenderedObservable.add(this._updateProgressBar);
  100317. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  100318. // an example how to trigger the help button. publiclly available
  100319. this.templateManager.eventManager.registerCallback("navBar", function () {
  100320. // do your thing
  100321. }, "pointerdown", "#help-button");
  100322. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  100323. var evt = event.event;
  100324. var element = (evt.target);
  100325. if (!_this._currentAnimation)
  100326. return;
  100327. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  100328. if (isNaN(gotoFrame))
  100329. return;
  100330. _this._currentAnimation.goToFrame(gotoFrame);
  100331. }, "input");
  100332. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  100333. if (_this._resumePlay) {
  100334. _this._togglePlayPause(true);
  100335. }
  100336. _this._resumePlay = false;
  100337. }, "pointerup", "#progress-wrapper");
  100338. }
  100339. };
  100340. /**
  100341. * Preparing the container element to present the viewer
  100342. */
  100343. DefaultViewer.prototype._prepareContainerElement = function () {
  100344. this.containerElement.style.position = 'relative';
  100345. this.containerElement.style.height = '100%';
  100346. this.containerElement.style.display = 'flex';
  100347. };
  100348. /**
  100349. * This function will configure the templates and update them after a model was loaded
  100350. * It is mainly responsible to changing the title and subtitle etc'.
  100351. * @param model the model to be used to configure the templates by
  100352. */
  100353. DefaultViewer.prototype._configureTemplate = function (model) {
  100354. var navbar = this.templateManager.getTemplate('navBar');
  100355. if (!navbar)
  100356. return;
  100357. var newParams = {};
  100358. var animationNames = model.getAnimationNames();
  100359. if (animationNames.length >= 1) {
  100360. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  100361. this._animationList = animationNames;
  100362. newParams.animations = this._animationList;
  100363. newParams.paused = this._isAnimationPaused;
  100364. var animationIndex = 0;
  100365. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  100366. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  100367. if (animationIndex === -1) {
  100368. animationIndex = 0;
  100369. }
  100370. }
  100371. this._updateAnimationType(animationNames[animationIndex], newParams);
  100372. }
  100373. if (model.configuration.thumbnail) {
  100374. newParams.logoImage = model.configuration.thumbnail;
  100375. }
  100376. navbar.updateParams(newParams);
  100377. };
  100378. /**
  100379. * This will load a new model to the default viewer
  100380. * overriding the AbstractViewer's loadModel.
  100381. * The scene will automatically be cleared of the old models, if exist.
  100382. * @param model the configuration object (or URL) to load.
  100383. */
  100384. DefaultViewer.prototype.loadModel = function (model) {
  100385. var _this = this;
  100386. if (!model) {
  100387. model = this.configuration.model;
  100388. }
  100389. this.showLoadingScreen();
  100390. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  100391. console.log(error);
  100392. _this.hideLoadingScreen();
  100393. _this.showOverlayScreen('error');
  100394. return Promise.reject(error);
  100395. });
  100396. };
  100397. /**
  100398. * Show the overlay and the defined sub-screen.
  100399. * Mainly used for help and errors
  100400. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  100401. */
  100402. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  100403. var _this = this;
  100404. var template = this.templateManager.getTemplate('overlay');
  100405. if (!template)
  100406. return Promise.resolve('Overlay template not found');
  100407. return template.show((function (template) {
  100408. var canvasRect = _this.containerElement.getBoundingClientRect();
  100409. template.parent.style.display = 'flex';
  100410. template.parent.style.width = canvasRect.width + "px";
  100411. template.parent.style.height = canvasRect.height + "px";
  100412. template.parent.style.opacity = "1";
  100413. var subTemplate = _this.templateManager.getTemplate(subScreen);
  100414. if (!subTemplate) {
  100415. return Promise.reject(subScreen + ' template not found');
  100416. }
  100417. return subTemplate.show((function (template) {
  100418. template.parent.style.display = 'flex';
  100419. return Promise.resolve(template);
  100420. }));
  100421. }));
  100422. };
  100423. /**
  100424. * Hide the overlay screen.
  100425. */
  100426. DefaultViewer.prototype.hideOverlayScreen = function () {
  100427. var template = this.templateManager.getTemplate('overlay');
  100428. if (!template)
  100429. return Promise.resolve('Overlay template not found');
  100430. return template.hide((function (template) {
  100431. template.parent.style.opacity = "0";
  100432. var onTransitionEnd = function () {
  100433. template.parent.removeEventListener("transitionend", onTransitionEnd);
  100434. template.parent.style.display = 'none';
  100435. };
  100436. template.parent.addEventListener("transitionend", onTransitionEnd);
  100437. var overlays = template.parent.querySelectorAll('.overlay');
  100438. if (overlays) {
  100439. for (var i = 0; i < overlays.length; ++i) {
  100440. var htmlElement = overlays.item(i);
  100441. htmlElement.style.display = 'none';
  100442. }
  100443. }
  100444. return Promise.resolve(template);
  100445. }));
  100446. };
  100447. /**
  100448. * show the viewer (in case it was hidden)
  100449. *
  100450. * @param visibilityFunction an optional function to execute in order to show the container
  100451. */
  100452. DefaultViewer.prototype.show = function (visibilityFunction) {
  100453. var template = this.templateManager.getTemplate('main');
  100454. //not possible, but yet:
  100455. if (!template)
  100456. return Promise.reject('Main template not found');
  100457. return template.show(visibilityFunction);
  100458. };
  100459. /**
  100460. * hide the viewer (in case it is visible)
  100461. *
  100462. * @param visibilityFunction an optional function to execute in order to hide the container
  100463. */
  100464. DefaultViewer.prototype.hide = function (visibilityFunction) {
  100465. var template = this.templateManager.getTemplate('main');
  100466. //not possible, but yet:
  100467. if (!template)
  100468. return Promise.reject('Main template not found');
  100469. return template.hide(visibilityFunction);
  100470. };
  100471. /**
  100472. * Show the loading screen.
  100473. * The loading screen can be configured using the configuration object
  100474. */
  100475. DefaultViewer.prototype.showLoadingScreen = function () {
  100476. var _this = this;
  100477. var template = this.templateManager.getTemplate('loadingScreen');
  100478. if (!template)
  100479. return Promise.resolve('Loading Screen template not found');
  100480. return template.show((function (template) {
  100481. var canvasRect = _this.containerElement.getBoundingClientRect();
  100482. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  100483. template.parent.style.display = 'flex';
  100484. template.parent.style.width = canvasRect.width + "px";
  100485. template.parent.style.height = canvasRect.height + "px";
  100486. template.parent.style.opacity = "1";
  100487. // from the configuration!!!
  100488. var color = "black";
  100489. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  100490. color = (_this.configuration.templates.loadingScreen.params &&
  100491. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  100492. }
  100493. template.parent.style.backgroundColor = color;
  100494. return Promise.resolve(template);
  100495. }));
  100496. };
  100497. /**
  100498. * Hide the loading screen
  100499. */
  100500. DefaultViewer.prototype.hideLoadingScreen = function () {
  100501. var template = this.templateManager.getTemplate('loadingScreen');
  100502. if (!template)
  100503. return Promise.resolve('Loading Screen template not found');
  100504. return template.hide((function (template) {
  100505. template.parent.style.opacity = "0";
  100506. var onTransitionEnd = function () {
  100507. template.parent.removeEventListener("transitionend", onTransitionEnd);
  100508. template.parent.style.display = 'none';
  100509. };
  100510. template.parent.addEventListener("transitionend", onTransitionEnd);
  100511. return Promise.resolve(template);
  100512. }));
  100513. };
  100514. /**
  100515. * An extension of the light configuration of the abstract viewer.
  100516. * @param lightsConfiguration the light configuration to use
  100517. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  100518. */
  100519. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  100520. var _this = this;
  100521. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  100522. // labs feature - flashlight
  100523. if (this._configuration.lab && this._configuration.lab.flashlight) {
  100524. var pointerPosition = babylonjs_1.Vector3.Zero();
  100525. var lightTarget_1;
  100526. var angle = 0.5;
  100527. var exponent = Math.PI / 2;
  100528. if (typeof this._configuration.lab.flashlight === "object") {
  100529. exponent = this._configuration.lab.flashlight.exponent || exponent;
  100530. angle = this._configuration.lab.flashlight.angle || angle;
  100531. }
  100532. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  100533. if (typeof this._configuration.lab.flashlight === "object") {
  100534. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  100535. if (this._configuration.lab.flashlight.diffuse) {
  100536. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  100537. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  100538. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  100539. }
  100540. if (this._configuration.lab.flashlight.specular) {
  100541. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  100542. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  100543. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  100544. }
  100545. }
  100546. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  100547. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  100548. if (eventData.type === 4 && eventData.pickInfo) {
  100549. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  100550. }
  100551. else {
  100552. lightTarget_1 = undefined;
  100553. }
  100554. });
  100555. var updateFlashlightFunction = function () {
  100556. if (_this.sceneManager.camera && flashlight) {
  100557. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  100558. if (lightTarget_1) {
  100559. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  100560. }
  100561. }
  100562. };
  100563. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  100564. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  100565. }
  100566. };
  100567. return DefaultViewer;
  100568. }(viewer_1.AbstractViewer));
  100569. exports.DefaultViewer = DefaultViewer;
  100570. /***/ }),
  100571. /* 10 */
  100572. /***/ (function(module, exports, __webpack_require__) {
  100573. "use strict";
  100574. Object.defineProperty(exports, "__esModule", { value: true });
  100575. var viewerManager_1 = __webpack_require__(8);
  100576. var sceneManager_1 = __webpack_require__(29);
  100577. var templateManager_1 = __webpack_require__(35);
  100578. var loader_1 = __webpack_require__(38);
  100579. var babylonjs_1 = __webpack_require__(0);
  100580. var deepmerge = __webpack_require__(1);
  100581. var modelLoader_1 = __webpack_require__(22);
  100582. var globals_1 = __webpack_require__(7);
  100583. var telemetryManager_1 = __webpack_require__(5);
  100584. /**
  100585. * The AbstractViewr is the center of Babylon's viewer.
  100586. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  100587. */
  100588. var AbstractViewer = /** @class */ (function () {
  100589. function AbstractViewer(containerElement, initialConfiguration) {
  100590. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  100591. var _this = this;
  100592. this.containerElement = containerElement;
  100593. /**
  100594. * A flag that controls whether or not the render loop should be executed
  100595. */
  100596. this.runRenderLoop = true;
  100597. /**
  100598. * is this viewer disposed?
  100599. */
  100600. this._isDisposed = false;
  100601. /**
  100602. * The resize function that will be registered with the window object
  100603. */
  100604. this._resize = function () {
  100605. // Only resize if Canvas is in the DOM
  100606. if (!_this.isCanvasInDOM()) {
  100607. return;
  100608. }
  100609. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  100610. return;
  100611. }
  100612. if (_this._configuration.engine && _this._configuration.engine.disableResize) {
  100613. return;
  100614. }
  100615. _this.engine.resize();
  100616. };
  100617. /**
  100618. * render loop that will be executed by the engine
  100619. */
  100620. this._render = function (force) {
  100621. if (force === void 0) { force = false; }
  100622. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  100623. if (_this.runRenderLoop || force) {
  100624. _this.engine.performanceMonitor.enable();
  100625. _this.sceneManager.scene.render();
  100626. _this.onFrameRenderedObservable.notifyObservers(_this);
  100627. }
  100628. else {
  100629. _this.engine.performanceMonitor.disable();
  100630. // update camera instead of rendering
  100631. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  100632. }
  100633. }
  100634. };
  100635. // if exists, use the container id. otherwise, generate a random string.
  100636. if (containerElement.id) {
  100637. this.baseId = containerElement.id;
  100638. }
  100639. else {
  100640. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  100641. }
  100642. this.onSceneInitObservable = new babylonjs_1.Observable();
  100643. this.onEngineInitObservable = new babylonjs_1.Observable();
  100644. this.onModelLoadedObservable = new babylonjs_1.Observable();
  100645. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  100646. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  100647. this.onModelAddedObservable = new babylonjs_1.Observable();
  100648. this.onModelRemovedObservable = new babylonjs_1.Observable();
  100649. this.onInitDoneObservable = new babylonjs_1.Observable();
  100650. this.onLoaderInitObservable = new babylonjs_1.Observable();
  100651. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  100652. this._registeredOnBeforeRenderFunctions = [];
  100653. this.modelLoader = new modelLoader_1.ModelLoader(this);
  100654. // add this viewer to the viewer manager
  100655. viewerManager_1.viewerManager.addViewer(this);
  100656. // create a new template manager for this viewer
  100657. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  100658. this.sceneManager = new sceneManager_1.SceneManager(this);
  100659. this._prepareContainerElement();
  100660. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  100661. // extend the configuration
  100662. this._configurationLoader = new loader_1.ConfigurationLoader();
  100663. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  100664. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  100665. if (_this._configuration.observers) {
  100666. _this._configureObservers(_this._configuration.observers);
  100667. }
  100668. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  100669. if (_this._configuration.loaderPlugins) {
  100670. Object.keys(_this._configuration.loaderPlugins).forEach((function (name) {
  100671. if (_this._configuration.loaderPlugins && _this._configuration.loaderPlugins[name]) {
  100672. _this.modelLoader.addPlugin(name);
  100673. }
  100674. }));
  100675. }
  100676. // initialize the templates
  100677. var templateConfiguration = _this._configuration.templates || {};
  100678. _this.templateManager.initTemplate(templateConfiguration);
  100679. // when done, execute onTemplatesLoaded()
  100680. _this.templateManager.onAllLoaded.add(function () {
  100681. var canvas = _this.templateManager.getCanvas();
  100682. if (canvas) {
  100683. _this._canvas = canvas;
  100684. }
  100685. _this._onTemplateLoaded();
  100686. });
  100687. });
  100688. this.onModelLoadedObservable.add(function (model) {
  100689. //this.updateConfiguration(this._configuration, model);
  100690. });
  100691. this.onSceneInitObservable.add(function () {
  100692. _this.updateConfiguration();
  100693. });
  100694. this.onInitDoneObservable.add(function () {
  100695. _this._isInit = true;
  100696. _this.engine.runRenderLoop(_this._render);
  100697. });
  100698. }
  100699. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  100700. /**
  100701. * The (single) canvas of this viewer
  100702. */
  100703. get: function () {
  100704. return this._canvas;
  100705. },
  100706. enumerable: true,
  100707. configurable: true
  100708. });
  100709. /**
  100710. * get the baseId of this viewer
  100711. */
  100712. AbstractViewer.prototype.getBaseId = function () {
  100713. return this.baseId;
  100714. };
  100715. /**
  100716. * Do we have a canvas to render on, and is it a part of the scene
  100717. */
  100718. AbstractViewer.prototype.isCanvasInDOM = function () {
  100719. return !!this._canvas && !!this._canvas.parentElement;
  100720. };
  100721. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  100722. /**
  100723. * Is the engine currently set to rende even when the page is in background
  100724. */
  100725. get: function () {
  100726. return this.engine && this.engine.renderEvenInBackground;
  100727. },
  100728. /**
  100729. * Set the viewer's background rendering flag.
  100730. */
  100731. set: function (value) {
  100732. if (this.engine) {
  100733. this.engine.renderEvenInBackground = value;
  100734. }
  100735. },
  100736. enumerable: true,
  100737. configurable: true
  100738. });
  100739. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  100740. /**
  100741. * Get the configuration object. This is a reference only.
  100742. * The configuration can ONLY be updated using the updateConfiguration function.
  100743. * changing this object will have no direct effect on the scene.
  100744. */
  100745. get: function () {
  100746. return this._configuration;
  100747. },
  100748. enumerable: true,
  100749. configurable: true
  100750. });
  100751. /**
  100752. * force resizing the engine.
  100753. */
  100754. AbstractViewer.prototype.forceResize = function () {
  100755. this._resize();
  100756. };
  100757. /**
  100758. * Force a single render loop execution.
  100759. */
  100760. AbstractViewer.prototype.forceRender = function () {
  100761. this._render(true);
  100762. };
  100763. /**
  100764. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  100765. * @param callback optional callback that will be triggered when screenshot is done.
  100766. * @param width Optional screenshot width (default to 512).
  100767. * @param height Optional screenshot height (default to 512).
  100768. * @returns a promise with the screenshot data
  100769. */
  100770. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  100771. var _this = this;
  100772. if (width === void 0) { width = 0; }
  100773. if (height === void 0) { height = 0; }
  100774. width = width || this.canvas.clientWidth;
  100775. height = height || this.canvas.clientHeight;
  100776. // Create the screenshot
  100777. return new Promise(function (resolve, reject) {
  100778. try {
  100779. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  100780. if (callback) {
  100781. callback(data);
  100782. }
  100783. resolve(data);
  100784. });
  100785. }
  100786. catch (e) {
  100787. reject(e);
  100788. }
  100789. });
  100790. };
  100791. /**
  100792. * Update the current viewer configuration with new values.
  100793. * Only provided information will be updated, old configuration values will be kept.
  100794. * If this.configuration was manually changed, you can trigger this function with no parameters,
  100795. * and the entire configuration will be updated.
  100796. * @param newConfiguration the partial configuration to update
  100797. *
  100798. */
  100799. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  100800. var _this = this;
  100801. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  100802. // update this.configuration with the new data
  100803. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  100804. this.sceneManager.updateConfiguration(newConfiguration, this._configuration);
  100805. // observers in configuration
  100806. if (newConfiguration.observers) {
  100807. this._configureObservers(newConfiguration.observers);
  100808. }
  100809. if (newConfiguration.loaderPlugins) {
  100810. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  100811. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  100812. _this.modelLoader.addPlugin(name);
  100813. }
  100814. }));
  100815. }
  100816. };
  100817. /**
  100818. * this is used to register native functions using the configuration object.
  100819. * This will configure the observers.
  100820. * @param observersConfiguration observers configuration
  100821. */
  100822. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  100823. if (observersConfiguration.onEngineInit) {
  100824. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  100825. }
  100826. else {
  100827. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  100828. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  100829. }
  100830. }
  100831. if (observersConfiguration.onSceneInit) {
  100832. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  100833. }
  100834. else {
  100835. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  100836. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  100837. }
  100838. }
  100839. if (observersConfiguration.onModelLoaded) {
  100840. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  100841. }
  100842. else {
  100843. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  100844. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  100845. }
  100846. }
  100847. };
  100848. /**
  100849. * Dispoe the entire viewer including the scene and the engine
  100850. */
  100851. AbstractViewer.prototype.dispose = function () {
  100852. if (this._isDisposed) {
  100853. return;
  100854. }
  100855. window.removeEventListener('resize', this._resize);
  100856. //observers
  100857. this.onEngineInitObservable.clear();
  100858. this.onInitDoneObservable.clear();
  100859. this.onLoaderInitObservable.clear();
  100860. this.onModelLoadedObservable.clear();
  100861. this.onModelLoadErrorObservable.clear();
  100862. this.onModelLoadProgressObservable.clear();
  100863. this.onSceneInitObservable.clear();
  100864. this.onFrameRenderedObservable.clear();
  100865. this.onModelAddedObservable.clear();
  100866. this.onModelRemovedObservable.clear();
  100867. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  100868. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  100869. }
  100870. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  100871. this.sceneManager.dispose();
  100872. this.modelLoader.dispose();
  100873. if (this.engine) {
  100874. this.engine.dispose();
  100875. }
  100876. this.templateManager.dispose();
  100877. viewerManager_1.viewerManager.removeViewer(this);
  100878. this._isDisposed = true;
  100879. };
  100880. /**
  100881. * This function will execute when the HTML templates finished initializing.
  100882. * It should initialize the engine and continue execution.
  100883. *
  100884. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  100885. */
  100886. AbstractViewer.prototype._onTemplatesLoaded = function () {
  100887. return Promise.resolve(this);
  100888. };
  100889. /**
  100890. * This will force the creation of an engine and a scene.
  100891. * It will also load a model if preconfigured.
  100892. * But first - it will load the extendible onTemplateLoaded()!
  100893. */
  100894. AbstractViewer.prototype._onTemplateLoaded = function () {
  100895. var _this = this;
  100896. // check if viewer was disposed right after created
  100897. if (this._isDisposed) {
  100898. return Promise.reject("viewer was disposed");
  100899. }
  100900. return this._onTemplatesLoaded().then(function () {
  100901. var autoLoad = typeof _this._configuration.model === 'string' || (_this._configuration.model && _this._configuration.model.url);
  100902. return _this._initEngine().then(function (engine) {
  100903. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  100904. }).then(function () {
  100905. _this._initTelemetryEvents();
  100906. if (autoLoad) {
  100907. return _this.loadModel(_this._configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  100908. }
  100909. else {
  100910. return _this.sceneManager.scene || _this.sceneManager.initScene(_this._configuration.scene);
  100911. }
  100912. }).then(function () {
  100913. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  100914. }).catch(function (e) {
  100915. babylonjs_1.Tools.Warn(e.toString());
  100916. return _this;
  100917. });
  100918. });
  100919. };
  100920. /**
  100921. * Initialize the engine. Retruns a promise in case async calls are needed.
  100922. *
  100923. * @protected
  100924. * @returns {Promise<Engine>}
  100925. * @memberof Viewer
  100926. */
  100927. AbstractViewer.prototype._initEngine = function () {
  100928. // init custom shaders
  100929. this._injectCustomShaders();
  100930. var canvasElement = this.templateManager.getCanvas();
  100931. if (!canvasElement) {
  100932. return Promise.reject('Canvas element not found!');
  100933. }
  100934. var config = this._configuration.engine || {};
  100935. // TDO enable further configuration
  100936. // check for webgl2 support, force-disable if needed.
  100937. if (globals_1.viewerGlobals.disableWebGL2Support) {
  100938. config.engineOptions = config.engineOptions || {};
  100939. config.engineOptions.disableWebGL2Support = true;
  100940. }
  100941. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  100942. // Disable manifest checking
  100943. babylonjs_1.Database.IDBStorageEnabled = false;
  100944. if (!config.disableResize) {
  100945. window.addEventListener('resize', this._resize);
  100946. }
  100947. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  100948. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  100949. this.engine.setHardwareScalingLevel(scale);
  100950. }
  100951. return Promise.resolve(this.engine);
  100952. };
  100953. /**
  100954. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  100955. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  100956. *
  100957. * @param modelConfig model configuration to use when loading the model.
  100958. * @param clearScene should the scene be cleared before loading this model
  100959. * @returns a ViewerModel object that is not yet fully loaded.
  100960. */
  100961. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  100962. var _this = this;
  100963. if (clearScene === void 0) { clearScene = true; }
  100964. var configuration;
  100965. if (typeof modelConfig === 'string') {
  100966. configuration = {
  100967. url: modelConfig
  100968. };
  100969. }
  100970. else if (modelConfig instanceof File) {
  100971. configuration = {
  100972. file: modelConfig,
  100973. root: "file:"
  100974. };
  100975. }
  100976. else {
  100977. configuration = modelConfig;
  100978. }
  100979. if (!configuration.url && !configuration.file) {
  100980. throw new Error("no model provided");
  100981. }
  100982. if (clearScene) {
  100983. this.sceneManager.clearScene(true, false);
  100984. }
  100985. //merge the configuration for future models:
  100986. if (this._configuration.model && typeof this._configuration.model === 'object') {
  100987. var globalConfig = deepmerge({}, this._configuration.model);
  100988. configuration = deepmerge(globalConfig, configuration);
  100989. if (modelConfig instanceof File) {
  100990. configuration.file = modelConfig;
  100991. }
  100992. }
  100993. else {
  100994. this._configuration.model = configuration;
  100995. }
  100996. this._isLoading = true;
  100997. var model = this.modelLoader.load(configuration);
  100998. this.lastUsedLoader = model.loader;
  100999. model.onLoadErrorObservable.add(function (errorObject) {
  101000. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  101001. });
  101002. model.onLoadProgressObservable.add(function (progressEvent) {
  101003. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  101004. });
  101005. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  101006. model.onLoadedObservable.add(function () {
  101007. _this._isLoading = false;
  101008. });
  101009. return model;
  101010. };
  101011. /**
  101012. * load a model using the provided configuration.
  101013. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  101014. * If you want to attach to the observables of the model, use initModle instead.
  101015. *
  101016. * @param modelConfig the model configuration or URL to load.
  101017. * @param clearScene Should the scene be cleared before loading the model
  101018. * @returns a Promise the fulfills when the model finished loading successfully.
  101019. */
  101020. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  101021. var _this = this;
  101022. if (clearScene === void 0) { clearScene = true; }
  101023. if (this._isLoading) {
  101024. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  101025. return Promise.reject("another model is curently being loaded.");
  101026. }
  101027. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  101028. if (!scene)
  101029. return _this.sceneManager.initScene(_this._configuration.scene, _this._configuration.optimizer);
  101030. return scene;
  101031. }).then(function () {
  101032. var model = _this.initModel(modelConfig, clearScene);
  101033. return new Promise(function (resolve, reject) {
  101034. // at this point, configuration.model is an object, not a string
  101035. model.onLoadedObservable.add(function () {
  101036. resolve(model);
  101037. });
  101038. model.onLoadErrorObservable.add(function (error) {
  101039. reject(error);
  101040. });
  101041. });
  101042. });
  101043. };
  101044. AbstractViewer.prototype._initTelemetryEvents = function () {
  101045. var _this = this;
  101046. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this, this.engine.getCaps());
  101047. telemetryManager_1.telemetryManager.broadcast("Platform Details", this, {
  101048. userAgent: navigator.userAgent,
  101049. platform: navigator.platform
  101050. });
  101051. telemetryManager_1.telemetryManager.flushWebGLErrors(this);
  101052. var trackFPS = function () {
  101053. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this, { fps: _this.engine.getFps() });
  101054. };
  101055. trackFPS();
  101056. // Track the FPS again after 60 seconds
  101057. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  101058. };
  101059. /**
  101060. * Injects all the spectre shader in the babylon shader store
  101061. */
  101062. AbstractViewer.prototype._injectCustomShaders = function () {
  101063. var customShaders = this._configuration.customShaders;
  101064. // Inject all the spectre shader in the babylon shader store.
  101065. if (!customShaders) {
  101066. return;
  101067. }
  101068. if (customShaders.shaders) {
  101069. Object.keys(customShaders.shaders).forEach(function (key) {
  101070. // typescript considers a callback "unsafe", so... '!'
  101071. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  101072. });
  101073. }
  101074. if (customShaders.includes) {
  101075. Object.keys(customShaders.includes).forEach(function (key) {
  101076. // typescript considers a callback "unsafe", so... '!'
  101077. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  101078. });
  101079. }
  101080. };
  101081. return AbstractViewer;
  101082. }());
  101083. exports.AbstractViewer = AbstractViewer;
  101084. /***/ }),
  101085. /* 11 */
  101086. /***/ (function(module, exports, __webpack_require__) {
  101087. "use strict";
  101088. Object.defineProperty(exports, "__esModule", { value: true });
  101089. function getConfigurationKey(key, configObject) {
  101090. var splits = key.split('.');
  101091. if (splits.length === 0 || !configObject)
  101092. return;
  101093. else if (splits.length === 1) {
  101094. if (configObject[key] !== undefined) {
  101095. return configObject[key];
  101096. }
  101097. }
  101098. else {
  101099. var firstKey = splits.shift();
  101100. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  101101. }
  101102. }
  101103. exports.getConfigurationKey = getConfigurationKey;
  101104. /***/ }),
  101105. /* 12 */
  101106. /***/ (function(module, exports, __webpack_require__) {
  101107. "use strict";
  101108. Object.defineProperty(exports, "__esModule", { value: true });
  101109. /**
  101110. * WebGL Pixel Formats
  101111. */
  101112. var PixelFormat;
  101113. (function (PixelFormat) {
  101114. PixelFormat[PixelFormat["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
  101115. PixelFormat[PixelFormat["ALPHA"] = 6406] = "ALPHA";
  101116. PixelFormat[PixelFormat["RGB"] = 6407] = "RGB";
  101117. PixelFormat[PixelFormat["RGBA"] = 6408] = "RGBA";
  101118. PixelFormat[PixelFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  101119. PixelFormat[PixelFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  101120. })(PixelFormat = exports.PixelFormat || (exports.PixelFormat = {}));
  101121. /**
  101122. * WebGL Pixel Types
  101123. */
  101124. var PixelType;
  101125. (function (PixelType) {
  101126. PixelType[PixelType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101127. PixelType[PixelType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  101128. PixelType[PixelType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  101129. PixelType[PixelType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  101130. })(PixelType = exports.PixelType || (exports.PixelType = {}));
  101131. /**
  101132. * WebGL Texture Magnification Filter
  101133. */
  101134. var TextureMagFilter;
  101135. (function (TextureMagFilter) {
  101136. TextureMagFilter[TextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  101137. TextureMagFilter[TextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  101138. })(TextureMagFilter = exports.TextureMagFilter || (exports.TextureMagFilter = {}));
  101139. /**
  101140. * WebGL Texture Minification Filter
  101141. */
  101142. var TextureMinFilter;
  101143. (function (TextureMinFilter) {
  101144. TextureMinFilter[TextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  101145. TextureMinFilter[TextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  101146. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  101147. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  101148. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  101149. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  101150. })(TextureMinFilter = exports.TextureMinFilter || (exports.TextureMinFilter = {}));
  101151. /**
  101152. * WebGL Texture Wrap Modes
  101153. */
  101154. var TextureWrapMode;
  101155. (function (TextureWrapMode) {
  101156. TextureWrapMode[TextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  101157. TextureWrapMode[TextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  101158. TextureWrapMode[TextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  101159. })(TextureWrapMode = exports.TextureWrapMode || (exports.TextureWrapMode = {}));
  101160. /**
  101161. * A minimal WebGL cubemap descriptor
  101162. */
  101163. var TextureCube = /** @class */ (function () {
  101164. /**
  101165. * constructor
  101166. * @param internalFormat WebGL pixel format for the texture on the GPU
  101167. * @param type WebGL pixel type of the supplied data and texture on the GPU
  101168. * @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
  101169. */
  101170. function TextureCube(internalFormat, type, source) {
  101171. if (source === void 0) { source = []; }
  101172. this.internalFormat = internalFormat;
  101173. this.type = type;
  101174. this.source = source;
  101175. }
  101176. Object.defineProperty(TextureCube.prototype, "Width", {
  101177. /**
  101178. * Returns the width of a face of the texture or 0 if not available
  101179. */
  101180. get: function () {
  101181. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  101182. },
  101183. enumerable: true,
  101184. configurable: true
  101185. });
  101186. Object.defineProperty(TextureCube.prototype, "Height", {
  101187. /**
  101188. * Returns the height of a face of the texture or 0 if not available
  101189. */
  101190. get: function () {
  101191. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  101192. },
  101193. enumerable: true,
  101194. configurable: true
  101195. });
  101196. return TextureCube;
  101197. }());
  101198. exports.TextureCube = TextureCube;
  101199. /**
  101200. * A static class providing methods to aid working with Bablyon textures.
  101201. */
  101202. var TextureUtils = /** @class */ (function () {
  101203. function TextureUtils() {
  101204. }
  101205. /**
  101206. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  101207. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  101208. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  101209. * @param scene A Babylon Scene instance
  101210. * @param textureCube A Spectre TextureCube object
  101211. * @param parameters WebGL texture sampling parameters
  101212. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  101213. * @param environment Specifies that the texture will be used as an environment
  101214. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  101215. * @return Babylon cube texture
  101216. */
  101217. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  101218. if (environment === void 0) { environment = false; }
  101219. if (singleLod === void 0) { singleLod = false; }
  101220. if (!textureCube)
  101221. throw new Error("no texture cube provided");
  101222. var parameters;
  101223. if (environment) {
  101224. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  101225. }
  101226. else {
  101227. parameters = {
  101228. magFilter: 9728 /* NEAREST */,
  101229. minFilter: 9728 /* NEAREST */,
  101230. wrapS: 33071 /* CLAMP_TO_EDGE */,
  101231. wrapT: 33071 /* CLAMP_TO_EDGE */
  101232. };
  101233. }
  101234. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  101235. var babylonTexture = textureCube[key];
  101236. if (!babylonTexture) {
  101237. //initialize babylon texture
  101238. babylonTexture = new BABYLON.CubeTexture('', scene);
  101239. if (environment) {
  101240. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  101241. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  101242. }
  101243. babylonTexture.gammaSpace = false;
  101244. var internalTexture_1 = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  101245. var glTexture_1 = internalTexture_1._webGLTexture;
  101246. //babylon properties
  101247. internalTexture_1.isCube = true;
  101248. internalTexture_1.generateMipMaps = false;
  101249. babylonTexture._texture = internalTexture_1;
  101250. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  101251. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  101252. var texturesUploaded_1 = 0;
  101253. var textureComplete = function () {
  101254. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  101255. };
  101256. var uploadFace = function (i, level, face) {
  101257. if (!glTexture_1)
  101258. return;
  101259. if (i === 0 && level === 0) {
  101260. internalTexture_1.width = face.width;
  101261. internalTexture_1.height = face.height;
  101262. }
  101263. var gl = (scene.getEngine())._gl;
  101264. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  101265. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  101266. if (face instanceof HTMLElement || face instanceof ImageData) {
  101267. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  101268. }
  101269. else {
  101270. var textureData = face;
  101271. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  101272. }
  101273. texturesUploaded_1++;
  101274. if (textureComplete()) {
  101275. //generate mipmaps
  101276. if (automaticMipmaps) {
  101277. var w = face.width;
  101278. var h = face.height;
  101279. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  101280. if (isPot) {
  101281. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  101282. }
  101283. }
  101284. // Upload Separate lods in case there is no support for texture lod.
  101285. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  101286. var mipSlices = 3;
  101287. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  101288. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  101289. var lod = textureCube[lodKey];
  101290. //initialize lod texture if it doesn't already exist
  101291. if (lod == null && textureCube.Width) {
  101292. //compute LOD from even spacing in smoothness (matching shader calculation)
  101293. var smoothness = i_1 / (mipSlices - 1);
  101294. var roughness = 1 - smoothness;
  101295. var kMinimumVariance = 0.0005;
  101296. var alphaG = roughness * roughness + kMinimumVariance;
  101297. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  101298. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (BABYLON.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  101299. var maxLODIndex = textureCube.source.length - 1;
  101300. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  101301. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  101302. if (i_1 === 0) {
  101303. internalTexture_1._lodTextureLow = lod;
  101304. }
  101305. else if (i_1 === 1) {
  101306. internalTexture_1._lodTextureMid = lod;
  101307. }
  101308. else {
  101309. internalTexture_1._lodTextureHigh = lod;
  101310. }
  101311. textureCube[lodKey] = lod;
  101312. }
  101313. }
  101314. }
  101315. internalTexture_1.isReady = true;
  101316. }
  101317. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  101318. scene.getEngine().resetTextureCache();
  101319. };
  101320. var _loop_1 = function (i) {
  101321. var faces = textureCube.source[i];
  101322. var _loop_2 = function (j) {
  101323. var face = faces[j];
  101324. if (face instanceof HTMLImageElement && !face.complete) {
  101325. face.addEventListener('load', function () {
  101326. uploadFace(j, i, face);
  101327. }, false);
  101328. }
  101329. else {
  101330. uploadFace(j, i, face);
  101331. }
  101332. };
  101333. for (var j = 0; j < faces.length; j++) {
  101334. _loop_2(j);
  101335. }
  101336. };
  101337. for (var i = 0; i <= maxMipLevel_1; i++) {
  101338. _loop_1(i);
  101339. }
  101340. scene.getEngine().resetTextureCache();
  101341. babylonTexture.isReady = function () {
  101342. return textureComplete();
  101343. };
  101344. textureCube[key] = babylonTexture;
  101345. }
  101346. return babylonTexture;
  101347. };
  101348. /**
  101349. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  101350. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  101351. * @param parameters Spectre SamplingParameters to apply
  101352. */
  101353. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  101354. var scene = babylonTexture.getScene();
  101355. if (!scene)
  101356. return;
  101357. var gl = (scene.getEngine())._gl;
  101358. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  101359. var internalTexture = babylonTexture._texture;
  101360. if (!internalTexture)
  101361. return;
  101362. var glTexture = internalTexture._webGLTexture;
  101363. gl.bindTexture(target, glTexture);
  101364. if (parameters.magFilter != null)
  101365. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  101366. if (parameters.minFilter != null)
  101367. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  101368. if (parameters.wrapS != null)
  101369. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  101370. if (parameters.wrapT != null)
  101371. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  101372. //set babylon wrap modes from sampling parameter
  101373. switch (parameters.wrapS) {
  101374. case 10497 /* REPEAT */:
  101375. babylonTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  101376. break;
  101377. case 33071 /* CLAMP_TO_EDGE */:
  101378. babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101379. break;
  101380. case 33648 /* MIRRORED_REPEAT */:
  101381. babylonTexture.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  101382. break;
  101383. default: babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101384. }
  101385. switch (parameters.wrapT) {
  101386. case 10497 /* REPEAT */:
  101387. babylonTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  101388. break;
  101389. case 33071 /* CLAMP_TO_EDGE */:
  101390. babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101391. break;
  101392. case 33648 /* MIRRORED_REPEAT */:
  101393. babylonTexture.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  101394. break;
  101395. default: babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101396. }
  101397. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  101398. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  101399. if (anisotropicExt) {
  101400. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  101401. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  101402. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  101403. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  101404. }
  101405. }
  101406. gl.bindTexture(target, null);
  101407. scene.getEngine().resetTextureCache();
  101408. };
  101409. /**
  101410. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  101411. */
  101412. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  101413. /**
  101414. * Controls anisotropic filtering for deserialized textures.
  101415. */
  101416. TextureUtils.MaxAnisotropy = 4;
  101417. TextureUtils._EnvironmentSampling = {
  101418. magFilter: 9729 /* LINEAR */,
  101419. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  101420. wrapS: 33071 /* CLAMP_TO_EDGE */,
  101421. wrapT: 33071 /* CLAMP_TO_EDGE */,
  101422. maxAnisotropy: 1
  101423. };
  101424. TextureUtils._EnvironmentSingleMipSampling = {
  101425. magFilter: 9729 /* LINEAR */,
  101426. minFilter: 9729 /* LINEAR */,
  101427. wrapS: 33071 /* CLAMP_TO_EDGE */,
  101428. wrapT: 33071 /* CLAMP_TO_EDGE */,
  101429. maxAnisotropy: 1
  101430. };
  101431. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  101432. /**
  101433. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  101434. */
  101435. TextureUtils.EnvironmentLODScale = 0.8;
  101436. /**
  101437. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  101438. */
  101439. TextureUtils.EnvironmentLODOffset = 1.0;
  101440. return TextureUtils;
  101441. }());
  101442. exports.TextureUtils = TextureUtils;
  101443. /***/ }),
  101444. /* 13 */
  101445. /***/ (function(module, exports) {
  101446. module.exports = "<style>@font-face{font-family:babylon;src:url({{babylonFont}}) format('woff');font-weight:400;font-style:normal}.icon{font-family:babylon}</style> {{#if fillScreen}} <style>body,html{width:100%;height:100%;margin:0;padding:0}</style> {{/if}} <fill-container></fill-container>";
  101447. /***/ }),
  101448. /* 14 */
  101449. /***/ (function(module, exports) {
  101450. module.exports = "<style>fill-container{display:flex}fill-container>*{touch-action:none}</style> {{#unless disable}} <style>fill-container{width:100%;height:100%;justify-content:flex-start;align-items:stretch;align-content:stretch}fill-container>*{flex:1 1 auto;flex-direction:row;justify-content:flex-start;align-items:stretch;align-content:stretch}</style> {{/unless}} <viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  101451. /***/ }),
  101452. /* 15 */
  101453. /***/ (function(module, exports) {
  101454. 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}}>";
  101455. /***/ }),
  101456. /* 16 */
  101457. /***/ (function(module, exports) {
  101458. 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=="
  101459. /***/ }),
  101460. /* 17 */
  101461. /***/ (function(module, exports) {
  101462. module.exports = "<style>viewer{position:relative;overflow:hidden;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas touch-action=none> </canvas> <nav-bar></nav-bar>";
  101463. /***/ }),
  101464. /* 18 */
  101465. /***/ (function(module, exports) {
  101466. 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>";
  101467. /***/ }),
  101468. /* 19 */
  101469. /***/ (function(module, exports) {
  101470. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  101471. /***/ }),
  101472. /* 20 */
  101473. /***/ (function(module, exports) {
  101474. module.exports = "Error loading the model";
  101475. /***/ }),
  101476. /* 21 */
  101477. /***/ (function(module, exports, __webpack_require__) {
  101478. "use strict";
  101479. function __export(m) {
  101480. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  101481. }
  101482. Object.defineProperty(exports, "__esModule", { value: true });
  101483. __export(__webpack_require__(11));
  101484. /***/ }),
  101485. /* 22 */
  101486. /***/ (function(module, exports, __webpack_require__) {
  101487. "use strict";
  101488. Object.defineProperty(exports, "__esModule", { value: true });
  101489. var babylonjs_1 = __webpack_require__(0);
  101490. var babylonjs_loaders_1 = __webpack_require__(23);
  101491. var viewerModel_1 = __webpack_require__(4);
  101492. var _1 = __webpack_require__(51);
  101493. /**
  101494. * An instance of the class is in charge of loading the model correctly.
  101495. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  101496. *
  101497. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  101498. */
  101499. var ModelLoader = /** @class */ (function () {
  101500. /**
  101501. * Create a new Model loader
  101502. * @param _viewer the viewer using this model loader
  101503. */
  101504. function ModelLoader(_viewer) {
  101505. this._viewer = _viewer;
  101506. this._disposed = false;
  101507. this._loaders = [];
  101508. this._loadId = 0;
  101509. this._plugins = [];
  101510. }
  101511. /**
  101512. * Adds a new plugin to the loader process.
  101513. *
  101514. * @param plugin the plugin name or the plugin itself
  101515. */
  101516. ModelLoader.prototype.addPlugin = function (plugin) {
  101517. var actualPlugin = {};
  101518. if (typeof plugin === 'string') {
  101519. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  101520. if (loadedPlugin) {
  101521. actualPlugin = loadedPlugin;
  101522. }
  101523. }
  101524. else {
  101525. actualPlugin = plugin;
  101526. }
  101527. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  101528. this._plugins.push(actualPlugin);
  101529. }
  101530. };
  101531. /**
  101532. * Load a model using predefined configuration
  101533. * @param modelConfiguration the modelConfiguration to use to load the model
  101534. */
  101535. ModelLoader.prototype.load = function (modelConfiguration) {
  101536. var _this = this;
  101537. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  101538. model.loadId = this._loadId++;
  101539. if (!modelConfiguration.url) {
  101540. model.state = viewerModel_1.ModelState.ERROR;
  101541. babylonjs_1.Tools.Error("No URL provided");
  101542. return model;
  101543. }
  101544. var base;
  101545. var filename;
  101546. if (modelConfiguration.file) {
  101547. base = "file:";
  101548. filename = modelConfiguration.file;
  101549. }
  101550. else {
  101551. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  101552. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  101553. }
  101554. var plugin = modelConfiguration.loader;
  101555. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.sceneManager.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  101556. meshes.forEach(function (mesh) {
  101557. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  101558. model.addMesh(mesh);
  101559. });
  101560. model.particleSystems = particleSystems;
  101561. model.skeletons = skeletons;
  101562. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  101563. var animationGroup = animationGroups_1[_i];
  101564. model.addAnimationGroup(animationGroup);
  101565. }
  101566. _this._checkAndRun("onLoaded", model);
  101567. _this._viewer.sceneManager.scene.executeWhenReady(function () {
  101568. model.onLoadedObservable.notifyObservers(model);
  101569. });
  101570. }, function (progressEvent) {
  101571. _this._checkAndRun("onProgress", progressEvent);
  101572. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  101573. }, function (scene, m, exception) {
  101574. model.state = viewerModel_1.ModelState.ERROR;
  101575. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  101576. _this._checkAndRun("onError", m, exception);
  101577. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  101578. }, plugin);
  101579. if (model.loader.name === "gltf") {
  101580. var gltfLoader_1 = model.loader;
  101581. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  101582. gltfLoader_1.compileMaterials = true;
  101583. if (!modelConfiguration.file) {
  101584. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  101585. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  101586. };
  101587. }
  101588. // if ground is set to "mirror":
  101589. if (this._viewer.configuration.ground && typeof this._viewer.configuration.ground === 'object' && this._viewer.configuration.ground.mirror) {
  101590. gltfLoader_1.useClipPlane = true;
  101591. }
  101592. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  101593. gltfLoader_1[functionName].add(function (payload) {
  101594. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  101595. });
  101596. });
  101597. gltfLoader_1.onParsedObservable.add(function (data) {
  101598. if (data && data.json && data.json['asset']) {
  101599. model.loadInfo = data.json['asset'];
  101600. }
  101601. });
  101602. gltfLoader_1.onCompleteObservable.add(function () {
  101603. model.loaderDone = true;
  101604. });
  101605. }
  101606. else {
  101607. model.loaderDone = true;
  101608. }
  101609. this._checkAndRun("onInit", model.loader, model);
  101610. this._loaders.push(model.loader);
  101611. return model;
  101612. };
  101613. ModelLoader.prototype.cancelLoad = function (model) {
  101614. var loader = model.loader || this._loaders[model.loadId];
  101615. // ATM only available in the GLTF Loader
  101616. if (loader && loader.name === "gltf") {
  101617. var gltfLoader = loader;
  101618. gltfLoader.dispose();
  101619. model.state = viewerModel_1.ModelState.CANCELED;
  101620. }
  101621. else {
  101622. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  101623. }
  101624. };
  101625. /**
  101626. * dispose the model loader.
  101627. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  101628. */
  101629. ModelLoader.prototype.dispose = function () {
  101630. this._loaders.forEach(function (loader) {
  101631. if (loader.name === "gltf") {
  101632. loader.dispose();
  101633. }
  101634. });
  101635. this._loaders.length = 0;
  101636. this._disposed = true;
  101637. };
  101638. ModelLoader.prototype._checkAndRun = function (functionName) {
  101639. var _this = this;
  101640. var payload = [];
  101641. for (var _i = 1; _i < arguments.length; _i++) {
  101642. payload[_i - 1] = arguments[_i];
  101643. }
  101644. if (this._disposed)
  101645. return;
  101646. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  101647. try {
  101648. plugin[functionName].apply(_this, payload);
  101649. }
  101650. catch (e) { }
  101651. });
  101652. };
  101653. return ModelLoader;
  101654. }());
  101655. exports.ModelLoader = ModelLoader;
  101656. /***/ }),
  101657. /* 23 */
  101658. /***/ (function(module, exports, __webpack_require__) {
  101659. (function universalModuleDefinition(root, factory) {
  101660. var amdDependencies = [];
  101661. var BABYLON = root.BABYLON || this.BABYLON;
  101662. if(true) {
  101663. BABYLON = BABYLON || __webpack_require__(0);
  101664. module.exports = factory(BABYLON);
  101665. } else if(typeof define === 'function' && define.amd) {
  101666. amdDependencies.push("babylonjs");
  101667. define("babylonjs-loaders", amdDependencies, factory);
  101668. } else if(typeof exports === 'object') {
  101669. BABYLON = BABYLON || require("babylonjs");
  101670. exports["babylonjs-loaders"] = factory(BABYLON);
  101671. } else {
  101672. root["BABYLON"] = factory(BABYLON);
  101673. }
  101674. })(this, function(BABYLON) {
  101675. BABYLON = BABYLON || this.BABYLON;
  101676. 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};
  101677. 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)}}();
  101678. var BABYLON;
  101679. (function (BABYLON) {
  101680. var STLFileLoader = /** @class */ (function () {
  101681. function STLFileLoader() {
  101682. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  101683. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  101684. 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;
  101685. 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;
  101686. this.name = "stl";
  101687. // force data to come in as an ArrayBuffer
  101688. // we'll convert to string if it looks like it's an ASCII .stl
  101689. this.extensions = {
  101690. ".stl": { isBinary: true },
  101691. };
  101692. }
  101693. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  101694. var matches;
  101695. if (this.isBinary(data)) {
  101696. // binary .stl
  101697. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  101698. this.parseBinary(babylonMesh, data);
  101699. if (meshes) {
  101700. meshes.push(babylonMesh);
  101701. }
  101702. return true;
  101703. }
  101704. // ASCII .stl
  101705. // convert to string
  101706. var array_buffer = new Uint8Array(data);
  101707. var str = '';
  101708. for (var i = 0; i < data.byteLength; i++) {
  101709. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  101710. }
  101711. data = str;
  101712. while (matches = this.solidPattern.exec(data)) {
  101713. var meshName = matches[1];
  101714. var meshNameFromEnd = matches[3];
  101715. if (meshName != meshNameFromEnd) {
  101716. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  101717. return false;
  101718. }
  101719. // check meshesNames
  101720. if (meshesNames && meshName) {
  101721. if (meshesNames instanceof Array) {
  101722. if (!meshesNames.indexOf(meshName)) {
  101723. continue;
  101724. }
  101725. }
  101726. else {
  101727. if (meshName !== meshesNames) {
  101728. continue;
  101729. }
  101730. }
  101731. }
  101732. // stl mesh name can be empty as well
  101733. meshName = meshName || "stlmesh";
  101734. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  101735. this.parseASCII(babylonMesh, matches[2]);
  101736. if (meshes) {
  101737. meshes.push(babylonMesh);
  101738. }
  101739. }
  101740. return true;
  101741. };
  101742. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  101743. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  101744. if (result) {
  101745. scene.createDefaultCameraOrLight();
  101746. }
  101747. return result;
  101748. };
  101749. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  101750. var container = new BABYLON.AssetContainer(scene);
  101751. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  101752. container.removeAllFromScene();
  101753. return container;
  101754. };
  101755. STLFileLoader.prototype.isBinary = function (data) {
  101756. // check if file size is correct for binary stl
  101757. var faceSize, nFaces, reader;
  101758. reader = new DataView(data);
  101759. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  101760. nFaces = reader.getUint32(80, true);
  101761. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  101762. return true;
  101763. }
  101764. // check characters higher than ASCII to confirm binary
  101765. var fileLength = reader.byteLength;
  101766. for (var index = 0; index < fileLength; index++) {
  101767. if (reader.getUint8(index) > 127) {
  101768. return true;
  101769. }
  101770. }
  101771. return false;
  101772. };
  101773. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  101774. var reader = new DataView(data);
  101775. var faces = reader.getUint32(80, true);
  101776. var dataOffset = 84;
  101777. var faceLength = 12 * 4 + 2;
  101778. var offset = 0;
  101779. var positions = new Float32Array(faces * 3 * 3);
  101780. var normals = new Float32Array(faces * 3 * 3);
  101781. var indices = new Uint32Array(faces * 3);
  101782. var indicesCount = 0;
  101783. for (var face = 0; face < faces; face++) {
  101784. var start = dataOffset + face * faceLength;
  101785. var normalX = reader.getFloat32(start, true);
  101786. var normalY = reader.getFloat32(start + 4, true);
  101787. var normalZ = reader.getFloat32(start + 8, true);
  101788. for (var i = 1; i <= 3; i++) {
  101789. var vertexstart = start + i * 12;
  101790. // ordering is intentional to match ascii import
  101791. positions[offset] = reader.getFloat32(vertexstart, true);
  101792. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  101793. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  101794. normals[offset] = normalX;
  101795. normals[offset + 2] = normalY;
  101796. normals[offset + 1] = normalZ;
  101797. offset += 3;
  101798. }
  101799. indices[indicesCount] = indicesCount++;
  101800. indices[indicesCount] = indicesCount++;
  101801. indices[indicesCount] = indicesCount++;
  101802. }
  101803. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  101804. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  101805. mesh.setIndices(indices);
  101806. mesh.computeWorldMatrix(true);
  101807. };
  101808. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  101809. var positions = [];
  101810. var normals = [];
  101811. var indices = [];
  101812. var indicesCount = 0;
  101813. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  101814. var matches;
  101815. while (matches = this.facetsPattern.exec(solidData)) {
  101816. var facet = matches[1];
  101817. //one normal per face
  101818. var normalMatches = this.normalPattern.exec(facet);
  101819. this.normalPattern.lastIndex = 0;
  101820. if (!normalMatches) {
  101821. continue;
  101822. }
  101823. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  101824. var vertexMatch;
  101825. while (vertexMatch = this.vertexPattern.exec(facet)) {
  101826. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  101827. normals.push(normal[0], normal[1], normal[2]);
  101828. }
  101829. indices.push(indicesCount++, indicesCount++, indicesCount++);
  101830. this.vertexPattern.lastIndex = 0;
  101831. }
  101832. this.facetsPattern.lastIndex = 0;
  101833. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  101834. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  101835. mesh.setIndices(indices);
  101836. mesh.computeWorldMatrix(true);
  101837. };
  101838. return STLFileLoader;
  101839. }());
  101840. BABYLON.STLFileLoader = STLFileLoader;
  101841. if (BABYLON.SceneLoader) {
  101842. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  101843. }
  101844. })(BABYLON || (BABYLON = {}));
  101845. //# sourceMappingURL=babylon.stlFileLoader.js.map
  101846. var BABYLON;
  101847. (function (BABYLON) {
  101848. /**
  101849. * Class reading and parsing the MTL file bundled with the obj file.
  101850. */
  101851. var MTLFileLoader = /** @class */ (function () {
  101852. function MTLFileLoader() {
  101853. // All material loaded from the mtl will be set here
  101854. this.materials = [];
  101855. }
  101856. /**
  101857. * This function will read the mtl file and create each material described inside
  101858. * This function could be improve by adding :
  101859. * -some component missing (Ni, Tf...)
  101860. * -including the specific options available
  101861. *
  101862. * @param scene
  101863. * @param data
  101864. * @param rootUrl
  101865. */
  101866. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  101867. if (data instanceof ArrayBuffer) {
  101868. return;
  101869. }
  101870. //Split the lines from the file
  101871. var lines = data.split('\n');
  101872. //Space char
  101873. var delimiter_pattern = /\s+/;
  101874. //Array with RGB colors
  101875. var color;
  101876. //New material
  101877. var material = null;
  101878. //Look at each line
  101879. for (var i = 0; i < lines.length; i++) {
  101880. var line = lines[i].trim();
  101881. // Blank line or comment
  101882. if (line.length === 0 || line.charAt(0) === '#') {
  101883. continue;
  101884. }
  101885. //Get the first parameter (keyword)
  101886. var pos = line.indexOf(' ');
  101887. var key = (pos >= 0) ? line.substring(0, pos) : line;
  101888. key = key.toLowerCase();
  101889. //Get the data following the key
  101890. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  101891. //This mtl keyword will create the new material
  101892. if (key === "newmtl") {
  101893. //Check if it is the first material.
  101894. // Materials specifications are described after this keyword.
  101895. if (material) {
  101896. //Add the previous material in the material array.
  101897. this.materials.push(material);
  101898. }
  101899. //Create a new material.
  101900. // value is the name of the material read in the mtl file
  101901. material = new BABYLON.StandardMaterial(value, scene);
  101902. }
  101903. else if (key === "kd" && material) {
  101904. // Diffuse color (color under white light) using RGB values
  101905. //value = "r g b"
  101906. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101907. //color = [r,g,b]
  101908. //Set tghe color into the material
  101909. material.diffuseColor = BABYLON.Color3.FromArray(color);
  101910. }
  101911. else if (key === "ka" && material) {
  101912. // Ambient color (color under shadow) using RGB values
  101913. //value = "r g b"
  101914. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101915. //color = [r,g,b]
  101916. //Set tghe color into the material
  101917. material.ambientColor = BABYLON.Color3.FromArray(color);
  101918. }
  101919. else if (key === "ks" && material) {
  101920. // Specular color (color when light is reflected from shiny surface) using RGB values
  101921. //value = "r g b"
  101922. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101923. //color = [r,g,b]
  101924. //Set the color into the material
  101925. material.specularColor = BABYLON.Color3.FromArray(color);
  101926. }
  101927. else if (key === "ke" && material) {
  101928. // Emissive color using RGB values
  101929. color = value.split(delimiter_pattern, 3).map(parseFloat);
  101930. material.emissiveColor = BABYLON.Color3.FromArray(color);
  101931. }
  101932. else if (key === "ns" && material) {
  101933. //value = "Integer"
  101934. material.specularPower = parseFloat(value);
  101935. }
  101936. else if (key === "d" && material) {
  101937. //d is dissolve for current material. It mean alpha for BABYLON
  101938. material.alpha = parseFloat(value);
  101939. //Texture
  101940. //This part can be improved by adding the possible options of texture
  101941. }
  101942. else if (key === "map_ka" && material) {
  101943. // ambient texture map with a loaded image
  101944. //We must first get the folder of the image
  101945. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101946. }
  101947. else if (key === "map_kd" && material) {
  101948. // Diffuse texture map with a loaded image
  101949. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101950. }
  101951. else if (key === "map_ks" && material) {
  101952. // Specular texture map with a loaded image
  101953. //We must first get the folder of the image
  101954. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101955. }
  101956. else if (key === "map_ns") {
  101957. //Specular
  101958. //Specular highlight component
  101959. //We must first get the folder of the image
  101960. //
  101961. //Not supported by BABYLON
  101962. //
  101963. // continue;
  101964. }
  101965. else if (key === "map_bump" && material) {
  101966. //The bump texture
  101967. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101968. }
  101969. else if (key === "map_d" && material) {
  101970. // The dissolve of the material
  101971. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  101972. //Options for illumination
  101973. }
  101974. else if (key === "illum") {
  101975. //Illumination
  101976. if (value === "0") {
  101977. //That mean Kd == Kd
  101978. }
  101979. else if (value === "1") {
  101980. //Color on and Ambient on
  101981. }
  101982. else if (value === "2") {
  101983. //Highlight on
  101984. }
  101985. else if (value === "3") {
  101986. //Reflection on and Ray trace on
  101987. }
  101988. else if (value === "4") {
  101989. //Transparency: Glass on, Reflection: Ray trace on
  101990. }
  101991. else if (value === "5") {
  101992. //Reflection: Fresnel on and Ray trace on
  101993. }
  101994. else if (value === "6") {
  101995. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  101996. }
  101997. else if (value === "7") {
  101998. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  101999. }
  102000. else if (value === "8") {
  102001. //Reflection on and Ray trace off
  102002. }
  102003. else if (value === "9") {
  102004. //Transparency: Glass on, Reflection: Ray trace off
  102005. }
  102006. else if (value === "10") {
  102007. //Casts shadows onto invisible surfaces
  102008. }
  102009. }
  102010. else {
  102011. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  102012. }
  102013. }
  102014. //At the end of the file, add the last material
  102015. if (material) {
  102016. this.materials.push(material);
  102017. }
  102018. };
  102019. /**
  102020. * Gets the texture for the material.
  102021. *
  102022. * If the material is imported from input file,
  102023. * We sanitize the url to ensure it takes the textre from aside the material.
  102024. *
  102025. * @param rootUrl The root url to load from
  102026. * @param value The value stored in the mtl
  102027. * @return The Texture
  102028. */
  102029. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  102030. if (!value) {
  102031. return null;
  102032. }
  102033. var url = rootUrl;
  102034. // Load from input file.
  102035. if (rootUrl === "file:") {
  102036. var lastDelimiter = value.lastIndexOf("\\");
  102037. if (lastDelimiter === -1) {
  102038. lastDelimiter = value.lastIndexOf("/");
  102039. }
  102040. if (lastDelimiter > -1) {
  102041. url += value.substr(lastDelimiter + 1);
  102042. }
  102043. else {
  102044. url += value;
  102045. }
  102046. }
  102047. // Not from input file.
  102048. else {
  102049. url += value;
  102050. }
  102051. return new BABYLON.Texture(url, scene);
  102052. };
  102053. return MTLFileLoader;
  102054. }());
  102055. BABYLON.MTLFileLoader = MTLFileLoader;
  102056. var OBJFileLoader = /** @class */ (function () {
  102057. function OBJFileLoader() {
  102058. this.name = "obj";
  102059. this.extensions = ".obj";
  102060. this.obj = /^o/;
  102061. this.group = /^g/;
  102062. this.mtllib = /^mtllib /;
  102063. this.usemtl = /^usemtl /;
  102064. this.smooth = /^s /;
  102065. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102066. // vn float float float
  102067. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102068. // vt float float
  102069. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102070. // f vertex vertex vertex ...
  102071. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  102072. // f vertex/uvs vertex/uvs vertex/uvs ...
  102073. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  102074. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  102075. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  102076. // f vertex//normal vertex//normal vertex//normal ...
  102077. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  102078. }
  102079. /**
  102080. * Calls synchronously the MTL file attached to this obj.
  102081. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  102082. * Without this function materials are not displayed in the first frame (but displayed after).
  102083. * In consequence it is impossible to get material information in your HTML file
  102084. *
  102085. * @param url The URL of the MTL file
  102086. * @param rootUrl
  102087. * @param onSuccess Callback function to be called when the MTL file is loaded
  102088. * @private
  102089. */
  102090. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  102091. //The complete path to the mtl file
  102092. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  102093. // Loads through the babylon tools to allow fileInput search.
  102094. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  102095. };
  102096. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  102097. //get the meshes from OBJ file
  102098. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  102099. //Push meshes from OBJ file into the variable mesh of this function
  102100. if (meshes) {
  102101. loadedMeshes.forEach(function (mesh) {
  102102. meshes.push(mesh);
  102103. });
  102104. }
  102105. return true;
  102106. };
  102107. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  102108. //Get the 3D model
  102109. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  102110. };
  102111. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  102112. var container = new BABYLON.AssetContainer(scene);
  102113. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  102114. container.removeAllFromScene();
  102115. return container;
  102116. };
  102117. /**
  102118. * Read the OBJ file and create an Array of meshes.
  102119. * Each mesh contains all information given by the OBJ and the MTL file.
  102120. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  102121. *
  102122. * @param meshesNames
  102123. * @param scene BABYLON.Scene The scene where are displayed the data
  102124. * @param data String The content of the obj file
  102125. * @param rootUrl String The path to the folder
  102126. * @returns Array<AbstractMesh>
  102127. * @private
  102128. */
  102129. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  102130. var positions = []; //values for the positions of vertices
  102131. var normals = []; //Values for the normals
  102132. var uvs = []; //Values for the textures
  102133. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  102134. var handledMesh; //The current mesh of meshes array
  102135. var indicesForBabylon = []; //The list of indices for VertexData
  102136. var wrappedPositionForBabylon = []; //The list of position in vectors
  102137. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  102138. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  102139. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  102140. var curPositionInIndices = 0;
  102141. var hasMeshes = false; //Meshes are defined in the file
  102142. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  102143. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  102144. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  102145. var triangles = []; //Indices from new triangles coming from polygons
  102146. var materialNameFromObj = ""; //The name of the current material
  102147. var fileToLoad = ""; //The name of the mtlFile to load
  102148. var materialsFromMTLFile = new MTLFileLoader();
  102149. var objMeshName = ""; //The name of the current obj mesh
  102150. var increment = 1; //Id for meshes created by the multimaterial
  102151. var isFirstMaterial = true;
  102152. /**
  102153. * Search for obj in the given array.
  102154. * This function is called to check if a couple of data already exists in an array.
  102155. *
  102156. * If found, returns the index of the founded tuple index. Returns -1 if not found
  102157. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  102158. * @param obj Array<number>
  102159. * @returns {boolean}
  102160. */
  102161. var isInArray = function (arr, obj) {
  102162. if (!arr[obj[0]])
  102163. arr[obj[0]] = { normals: [], idx: [] };
  102164. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  102165. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  102166. };
  102167. var isInArrayUV = function (arr, obj) {
  102168. if (!arr[obj[0]])
  102169. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  102170. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  102171. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  102172. return arr[obj[0]].idx[idx];
  102173. }
  102174. return -1;
  102175. };
  102176. /**
  102177. * This function set the data for each triangle.
  102178. * Data are position, normals and uvs
  102179. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  102180. * If the tuple already exist, add only their indice
  102181. *
  102182. * @param indicePositionFromObj Integer The index in positions array
  102183. * @param indiceUvsFromObj Integer The index in uvs array
  102184. * @param indiceNormalFromObj Integer The index in normals array
  102185. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  102186. * @param textureVectorFromOBJ Vector3 The value of uvs
  102187. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  102188. */
  102189. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  102190. //Check if this tuple already exists in the list of tuples
  102191. var _index;
  102192. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  102193. _index = isInArrayUV(tuplePosNorm, [
  102194. indicePositionFromObj,
  102195. indiceNormalFromObj,
  102196. indiceUvsFromObj
  102197. ]);
  102198. }
  102199. else {
  102200. _index = isInArray(tuplePosNorm, [
  102201. indicePositionFromObj,
  102202. indiceNormalFromObj
  102203. ]);
  102204. }
  102205. //If it not exists
  102206. if (_index == -1) {
  102207. //Add an new indice.
  102208. //The array of indices is only an array with his length equal to the number of triangles - 1.
  102209. //We add vertices data in this order
  102210. indicesForBabylon.push(wrappedPositionForBabylon.length);
  102211. //Push the position of vertice for Babylon
  102212. //Each element is a BABYLON.Vector3(x,y,z)
  102213. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  102214. //Push the uvs for Babylon
  102215. //Each element is a BABYLON.Vector3(u,v)
  102216. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  102217. //Push the normals for Babylon
  102218. //Each element is a BABYLON.Vector3(x,y,z)
  102219. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  102220. //Add the tuple in the comparison list
  102221. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  102222. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  102223. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  102224. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  102225. }
  102226. else {
  102227. //The tuple already exists
  102228. //Add the index of the already existing tuple
  102229. //At this index we can get the value of position, normal and uvs of vertex
  102230. indicesForBabylon.push(_index);
  102231. }
  102232. };
  102233. /**
  102234. * Transform BABYLON.Vector() object onto 3 digits in an array
  102235. */
  102236. var unwrapData = function () {
  102237. //Every array has the same length
  102238. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  102239. //Push the x, y, z values of each element in the unwrapped array
  102240. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  102241. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  102242. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  102243. }
  102244. // Reset arrays for the next new meshes
  102245. wrappedPositionForBabylon = [];
  102246. wrappedNormalsForBabylon = [];
  102247. wrappedUvsForBabylon = [];
  102248. tuplePosNorm = [];
  102249. curPositionInIndices = 0;
  102250. };
  102251. /**
  102252. * Create triangles from polygons by recursion
  102253. * The best to understand how it works is to draw it in the same time you get the recursion.
  102254. * It is important to notice that a triangle is a polygon
  102255. * We get 4 patterns of face defined in OBJ File :
  102256. * facePattern1 = ["1","2","3","4","5","6"]
  102257. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  102258. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  102259. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  102260. * Each pattern is divided by the same method
  102261. * @param face Array[String] The indices of elements
  102262. * @param v Integer The variable to increment
  102263. */
  102264. var getTriangles = function (face, v) {
  102265. //Work for each element of the array
  102266. if (v + 1 < face.length) {
  102267. //Add on the triangle variable the indexes to obtain triangles
  102268. triangles.push(face[0], face[v], face[v + 1]);
  102269. //Incrementation for recursion
  102270. v += 1;
  102271. //Recursion
  102272. getTriangles(face, v);
  102273. }
  102274. //Result obtained after 2 iterations:
  102275. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  102276. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  102277. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  102278. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  102279. };
  102280. /**
  102281. * Create triangles and push the data for each polygon for the pattern 1
  102282. * In this pattern we get vertice positions
  102283. * @param face
  102284. * @param v
  102285. */
  102286. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  102287. //Get the indices of triangles for each polygon
  102288. getTriangles(face, v);
  102289. //For each element in the triangles array.
  102290. //This var could contains 1 to an infinity of triangles
  102291. for (var k = 0; k < triangles.length; k++) {
  102292. // Set position indice
  102293. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  102294. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  102295. positions[indicePositionFromObj], //Get the vectors data
  102296. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  102297. );
  102298. }
  102299. //Reset variable for the next line
  102300. triangles = [];
  102301. };
  102302. /**
  102303. * Create triangles and push the data for each polygon for the pattern 2
  102304. * In this pattern we get vertice positions and uvsu
  102305. * @param face
  102306. * @param v
  102307. */
  102308. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  102309. //Get the indices of triangles for each polygon
  102310. getTriangles(face, v);
  102311. for (var k = 0; k < triangles.length; k++) {
  102312. //triangle[k] = "1/1"
  102313. //Split the data for getting position and uv
  102314. var point = triangles[k].split("/"); // ["1", "1"]
  102315. //Set position indice
  102316. var indicePositionFromObj = parseInt(point[0]) - 1;
  102317. //Set uv indice
  102318. var indiceUvsFromObj = parseInt(point[1]) - 1;
  102319. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  102320. positions[indicePositionFromObj], //Get the values for each element
  102321. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  102322. );
  102323. }
  102324. //Reset variable for the next line
  102325. triangles = [];
  102326. };
  102327. /**
  102328. * Create triangles and push the data for each polygon for the pattern 3
  102329. * In this pattern we get vertice positions, uvs and normals
  102330. * @param face
  102331. * @param v
  102332. */
  102333. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  102334. //Get the indices of triangles for each polygon
  102335. getTriangles(face, v);
  102336. for (var k = 0; k < triangles.length; k++) {
  102337. //triangle[k] = "1/1/1"
  102338. //Split the data for getting position, uv, and normals
  102339. var point = triangles[k].split("/"); // ["1", "1", "1"]
  102340. // Set position indice
  102341. var indicePositionFromObj = parseInt(point[0]) - 1;
  102342. // Set uv indice
  102343. var indiceUvsFromObj = parseInt(point[1]) - 1;
  102344. // Set normal indice
  102345. var indiceNormalFromObj = parseInt(point[2]) - 1;
  102346. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  102347. );
  102348. }
  102349. //Reset variable for the next line
  102350. triangles = [];
  102351. };
  102352. /**
  102353. * Create triangles and push the data for each polygon for the pattern 4
  102354. * In this pattern we get vertice positions and normals
  102355. * @param face
  102356. * @param v
  102357. */
  102358. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  102359. getTriangles(face, v);
  102360. for (var k = 0; k < triangles.length; k++) {
  102361. //triangle[k] = "1//1"
  102362. //Split the data for getting position and normals
  102363. var point = triangles[k].split("//"); // ["1", "1"]
  102364. // We check indices, and normals
  102365. var indicePositionFromObj = parseInt(point[0]) - 1;
  102366. var indiceNormalFromObj = parseInt(point[1]) - 1;
  102367. setData(indicePositionFromObj, 1, //Default value for uv
  102368. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  102369. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  102370. }
  102371. //Reset variable for the next line
  102372. triangles = [];
  102373. };
  102374. var addPreviousObjMesh = function () {
  102375. //Check if it is not the first mesh. Otherwise we don't have data.
  102376. if (meshesFromObj.length > 0) {
  102377. //Get the previous mesh for applying the data about the faces
  102378. //=> in obj file, faces definition append after the name of the mesh
  102379. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  102380. //Set the data into Array for the mesh
  102381. unwrapData();
  102382. // Reverse tab. Otherwise face are displayed in the wrong sens
  102383. indicesForBabylon.reverse();
  102384. //Set the information for the mesh
  102385. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  102386. handledMesh.indices = indicesForBabylon.slice();
  102387. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  102388. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  102389. handledMesh.uvs = unwrappedUVForBabylon.slice();
  102390. //Reset the array for the next mesh
  102391. indicesForBabylon = [];
  102392. unwrappedPositionsForBabylon = [];
  102393. unwrappedNormalsForBabylon = [];
  102394. unwrappedUVForBabylon = [];
  102395. }
  102396. };
  102397. //Main function
  102398. //Split the file into lines
  102399. var lines = data.split('\n');
  102400. //Look at each line
  102401. for (var i = 0; i < lines.length; i++) {
  102402. var line = lines[i].trim();
  102403. var result;
  102404. //Comment or newLine
  102405. if (line.length === 0 || line.charAt(0) === '#') {
  102406. continue;
  102407. //Get information about one position possible for the vertices
  102408. }
  102409. else if ((result = this.vertexPattern.exec(line)) !== null) {
  102410. //Create a Vector3 with the position x, y, z
  102411. //Value of result:
  102412. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  102413. //Add the Vector in the list of positions
  102414. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  102415. }
  102416. else if ((result = this.normalPattern.exec(line)) !== null) {
  102417. //Create a Vector3 with the normals x, y, z
  102418. //Value of result
  102419. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  102420. //Add the Vector in the list of normals
  102421. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  102422. }
  102423. else if ((result = this.uvPattern.exec(line)) !== null) {
  102424. //Create a Vector2 with the normals u, v
  102425. //Value of result
  102426. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  102427. //Add the Vector in the list of uvs
  102428. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  102429. //Identify patterns of faces
  102430. //Face could be defined in different type of pattern
  102431. }
  102432. else if ((result = this.facePattern3.exec(line)) !== null) {
  102433. //Value of result:
  102434. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  102435. //Set the data for this face
  102436. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  102437. 1);
  102438. }
  102439. else if ((result = this.facePattern4.exec(line)) !== null) {
  102440. //Value of result:
  102441. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  102442. //Set the data for this face
  102443. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  102444. 1);
  102445. }
  102446. else if ((result = this.facePattern2.exec(line)) !== null) {
  102447. //Value of result:
  102448. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  102449. //Set the data for this face
  102450. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  102451. 1);
  102452. }
  102453. else if ((result = this.facePattern1.exec(line)) !== null) {
  102454. //Value of result
  102455. //["f 1 2 3", "1 2 3"...]
  102456. //Set the data for this face
  102457. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  102458. 1);
  102459. //Define a mesh or an object
  102460. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  102461. }
  102462. else if (this.group.test(line) || this.obj.test(line)) {
  102463. //Create a new mesh corresponding to the name of the group.
  102464. //Definition of the mesh
  102465. var objMesh =
  102466. //Set the name of the current obj mesh
  102467. {
  102468. name: line.substring(2).trim(),
  102469. indices: undefined,
  102470. positions: undefined,
  102471. normals: undefined,
  102472. uvs: undefined,
  102473. materialName: ""
  102474. };
  102475. addPreviousObjMesh();
  102476. //Push the last mesh created with only the name
  102477. meshesFromObj.push(objMesh);
  102478. //Set this variable to indicate that now meshesFromObj has objects defined inside
  102479. hasMeshes = true;
  102480. isFirstMaterial = true;
  102481. increment = 1;
  102482. //Keyword for applying a material
  102483. }
  102484. else if (this.usemtl.test(line)) {
  102485. //Get the name of the material
  102486. materialNameFromObj = line.substring(7).trim();
  102487. //If this new material is in the same mesh
  102488. if (!isFirstMaterial) {
  102489. //Set the data for the previous mesh
  102490. addPreviousObjMesh();
  102491. //Create a new mesh
  102492. var objMesh =
  102493. //Set the name of the current obj mesh
  102494. {
  102495. name: objMeshName + "_mm" + increment.toString(),
  102496. indices: undefined,
  102497. positions: undefined,
  102498. normals: undefined,
  102499. uvs: undefined,
  102500. materialName: materialNameFromObj
  102501. };
  102502. increment++;
  102503. //If meshes are already defined
  102504. meshesFromObj.push(objMesh);
  102505. }
  102506. //Set the material name if the previous line define a mesh
  102507. if (hasMeshes && isFirstMaterial) {
  102508. //Set the material name to the previous mesh (1 material per mesh)
  102509. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  102510. isFirstMaterial = false;
  102511. }
  102512. //Keyword for loading the mtl file
  102513. }
  102514. else if (this.mtllib.test(line)) {
  102515. //Get the name of mtl file
  102516. fileToLoad = line.substring(7).trim();
  102517. //Apply smoothing
  102518. }
  102519. else if (this.smooth.test(line)) {
  102520. // smooth shading => apply smoothing
  102521. //Toda y I don't know it work with babylon and with obj.
  102522. //With the obj file an integer is set
  102523. }
  102524. else {
  102525. //If there is another possibility
  102526. console.log("Unhandled expression at line : " + line);
  102527. }
  102528. }
  102529. //At the end of the file, add the last mesh into the meshesFromObj array
  102530. if (hasMeshes) {
  102531. //Set the data for the last mesh
  102532. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  102533. //Reverse indices for displaying faces in the good sens
  102534. indicesForBabylon.reverse();
  102535. //Get the good array
  102536. unwrapData();
  102537. //Set array
  102538. handledMesh.indices = indicesForBabylon;
  102539. handledMesh.positions = unwrappedPositionsForBabylon;
  102540. handledMesh.normals = unwrappedNormalsForBabylon;
  102541. handledMesh.uvs = unwrappedUVForBabylon;
  102542. }
  102543. //If any o or g keyword found, create a mesj with a random id
  102544. if (!hasMeshes) {
  102545. // reverse tab of indices
  102546. indicesForBabylon.reverse();
  102547. //Get positions normals uvs
  102548. unwrapData();
  102549. //Set data for one mesh
  102550. meshesFromObj.push({
  102551. name: BABYLON.Geometry.RandomId(),
  102552. indices: indicesForBabylon,
  102553. positions: unwrappedPositionsForBabylon,
  102554. normals: unwrappedNormalsForBabylon,
  102555. uvs: unwrappedUVForBabylon,
  102556. materialName: materialNameFromObj
  102557. });
  102558. }
  102559. //Create a BABYLON.Mesh list
  102560. var babylonMeshesArray = []; //The mesh for babylon
  102561. var materialToUse = new Array();
  102562. //Set data for each mesh
  102563. for (var j = 0; j < meshesFromObj.length; j++) {
  102564. //check meshesNames (stlFileLoader)
  102565. if (meshesNames && meshesFromObj[j].name) {
  102566. if (meshesNames instanceof Array) {
  102567. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  102568. continue;
  102569. }
  102570. }
  102571. else {
  102572. if (meshesFromObj[j].name !== meshesNames) {
  102573. continue;
  102574. }
  102575. }
  102576. }
  102577. //Get the current mesh
  102578. //Set the data with VertexBuffer for each mesh
  102579. handledMesh = meshesFromObj[j];
  102580. //Create a BABYLON.Mesh with the name of the obj mesh
  102581. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  102582. //Push the name of the material to an array
  102583. //This is indispensable for the importMesh function
  102584. materialToUse.push(meshesFromObj[j].materialName);
  102585. var vertexData = new BABYLON.VertexData(); //The container for the values
  102586. //Set the data for the babylonMesh
  102587. vertexData.positions = handledMesh.positions;
  102588. vertexData.normals = handledMesh.normals;
  102589. vertexData.uvs = handledMesh.uvs;
  102590. vertexData.indices = handledMesh.indices;
  102591. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  102592. vertexData.applyToMesh(babylonMesh);
  102593. if (OBJFileLoader.INVERT_Y) {
  102594. babylonMesh.scaling.y *= -1;
  102595. }
  102596. //Push the mesh into an array
  102597. babylonMeshesArray.push(babylonMesh);
  102598. }
  102599. //load the materials
  102600. //Check if we have a file to load
  102601. if (fileToLoad !== "") {
  102602. //Load the file synchronously
  102603. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  102604. //Create materials thanks MTLLoader function
  102605. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  102606. //Look at each material loaded in the mtl file
  102607. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  102608. //Three variables to get all meshes with the same material
  102609. var startIndex = 0;
  102610. var _indices = [];
  102611. var _index;
  102612. //The material from MTL file is used in the meshes loaded
  102613. //Push the indice in an array
  102614. //Check if the material is not used for another mesh
  102615. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  102616. _indices.push(_index);
  102617. startIndex = _index + 1;
  102618. }
  102619. //If the material is not used dispose it
  102620. if (_index == -1 && _indices.length == 0) {
  102621. //If the material is not needed, remove it
  102622. materialsFromMTLFile.materials[n].dispose();
  102623. }
  102624. else {
  102625. for (var o = 0; o < _indices.length; o++) {
  102626. //Apply the material to the BABYLON.Mesh for each mesh with the material
  102627. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  102628. }
  102629. }
  102630. }
  102631. });
  102632. }
  102633. //Return an array with all BABYLON.Mesh
  102634. return babylonMeshesArray;
  102635. };
  102636. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  102637. OBJFileLoader.INVERT_Y = false;
  102638. return OBJFileLoader;
  102639. }());
  102640. BABYLON.OBJFileLoader = OBJFileLoader;
  102641. if (BABYLON.SceneLoader) {
  102642. //Add this loader into the register plugin
  102643. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  102644. }
  102645. })(BABYLON || (BABYLON = {}));
  102646. //# sourceMappingURL=babylon.objFileLoader.js.map
  102647. var BABYLON;
  102648. (function (BABYLON) {
  102649. /**
  102650. * Mode that determines the coordinate system to use.
  102651. */
  102652. var GLTFLoaderCoordinateSystemMode;
  102653. (function (GLTFLoaderCoordinateSystemMode) {
  102654. /**
  102655. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  102656. */
  102657. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  102658. /**
  102659. * Sets the useRightHandedSystem flag on the scene.
  102660. */
  102661. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  102662. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  102663. /**
  102664. * Mode that determines what animations will start.
  102665. */
  102666. var GLTFLoaderAnimationStartMode;
  102667. (function (GLTFLoaderAnimationStartMode) {
  102668. /**
  102669. * No animation will start.
  102670. */
  102671. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  102672. /**
  102673. * The first animation will start.
  102674. */
  102675. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  102676. /**
  102677. * All animations will start.
  102678. */
  102679. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  102680. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  102681. /**
  102682. * Loader state.
  102683. */
  102684. var GLTFLoaderState;
  102685. (function (GLTFLoaderState) {
  102686. /**
  102687. * The asset is loading.
  102688. */
  102689. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  102690. /**
  102691. * The asset is ready for rendering.
  102692. */
  102693. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  102694. /**
  102695. * The asset is completely loaded.
  102696. */
  102697. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  102698. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  102699. /**
  102700. * File loader for loading glTF files into a scene.
  102701. */
  102702. var GLTFFileLoader = /** @class */ (function () {
  102703. function GLTFFileLoader() {
  102704. // #region Common options
  102705. /**
  102706. * Raised when the asset has been parsed
  102707. */
  102708. this.onParsedObservable = new BABYLON.Observable();
  102709. // #endregion
  102710. // #region V2 options
  102711. /**
  102712. * The coordinate system mode. Defaults to AUTO.
  102713. */
  102714. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  102715. /**
  102716. * The animation start mode. Defaults to FIRST.
  102717. */
  102718. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  102719. /**
  102720. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  102721. */
  102722. this.compileMaterials = false;
  102723. /**
  102724. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  102725. */
  102726. this.useClipPlane = false;
  102727. /**
  102728. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  102729. */
  102730. this.compileShadowGenerators = false;
  102731. /**
  102732. * Defines if the Alpha blended materials are only applied as coverage.
  102733. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  102734. * If true, no extra effects are applied to transparent pixels.
  102735. */
  102736. this.transparencyAsCoverage = false;
  102737. /** @hidden */
  102738. this._normalizeAnimationGroupsToBeginAtZero = true;
  102739. /**
  102740. * Function called before loading a url referenced by the asset.
  102741. */
  102742. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  102743. /**
  102744. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  102745. */
  102746. this.onMeshLoadedObservable = new BABYLON.Observable();
  102747. /**
  102748. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  102749. */
  102750. this.onTextureLoadedObservable = new BABYLON.Observable();
  102751. /**
  102752. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  102753. */
  102754. this.onMaterialLoadedObservable = new BABYLON.Observable();
  102755. /**
  102756. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  102757. */
  102758. this.onCameraLoadedObservable = new BABYLON.Observable();
  102759. /**
  102760. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  102761. * For assets with LODs, raised when all of the LODs are complete.
  102762. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  102763. */
  102764. this.onCompleteObservable = new BABYLON.Observable();
  102765. /**
  102766. * Observable raised after the loader is disposed.
  102767. */
  102768. this.onDisposeObservable = new BABYLON.Observable();
  102769. /**
  102770. * Observable raised after a loader extension is created.
  102771. * Set additional options for a loader extension in this event.
  102772. */
  102773. this.onExtensionLoadedObservable = new BABYLON.Observable();
  102774. // #endregion
  102775. this._loader = null;
  102776. /**
  102777. * Name of the loader ("gltf")
  102778. */
  102779. this.name = "gltf";
  102780. /**
  102781. * Supported file extensions of the loader (.gltf, .glb)
  102782. */
  102783. this.extensions = {
  102784. ".gltf": { isBinary: false },
  102785. ".glb": { isBinary: true }
  102786. };
  102787. }
  102788. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  102789. /**
  102790. * Raised when the asset has been parsed
  102791. */
  102792. set: function (callback) {
  102793. if (this._onParsedObserver) {
  102794. this.onParsedObservable.remove(this._onParsedObserver);
  102795. }
  102796. this._onParsedObserver = this.onParsedObservable.add(callback);
  102797. },
  102798. enumerable: true,
  102799. configurable: true
  102800. });
  102801. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  102802. /**
  102803. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  102804. */
  102805. set: function (callback) {
  102806. if (this._onMeshLoadedObserver) {
  102807. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  102808. }
  102809. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  102810. },
  102811. enumerable: true,
  102812. configurable: true
  102813. });
  102814. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  102815. /**
  102816. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  102817. */
  102818. set: function (callback) {
  102819. if (this._onTextureLoadedObserver) {
  102820. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  102821. }
  102822. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  102823. },
  102824. enumerable: true,
  102825. configurable: true
  102826. });
  102827. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  102828. /**
  102829. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  102830. */
  102831. set: function (callback) {
  102832. if (this._onMaterialLoadedObserver) {
  102833. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  102834. }
  102835. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  102836. },
  102837. enumerable: true,
  102838. configurable: true
  102839. });
  102840. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  102841. /**
  102842. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  102843. */
  102844. set: function (callback) {
  102845. if (this._onCameraLoadedObserver) {
  102846. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  102847. }
  102848. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  102849. },
  102850. enumerable: true,
  102851. configurable: true
  102852. });
  102853. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  102854. /**
  102855. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  102856. */
  102857. set: function (callback) {
  102858. if (this._onCompleteObserver) {
  102859. this.onCompleteObservable.remove(this._onCompleteObserver);
  102860. }
  102861. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  102862. },
  102863. enumerable: true,
  102864. configurable: true
  102865. });
  102866. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  102867. /**
  102868. * Callback raised after the loader is disposed.
  102869. */
  102870. set: function (callback) {
  102871. if (this._onDisposeObserver) {
  102872. this.onDisposeObservable.remove(this._onDisposeObserver);
  102873. }
  102874. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  102875. },
  102876. enumerable: true,
  102877. configurable: true
  102878. });
  102879. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  102880. /**
  102881. * Callback raised after a loader extension is created.
  102882. */
  102883. set: function (callback) {
  102884. if (this._onExtensionLoadedObserver) {
  102885. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  102886. }
  102887. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  102888. },
  102889. enumerable: true,
  102890. configurable: true
  102891. });
  102892. /**
  102893. * Returns a promise that resolves when the asset is completely loaded.
  102894. * @returns a promise that resolves when the asset is completely loaded.
  102895. */
  102896. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  102897. var _this = this;
  102898. return new Promise(function (resolve) {
  102899. _this.onCompleteObservable.addOnce(function () {
  102900. resolve();
  102901. });
  102902. });
  102903. };
  102904. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  102905. /**
  102906. * The loader state or null if the loader is not active.
  102907. */
  102908. get: function () {
  102909. return this._loader ? this._loader.state : null;
  102910. },
  102911. enumerable: true,
  102912. configurable: true
  102913. });
  102914. /**
  102915. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  102916. */
  102917. GLTFFileLoader.prototype.dispose = function () {
  102918. if (this._loader) {
  102919. this._loader.dispose();
  102920. this._loader = null;
  102921. }
  102922. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  102923. this.onMeshLoadedObservable.clear();
  102924. this.onTextureLoadedObservable.clear();
  102925. this.onMaterialLoadedObservable.clear();
  102926. this.onCameraLoadedObservable.clear();
  102927. this.onCompleteObservable.clear();
  102928. this.onExtensionLoadedObservable.clear();
  102929. this.onDisposeObservable.notifyObservers(this);
  102930. this.onDisposeObservable.clear();
  102931. };
  102932. /**
  102933. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  102934. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  102935. * @param scene the scene the meshes should be added to
  102936. * @param data the glTF data to load
  102937. * @param rootUrl root url to load from
  102938. * @param onProgress event that fires when loading progress has occured
  102939. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  102940. */
  102941. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  102942. var _this = this;
  102943. return Promise.resolve().then(function () {
  102944. var loaderData = _this._parse(data);
  102945. _this._loader = _this._getLoader(loaderData);
  102946. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  102947. });
  102948. };
  102949. /**
  102950. * Imports all objects from the loaded glTF data and adds them to the scene
  102951. * @param scene the scene the objects should be added to
  102952. * @param data the glTF data to load
  102953. * @param rootUrl root url to load from
  102954. * @param onProgress event that fires when loading progress has occured
  102955. * @returns a promise which completes when objects have been loaded to the scene
  102956. */
  102957. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  102958. var _this = this;
  102959. return Promise.resolve().then(function () {
  102960. var loaderData = _this._parse(data);
  102961. _this._loader = _this._getLoader(loaderData);
  102962. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  102963. });
  102964. };
  102965. /**
  102966. * Load into an asset container.
  102967. * @param scene The scene to load into
  102968. * @param data The data to import
  102969. * @param rootUrl The root url for scene and resources
  102970. * @param onProgress The callback when the load progresses
  102971. * @returns The loaded asset container
  102972. */
  102973. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  102974. var _this = this;
  102975. return Promise.resolve().then(function () {
  102976. var loaderData = _this._parse(data);
  102977. _this._loader = _this._getLoader(loaderData);
  102978. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  102979. var container = new BABYLON.AssetContainer(scene);
  102980. Array.prototype.push.apply(container.meshes, result.meshes);
  102981. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  102982. Array.prototype.push.apply(container.skeletons, result.skeletons);
  102983. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  102984. container.removeAllFromScene();
  102985. return container;
  102986. });
  102987. });
  102988. };
  102989. /**
  102990. * If the data string can be loaded directly.
  102991. * @param data string contianing the file data
  102992. * @returns if the data can be loaded directly
  102993. */
  102994. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  102995. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  102996. };
  102997. /**
  102998. * Instantiates a glTF file loader plugin.
  102999. * @returns the created plugin
  103000. */
  103001. GLTFFileLoader.prototype.createPlugin = function () {
  103002. return new GLTFFileLoader();
  103003. };
  103004. GLTFFileLoader.prototype._parse = function (data) {
  103005. var parsedData;
  103006. if (data instanceof ArrayBuffer) {
  103007. parsedData = GLTFFileLoader._parseBinary(data);
  103008. }
  103009. else {
  103010. parsedData = {
  103011. json: JSON.parse(data),
  103012. bin: null
  103013. };
  103014. }
  103015. this.onParsedObservable.notifyObservers(parsedData);
  103016. this.onParsedObservable.clear();
  103017. return parsedData;
  103018. };
  103019. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  103020. var _this = this;
  103021. var loaderVersion = { major: 2, minor: 0 };
  103022. var asset = loaderData.json.asset || {};
  103023. var version = GLTFFileLoader._parseVersion(asset.version);
  103024. if (!version) {
  103025. throw new Error("Invalid version: " + asset.version);
  103026. }
  103027. if (asset.minVersion !== undefined) {
  103028. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  103029. if (!minVersion) {
  103030. throw new Error("Invalid minimum version: " + asset.minVersion);
  103031. }
  103032. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  103033. throw new Error("Incompatible minimum version: " + asset.minVersion);
  103034. }
  103035. }
  103036. var createLoaders = {
  103037. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  103038. 2: GLTFFileLoader.CreateGLTFLoaderV2
  103039. };
  103040. var createLoader = createLoaders[version.major];
  103041. if (!createLoader) {
  103042. throw new Error("Unsupported version: " + asset.version);
  103043. }
  103044. var loader = createLoader();
  103045. loader.coordinateSystemMode = this.coordinateSystemMode;
  103046. loader.animationStartMode = this.animationStartMode;
  103047. loader.compileMaterials = this.compileMaterials;
  103048. loader.useClipPlane = this.useClipPlane;
  103049. loader.compileShadowGenerators = this.compileShadowGenerators;
  103050. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  103051. loader._normalizeAnimationGroupsToBeginAtZero = this._normalizeAnimationGroupsToBeginAtZero;
  103052. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  103053. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  103054. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  103055. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  103056. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  103057. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  103058. loader.onCompleteObservable.add(function () {
  103059. _this.onMeshLoadedObservable.clear();
  103060. _this.onTextureLoadedObservable.clear();
  103061. _this.onMaterialLoadedObservable.clear();
  103062. _this.onCameraLoadedObservable.clear();
  103063. _this.onExtensionLoadedObservable.clear();
  103064. _this.onCompleteObservable.notifyObservers(_this);
  103065. _this.onCompleteObservable.clear();
  103066. });
  103067. return loader;
  103068. };
  103069. GLTFFileLoader._parseBinary = function (data) {
  103070. var Binary = {
  103071. Magic: 0x46546C67
  103072. };
  103073. var binaryReader = new BinaryReader(data);
  103074. var magic = binaryReader.readUint32();
  103075. if (magic !== Binary.Magic) {
  103076. throw new Error("Unexpected magic: " + magic);
  103077. }
  103078. var version = binaryReader.readUint32();
  103079. switch (version) {
  103080. case 1: return GLTFFileLoader._parseV1(binaryReader);
  103081. case 2: return GLTFFileLoader._parseV2(binaryReader);
  103082. }
  103083. throw new Error("Unsupported version: " + version);
  103084. };
  103085. GLTFFileLoader._parseV1 = function (binaryReader) {
  103086. var ContentFormat = {
  103087. JSON: 0
  103088. };
  103089. var length = binaryReader.readUint32();
  103090. if (length != binaryReader.getLength()) {
  103091. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  103092. }
  103093. var contentLength = binaryReader.readUint32();
  103094. var contentFormat = binaryReader.readUint32();
  103095. var content;
  103096. switch (contentFormat) {
  103097. case ContentFormat.JSON: {
  103098. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  103099. break;
  103100. }
  103101. default: {
  103102. throw new Error("Unexpected content format: " + contentFormat);
  103103. }
  103104. }
  103105. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  103106. var body = binaryReader.readUint8Array(bytesRemaining);
  103107. return {
  103108. json: content,
  103109. bin: body
  103110. };
  103111. };
  103112. GLTFFileLoader._parseV2 = function (binaryReader) {
  103113. var ChunkFormat = {
  103114. JSON: 0x4E4F534A,
  103115. BIN: 0x004E4942
  103116. };
  103117. var length = binaryReader.readUint32();
  103118. if (length !== binaryReader.getLength()) {
  103119. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  103120. }
  103121. // JSON chunk
  103122. var chunkLength = binaryReader.readUint32();
  103123. var chunkFormat = binaryReader.readUint32();
  103124. if (chunkFormat !== ChunkFormat.JSON) {
  103125. throw new Error("First chunk format is not JSON");
  103126. }
  103127. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  103128. // Look for BIN chunk
  103129. var bin = null;
  103130. while (binaryReader.getPosition() < binaryReader.getLength()) {
  103131. var chunkLength_1 = binaryReader.readUint32();
  103132. var chunkFormat_1 = binaryReader.readUint32();
  103133. switch (chunkFormat_1) {
  103134. case ChunkFormat.JSON: {
  103135. throw new Error("Unexpected JSON chunk");
  103136. }
  103137. case ChunkFormat.BIN: {
  103138. bin = binaryReader.readUint8Array(chunkLength_1);
  103139. break;
  103140. }
  103141. default: {
  103142. // ignore unrecognized chunkFormat
  103143. binaryReader.skipBytes(chunkLength_1);
  103144. break;
  103145. }
  103146. }
  103147. }
  103148. return {
  103149. json: json,
  103150. bin: bin
  103151. };
  103152. };
  103153. GLTFFileLoader._parseVersion = function (version) {
  103154. if (version === "1.0" || version === "1.0.1") {
  103155. return {
  103156. major: 1,
  103157. minor: 0
  103158. };
  103159. }
  103160. var match = (version + "").match(/^(\d+)\.(\d+)/);
  103161. if (!match) {
  103162. return null;
  103163. }
  103164. return {
  103165. major: parseInt(match[1]),
  103166. minor: parseInt(match[2])
  103167. };
  103168. };
  103169. GLTFFileLoader._compareVersion = function (a, b) {
  103170. if (a.major > b.major)
  103171. return 1;
  103172. if (a.major < b.major)
  103173. return -1;
  103174. if (a.minor > b.minor)
  103175. return 1;
  103176. if (a.minor < b.minor)
  103177. return -1;
  103178. return 0;
  103179. };
  103180. GLTFFileLoader._decodeBufferToText = function (buffer) {
  103181. var result = "";
  103182. var length = buffer.byteLength;
  103183. for (var i = 0; i < length; i++) {
  103184. result += String.fromCharCode(buffer[i]);
  103185. }
  103186. return result;
  103187. };
  103188. // #endregion
  103189. // #region V1 options
  103190. /**
  103191. * 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.
  103192. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  103193. * Defaults to true.
  103194. */
  103195. GLTFFileLoader.IncrementalLoading = true;
  103196. /**
  103197. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  103198. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  103199. */
  103200. GLTFFileLoader.HomogeneousCoordinates = false;
  103201. return GLTFFileLoader;
  103202. }());
  103203. BABYLON.GLTFFileLoader = GLTFFileLoader;
  103204. var BinaryReader = /** @class */ (function () {
  103205. function BinaryReader(arrayBuffer) {
  103206. this._arrayBuffer = arrayBuffer;
  103207. this._dataView = new DataView(arrayBuffer);
  103208. this._byteOffset = 0;
  103209. }
  103210. BinaryReader.prototype.getPosition = function () {
  103211. return this._byteOffset;
  103212. };
  103213. BinaryReader.prototype.getLength = function () {
  103214. return this._arrayBuffer.byteLength;
  103215. };
  103216. BinaryReader.prototype.readUint32 = function () {
  103217. var value = this._dataView.getUint32(this._byteOffset, true);
  103218. this._byteOffset += 4;
  103219. return value;
  103220. };
  103221. BinaryReader.prototype.readUint8Array = function (length) {
  103222. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  103223. this._byteOffset += length;
  103224. return value;
  103225. };
  103226. BinaryReader.prototype.skipBytes = function (length) {
  103227. this._byteOffset += length;
  103228. };
  103229. return BinaryReader;
  103230. }());
  103231. if (BABYLON.SceneLoader) {
  103232. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  103233. }
  103234. })(BABYLON || (BABYLON = {}));
  103235. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  103236. var BABYLON;
  103237. (function (BABYLON) {
  103238. var GLTF1;
  103239. (function (GLTF1) {
  103240. /**
  103241. * Enums
  103242. */
  103243. var EComponentType;
  103244. (function (EComponentType) {
  103245. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  103246. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  103247. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  103248. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  103249. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  103250. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  103251. var EShaderType;
  103252. (function (EShaderType) {
  103253. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  103254. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  103255. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  103256. var EParameterType;
  103257. (function (EParameterType) {
  103258. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  103259. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  103260. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  103261. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  103262. EParameterType[EParameterType["INT"] = 5124] = "INT";
  103263. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  103264. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  103265. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  103266. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  103267. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  103268. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  103269. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  103270. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  103271. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  103272. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  103273. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  103274. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  103275. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  103276. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  103277. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  103278. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  103279. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  103280. var ETextureWrapMode;
  103281. (function (ETextureWrapMode) {
  103282. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  103283. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  103284. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  103285. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  103286. var ETextureFilterType;
  103287. (function (ETextureFilterType) {
  103288. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  103289. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  103290. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  103291. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  103292. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  103293. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  103294. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  103295. var ETextureFormat;
  103296. (function (ETextureFormat) {
  103297. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  103298. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  103299. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  103300. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  103301. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  103302. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  103303. var ECullingType;
  103304. (function (ECullingType) {
  103305. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  103306. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  103307. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  103308. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  103309. var EBlendingFunction;
  103310. (function (EBlendingFunction) {
  103311. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  103312. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  103313. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  103314. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  103315. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  103316. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  103317. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  103318. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  103319. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  103320. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  103321. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  103322. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  103323. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  103324. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  103325. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  103326. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  103327. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103328. })(BABYLON || (BABYLON = {}));
  103329. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  103330. var BABYLON;
  103331. (function (BABYLON) {
  103332. var GLTF1;
  103333. (function (GLTF1) {
  103334. /**
  103335. * Tokenizer. Used for shaders compatibility
  103336. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  103337. */
  103338. var ETokenType;
  103339. (function (ETokenType) {
  103340. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  103341. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  103342. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  103343. })(ETokenType || (ETokenType = {}));
  103344. var Tokenizer = /** @class */ (function () {
  103345. function Tokenizer(toParse) {
  103346. this._pos = 0;
  103347. this.currentToken = ETokenType.UNKNOWN;
  103348. this.currentIdentifier = "";
  103349. this.currentString = "";
  103350. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  103351. this._toParse = toParse;
  103352. this._maxPos = toParse.length;
  103353. }
  103354. Tokenizer.prototype.getNextToken = function () {
  103355. if (this.isEnd())
  103356. return ETokenType.END_OF_INPUT;
  103357. this.currentString = this.read();
  103358. this.currentToken = ETokenType.UNKNOWN;
  103359. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  103360. this.currentToken = ETokenType.IDENTIFIER;
  103361. this.currentIdentifier = this.currentString;
  103362. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  103363. this.currentIdentifier += this.currentString;
  103364. this.forward();
  103365. }
  103366. }
  103367. return this.currentToken;
  103368. };
  103369. Tokenizer.prototype.peek = function () {
  103370. return this._toParse[this._pos];
  103371. };
  103372. Tokenizer.prototype.read = function () {
  103373. return this._toParse[this._pos++];
  103374. };
  103375. Tokenizer.prototype.forward = function () {
  103376. this._pos++;
  103377. };
  103378. Tokenizer.prototype.isEnd = function () {
  103379. return this._pos >= this._maxPos;
  103380. };
  103381. return Tokenizer;
  103382. }());
  103383. /**
  103384. * Values
  103385. */
  103386. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  103387. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  103388. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  103389. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  103390. /**
  103391. * Parse
  103392. */
  103393. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  103394. for (var buf in parsedBuffers) {
  103395. var parsedBuffer = parsedBuffers[buf];
  103396. gltfRuntime.buffers[buf] = parsedBuffer;
  103397. gltfRuntime.buffersCount++;
  103398. }
  103399. };
  103400. var parseShaders = function (parsedShaders, gltfRuntime) {
  103401. for (var sha in parsedShaders) {
  103402. var parsedShader = parsedShaders[sha];
  103403. gltfRuntime.shaders[sha] = parsedShader;
  103404. gltfRuntime.shaderscount++;
  103405. }
  103406. };
  103407. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  103408. for (var object in parsedObjects) {
  103409. var parsedObject = parsedObjects[object];
  103410. gltfRuntime[runtimeProperty][object] = parsedObject;
  103411. }
  103412. };
  103413. /**
  103414. * Utils
  103415. */
  103416. var normalizeUVs = function (buffer) {
  103417. if (!buffer) {
  103418. return;
  103419. }
  103420. for (var i = 0; i < buffer.length / 2; i++) {
  103421. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  103422. }
  103423. };
  103424. var getAttribute = function (attributeParameter) {
  103425. if (attributeParameter.semantic === "NORMAL") {
  103426. return "normal";
  103427. }
  103428. else if (attributeParameter.semantic === "POSITION") {
  103429. return "position";
  103430. }
  103431. else if (attributeParameter.semantic === "JOINT") {
  103432. return "matricesIndices";
  103433. }
  103434. else if (attributeParameter.semantic === "WEIGHT") {
  103435. return "matricesWeights";
  103436. }
  103437. else if (attributeParameter.semantic === "COLOR") {
  103438. return "color";
  103439. }
  103440. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  103441. var channel = Number(attributeParameter.semantic.split("_")[1]);
  103442. return "uv" + (channel === 0 ? "" : channel + 1);
  103443. }
  103444. return null;
  103445. };
  103446. /**
  103447. * Loads and creates animations
  103448. */
  103449. var loadAnimations = function (gltfRuntime) {
  103450. for (var anim in gltfRuntime.animations) {
  103451. var animation = gltfRuntime.animations[anim];
  103452. if (!animation.channels || !animation.samplers) {
  103453. continue;
  103454. }
  103455. var lastAnimation = null;
  103456. for (var i = 0; i < animation.channels.length; i++) {
  103457. // Get parameters and load buffers
  103458. var channel = animation.channels[i];
  103459. var sampler = animation.samplers[channel.sampler];
  103460. if (!sampler) {
  103461. continue;
  103462. }
  103463. var inputData = null;
  103464. var outputData = null;
  103465. if (animation.parameters) {
  103466. inputData = animation.parameters[sampler.input];
  103467. outputData = animation.parameters[sampler.output];
  103468. }
  103469. else {
  103470. inputData = sampler.input;
  103471. outputData = sampler.output;
  103472. }
  103473. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  103474. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  103475. var targetID = channel.target.id;
  103476. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  103477. if (targetNode === null) {
  103478. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  103479. }
  103480. if (targetNode === null) {
  103481. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  103482. continue;
  103483. }
  103484. var isBone = targetNode instanceof BABYLON.Bone;
  103485. // Get target path (position, rotation or scaling)
  103486. var targetPath = channel.target.path;
  103487. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  103488. if (targetPathIndex !== -1) {
  103489. targetPath = babylonAnimationPaths[targetPathIndex];
  103490. }
  103491. // Determine animation type
  103492. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  103493. if (!isBone) {
  103494. if (targetPath === "rotationQuaternion") {
  103495. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  103496. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  103497. }
  103498. else {
  103499. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  103500. }
  103501. }
  103502. // Create animation and key frames
  103503. var babylonAnimation = null;
  103504. var keys = [];
  103505. var arrayOffset = 0;
  103506. var modifyKey = false;
  103507. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  103508. babylonAnimation = lastAnimation;
  103509. modifyKey = true;
  103510. }
  103511. if (!modifyKey) {
  103512. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  103513. }
  103514. // For each frame
  103515. for (var j = 0; j < bufferInput.length; j++) {
  103516. var value = null;
  103517. if (targetPath === "rotationQuaternion") { // VEC4
  103518. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  103519. arrayOffset += 4;
  103520. }
  103521. else { // Position and scaling are VEC3
  103522. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  103523. arrayOffset += 3;
  103524. }
  103525. if (isBone) {
  103526. var bone = targetNode;
  103527. var translation = BABYLON.Vector3.Zero();
  103528. var rotationQuaternion = new BABYLON.Quaternion();
  103529. var scaling = BABYLON.Vector3.Zero();
  103530. // Warning on decompose
  103531. var mat = bone.getBaseMatrix();
  103532. if (modifyKey && lastAnimation) {
  103533. mat = lastAnimation.getKeys()[j].value;
  103534. }
  103535. mat.decompose(scaling, rotationQuaternion, translation);
  103536. if (targetPath === "position") {
  103537. translation = value;
  103538. }
  103539. else if (targetPath === "rotationQuaternion") {
  103540. rotationQuaternion = value;
  103541. }
  103542. else {
  103543. scaling = value;
  103544. }
  103545. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  103546. }
  103547. if (!modifyKey) {
  103548. keys.push({
  103549. frame: bufferInput[j],
  103550. value: value
  103551. });
  103552. }
  103553. else if (lastAnimation) {
  103554. lastAnimation.getKeys()[j].value = value;
  103555. }
  103556. }
  103557. // Finish
  103558. if (!modifyKey && babylonAnimation) {
  103559. babylonAnimation.setKeys(keys);
  103560. targetNode.animations.push(babylonAnimation);
  103561. }
  103562. lastAnimation = babylonAnimation;
  103563. gltfRuntime.scene.stopAnimation(targetNode);
  103564. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  103565. }
  103566. }
  103567. };
  103568. /**
  103569. * Returns the bones transformation matrix
  103570. */
  103571. var configureBoneTransformation = function (node) {
  103572. var mat = null;
  103573. if (node.translation || node.rotation || node.scale) {
  103574. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  103575. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  103576. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  103577. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  103578. }
  103579. else {
  103580. mat = BABYLON.Matrix.FromArray(node.matrix);
  103581. }
  103582. return mat;
  103583. };
  103584. /**
  103585. * Returns the parent bone
  103586. */
  103587. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  103588. // Try to find
  103589. for (var i = 0; i < newSkeleton.bones.length; i++) {
  103590. if (newSkeleton.bones[i].name === jointName) {
  103591. return newSkeleton.bones[i];
  103592. }
  103593. }
  103594. // Not found, search in gltf nodes
  103595. var nodes = gltfRuntime.nodes;
  103596. for (var nde in nodes) {
  103597. var node = nodes[nde];
  103598. if (!node.jointName) {
  103599. continue;
  103600. }
  103601. var children = node.children;
  103602. for (var i = 0; i < children.length; i++) {
  103603. var child = gltfRuntime.nodes[children[i]];
  103604. if (!child.jointName) {
  103605. continue;
  103606. }
  103607. if (child.jointName === jointName) {
  103608. var mat = configureBoneTransformation(node);
  103609. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  103610. bone.id = nde;
  103611. return bone;
  103612. }
  103613. }
  103614. }
  103615. return null;
  103616. };
  103617. /**
  103618. * Returns the appropriate root node
  103619. */
  103620. var getNodeToRoot = function (nodesToRoot, id) {
  103621. for (var i = 0; i < nodesToRoot.length; i++) {
  103622. var nodeToRoot = nodesToRoot[i];
  103623. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  103624. var child = nodeToRoot.node.children[j];
  103625. if (child === id) {
  103626. return nodeToRoot.bone;
  103627. }
  103628. }
  103629. }
  103630. return null;
  103631. };
  103632. /**
  103633. * Returns the node with the joint name
  103634. */
  103635. var getJointNode = function (gltfRuntime, jointName) {
  103636. var nodes = gltfRuntime.nodes;
  103637. var node = nodes[jointName];
  103638. if (node) {
  103639. return {
  103640. node: node,
  103641. id: jointName
  103642. };
  103643. }
  103644. for (var nde in nodes) {
  103645. node = nodes[nde];
  103646. if (node.jointName === jointName) {
  103647. return {
  103648. node: node,
  103649. id: nde
  103650. };
  103651. }
  103652. }
  103653. return null;
  103654. };
  103655. /**
  103656. * Checks if a nodes is in joints
  103657. */
  103658. var nodeIsInJoints = function (skins, id) {
  103659. for (var i = 0; i < skins.jointNames.length; i++) {
  103660. if (skins.jointNames[i] === id) {
  103661. return true;
  103662. }
  103663. }
  103664. return false;
  103665. };
  103666. /**
  103667. * Fills the nodes to root for bones and builds hierarchy
  103668. */
  103669. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  103670. // Creates nodes for root
  103671. for (var nde in gltfRuntime.nodes) {
  103672. var node = gltfRuntime.nodes[nde];
  103673. var id = nde;
  103674. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  103675. continue;
  103676. }
  103677. // Create node to root bone
  103678. var mat = configureBoneTransformation(node);
  103679. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  103680. bone.id = id;
  103681. nodesToRoot.push({ bone: bone, node: node, id: id });
  103682. }
  103683. // Parenting
  103684. for (var i = 0; i < nodesToRoot.length; i++) {
  103685. var nodeToRoot = nodesToRoot[i];
  103686. var children = nodeToRoot.node.children;
  103687. for (var j = 0; j < children.length; j++) {
  103688. var child = null;
  103689. for (var k = 0; k < nodesToRoot.length; k++) {
  103690. if (nodesToRoot[k].id === children[j]) {
  103691. child = nodesToRoot[k];
  103692. break;
  103693. }
  103694. }
  103695. if (child) {
  103696. child.bone._parent = nodeToRoot.bone;
  103697. nodeToRoot.bone.children.push(child.bone);
  103698. }
  103699. }
  103700. }
  103701. };
  103702. /**
  103703. * Imports a skeleton
  103704. */
  103705. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  103706. if (!newSkeleton) {
  103707. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  103708. }
  103709. if (!skins.babylonSkeleton) {
  103710. return newSkeleton;
  103711. }
  103712. // Find the root bones
  103713. var nodesToRoot = [];
  103714. var nodesToRootToAdd = [];
  103715. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  103716. newSkeleton.bones = [];
  103717. // Joints
  103718. for (var i = 0; i < skins.jointNames.length; i++) {
  103719. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  103720. if (!jointNode) {
  103721. continue;
  103722. }
  103723. var node = jointNode.node;
  103724. if (!node) {
  103725. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  103726. continue;
  103727. }
  103728. var id = jointNode.id;
  103729. // Optimize, if the bone already exists...
  103730. var existingBone = gltfRuntime.scene.getBoneByID(id);
  103731. if (existingBone) {
  103732. newSkeleton.bones.push(existingBone);
  103733. continue;
  103734. }
  103735. // Search for parent bone
  103736. var foundBone = false;
  103737. var parentBone = null;
  103738. for (var j = 0; j < i; j++) {
  103739. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  103740. if (!jointNode_1) {
  103741. continue;
  103742. }
  103743. var joint = jointNode_1.node;
  103744. if (!joint) {
  103745. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  103746. continue;
  103747. }
  103748. var children = joint.children;
  103749. if (!children) {
  103750. continue;
  103751. }
  103752. foundBone = false;
  103753. for (var k = 0; k < children.length; k++) {
  103754. if (children[k] === id) {
  103755. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  103756. foundBone = true;
  103757. break;
  103758. }
  103759. }
  103760. if (foundBone) {
  103761. break;
  103762. }
  103763. }
  103764. // Create bone
  103765. var mat = configureBoneTransformation(node);
  103766. if (!parentBone && nodesToRoot.length > 0) {
  103767. parentBone = getNodeToRoot(nodesToRoot, id);
  103768. if (parentBone) {
  103769. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  103770. nodesToRootToAdd.push(parentBone);
  103771. }
  103772. }
  103773. }
  103774. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  103775. bone.id = id;
  103776. }
  103777. // Polish
  103778. var bones = newSkeleton.bones;
  103779. newSkeleton.bones = [];
  103780. for (var i = 0; i < skins.jointNames.length; i++) {
  103781. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  103782. if (!jointNode) {
  103783. continue;
  103784. }
  103785. for (var j = 0; j < bones.length; j++) {
  103786. if (bones[j].id === jointNode.id) {
  103787. newSkeleton.bones.push(bones[j]);
  103788. break;
  103789. }
  103790. }
  103791. }
  103792. newSkeleton.prepare();
  103793. // Finish
  103794. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  103795. newSkeleton.bones.push(nodesToRootToAdd[i]);
  103796. }
  103797. return newSkeleton;
  103798. };
  103799. /**
  103800. * Imports a mesh and its geometries
  103801. */
  103802. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  103803. if (!newMesh) {
  103804. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  103805. newMesh.id = id;
  103806. }
  103807. if (!node.babylonNode) {
  103808. return newMesh;
  103809. }
  103810. var subMaterials = [];
  103811. var vertexData = null;
  103812. var verticesStarts = new Array();
  103813. var verticesCounts = new Array();
  103814. var indexStarts = new Array();
  103815. var indexCounts = new Array();
  103816. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  103817. var meshID = meshes[meshIndex];
  103818. var mesh = gltfRuntime.meshes[meshID];
  103819. if (!mesh) {
  103820. continue;
  103821. }
  103822. // Positions, normals and UVs
  103823. for (var i = 0; i < mesh.primitives.length; i++) {
  103824. // Temporary vertex data
  103825. var tempVertexData = new BABYLON.VertexData();
  103826. var primitive = mesh.primitives[i];
  103827. if (primitive.mode !== 4) {
  103828. // continue;
  103829. }
  103830. var attributes = primitive.attributes;
  103831. var accessor = null;
  103832. var buffer = null;
  103833. // Set positions, normal and uvs
  103834. for (var semantic in attributes) {
  103835. // Link accessor and buffer view
  103836. accessor = gltfRuntime.accessors[attributes[semantic]];
  103837. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  103838. if (semantic === "NORMAL") {
  103839. tempVertexData.normals = new Float32Array(buffer.length);
  103840. tempVertexData.normals.set(buffer);
  103841. }
  103842. else if (semantic === "POSITION") {
  103843. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  103844. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  103845. for (var j = 0; j < buffer.length; j += 4) {
  103846. tempVertexData.positions[j] = buffer[j];
  103847. tempVertexData.positions[j + 1] = buffer[j + 1];
  103848. tempVertexData.positions[j + 2] = buffer[j + 2];
  103849. }
  103850. }
  103851. else {
  103852. tempVertexData.positions = new Float32Array(buffer.length);
  103853. tempVertexData.positions.set(buffer);
  103854. }
  103855. verticesCounts.push(tempVertexData.positions.length);
  103856. }
  103857. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  103858. var channel = Number(semantic.split("_")[1]);
  103859. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  103860. var uvs = new Float32Array(buffer.length);
  103861. uvs.set(buffer);
  103862. normalizeUVs(uvs);
  103863. tempVertexData.set(uvs, uvKind);
  103864. }
  103865. else if (semantic === "JOINT") {
  103866. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  103867. tempVertexData.matricesIndices.set(buffer);
  103868. }
  103869. else if (semantic === "WEIGHT") {
  103870. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  103871. tempVertexData.matricesWeights.set(buffer);
  103872. }
  103873. else if (semantic === "COLOR") {
  103874. tempVertexData.colors = new Float32Array(buffer.length);
  103875. tempVertexData.colors.set(buffer);
  103876. }
  103877. }
  103878. // Indices
  103879. accessor = gltfRuntime.accessors[primitive.indices];
  103880. if (accessor) {
  103881. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  103882. tempVertexData.indices = new Int32Array(buffer.length);
  103883. tempVertexData.indices.set(buffer);
  103884. indexCounts.push(tempVertexData.indices.length);
  103885. }
  103886. else {
  103887. // Set indices on the fly
  103888. var indices = [];
  103889. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  103890. indices.push(j);
  103891. }
  103892. tempVertexData.indices = new Int32Array(indices);
  103893. indexCounts.push(tempVertexData.indices.length);
  103894. }
  103895. if (!vertexData) {
  103896. vertexData = tempVertexData;
  103897. }
  103898. else {
  103899. vertexData.merge(tempVertexData);
  103900. }
  103901. // Sub material
  103902. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  103903. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  103904. // Update vertices start and index start
  103905. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  103906. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  103907. }
  103908. }
  103909. var material;
  103910. if (subMaterials.length > 1) {
  103911. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  103912. material.subMaterials = subMaterials;
  103913. }
  103914. else {
  103915. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  103916. }
  103917. if (subMaterials.length === 1) {
  103918. material = subMaterials[0];
  103919. }
  103920. if (!newMesh.material) {
  103921. newMesh.material = material;
  103922. }
  103923. // Apply geometry
  103924. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  103925. newMesh.computeWorldMatrix(true);
  103926. // Apply submeshes
  103927. newMesh.subMeshes = [];
  103928. var index = 0;
  103929. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  103930. var meshID = meshes[meshIndex];
  103931. var mesh = gltfRuntime.meshes[meshID];
  103932. if (!mesh) {
  103933. continue;
  103934. }
  103935. for (var i = 0; i < mesh.primitives.length; i++) {
  103936. if (mesh.primitives[i].mode !== 4) {
  103937. //continue;
  103938. }
  103939. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  103940. index++;
  103941. }
  103942. }
  103943. // Finish
  103944. return newMesh;
  103945. };
  103946. /**
  103947. * Configure node transformation from position, rotation and scaling
  103948. */
  103949. var configureNode = function (newNode, position, rotation, scaling) {
  103950. if (newNode.position) {
  103951. newNode.position = position;
  103952. }
  103953. if (newNode.rotationQuaternion || newNode.rotation) {
  103954. newNode.rotationQuaternion = rotation;
  103955. }
  103956. if (newNode.scaling) {
  103957. newNode.scaling = scaling;
  103958. }
  103959. };
  103960. /**
  103961. * Configures node from transformation matrix
  103962. */
  103963. var configureNodeFromMatrix = function (newNode, node, parent) {
  103964. if (node.matrix) {
  103965. var position = new BABYLON.Vector3(0, 0, 0);
  103966. var rotation = new BABYLON.Quaternion();
  103967. var scaling = new BABYLON.Vector3(0, 0, 0);
  103968. var mat = BABYLON.Matrix.FromArray(node.matrix);
  103969. mat.decompose(scaling, rotation, position);
  103970. configureNode(newNode, position, rotation, scaling);
  103971. }
  103972. else if (node.translation && node.rotation && node.scale) {
  103973. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  103974. }
  103975. newNode.computeWorldMatrix(true);
  103976. };
  103977. /**
  103978. * Imports a node
  103979. */
  103980. var importNode = function (gltfRuntime, node, id, parent) {
  103981. var lastNode = null;
  103982. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  103983. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  103984. return null;
  103985. }
  103986. }
  103987. // Meshes
  103988. if (node.skin) {
  103989. if (node.meshes) {
  103990. var skin = gltfRuntime.skins[node.skin];
  103991. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  103992. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  103993. if (newMesh.skeleton === null) {
  103994. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  103995. if (!skin.babylonSkeleton) {
  103996. skin.babylonSkeleton = newMesh.skeleton;
  103997. }
  103998. }
  103999. lastNode = newMesh;
  104000. }
  104001. }
  104002. else if (node.meshes) {
  104003. /**
  104004. * Improve meshes property
  104005. */
  104006. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  104007. lastNode = newMesh;
  104008. }
  104009. // Lights
  104010. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  104011. var light = gltfRuntime.lights[node.light];
  104012. if (light) {
  104013. if (light.type === "ambient") {
  104014. var ambienLight = light[light.type];
  104015. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104016. hemiLight.name = node.name || "";
  104017. if (ambienLight.color) {
  104018. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  104019. }
  104020. lastNode = hemiLight;
  104021. }
  104022. else if (light.type === "directional") {
  104023. var directionalLight = light[light.type];
  104024. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104025. dirLight.name = node.name || "";
  104026. if (directionalLight.color) {
  104027. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  104028. }
  104029. lastNode = dirLight;
  104030. }
  104031. else if (light.type === "point") {
  104032. var pointLight = light[light.type];
  104033. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104034. ptLight.name = node.name || "";
  104035. if (pointLight.color) {
  104036. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  104037. }
  104038. lastNode = ptLight;
  104039. }
  104040. else if (light.type === "spot") {
  104041. var spotLight = light[light.type];
  104042. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  104043. spLight.name = node.name || "";
  104044. if (spotLight.color) {
  104045. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  104046. }
  104047. if (spotLight.fallOfAngle) {
  104048. spLight.angle = spotLight.fallOfAngle;
  104049. }
  104050. if (spotLight.fallOffExponent) {
  104051. spLight.exponent = spotLight.fallOffExponent;
  104052. }
  104053. lastNode = spLight;
  104054. }
  104055. }
  104056. }
  104057. // Cameras
  104058. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  104059. var camera = gltfRuntime.cameras[node.camera];
  104060. if (camera) {
  104061. if (camera.type === "orthographic") {
  104062. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  104063. orthoCamera.name = node.name || "";
  104064. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  104065. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  104066. lastNode = orthoCamera;
  104067. }
  104068. else if (camera.type === "perspective") {
  104069. var perspectiveCamera = camera[camera.type];
  104070. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  104071. persCamera.name = node.name || "";
  104072. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  104073. if (!perspectiveCamera.aspectRatio) {
  104074. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  104075. }
  104076. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  104077. persCamera.maxZ = perspectiveCamera.zfar;
  104078. persCamera.minZ = perspectiveCamera.znear;
  104079. }
  104080. lastNode = persCamera;
  104081. }
  104082. }
  104083. }
  104084. // Empty node
  104085. if (!node.jointName) {
  104086. if (node.babylonNode) {
  104087. return node.babylonNode;
  104088. }
  104089. else if (lastNode === null) {
  104090. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  104091. node.babylonNode = dummy;
  104092. lastNode = dummy;
  104093. }
  104094. }
  104095. if (lastNode !== null) {
  104096. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  104097. configureNodeFromMatrix(lastNode, node, parent);
  104098. }
  104099. else {
  104100. var translation = node.translation || [0, 0, 0];
  104101. var rotation = node.rotation || [0, 0, 0, 1];
  104102. var scale = node.scale || [1, 1, 1];
  104103. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  104104. }
  104105. lastNode.updateCache(true);
  104106. node.babylonNode = lastNode;
  104107. }
  104108. return lastNode;
  104109. };
  104110. /**
  104111. * Traverses nodes and creates them
  104112. */
  104113. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  104114. if (meshIncluded === void 0) { meshIncluded = false; }
  104115. var node = gltfRuntime.nodes[id];
  104116. var newNode = null;
  104117. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  104118. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  104119. meshIncluded = true;
  104120. }
  104121. else {
  104122. meshIncluded = false;
  104123. }
  104124. }
  104125. else {
  104126. meshIncluded = true;
  104127. }
  104128. if (!node.jointName && meshIncluded) {
  104129. newNode = importNode(gltfRuntime, node, id, parent);
  104130. if (newNode !== null) {
  104131. newNode.id = id;
  104132. newNode.parent = parent;
  104133. }
  104134. }
  104135. if (node.children) {
  104136. for (var i = 0; i < node.children.length; i++) {
  104137. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  104138. }
  104139. }
  104140. };
  104141. /**
  104142. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  104143. */
  104144. var postLoad = function (gltfRuntime) {
  104145. // Nodes
  104146. var currentScene = gltfRuntime.currentScene;
  104147. if (currentScene) {
  104148. for (var i = 0; i < currentScene.nodes.length; i++) {
  104149. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104150. }
  104151. }
  104152. else {
  104153. for (var thing in gltfRuntime.scenes) {
  104154. currentScene = gltfRuntime.scenes[thing];
  104155. for (var i = 0; i < currentScene.nodes.length; i++) {
  104156. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104157. }
  104158. }
  104159. }
  104160. // Set animations
  104161. loadAnimations(gltfRuntime);
  104162. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  104163. var skeleton = gltfRuntime.scene.skeletons[i];
  104164. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  104165. }
  104166. };
  104167. /**
  104168. * onBind shaderrs callback to set uniforms and matrices
  104169. */
  104170. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  104171. var materialValues = material.values || technique.parameters;
  104172. for (var unif in unTreatedUniforms) {
  104173. var uniform = unTreatedUniforms[unif];
  104174. var type = uniform.type;
  104175. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  104176. if (uniform.semantic && !uniform.source && !uniform.node) {
  104177. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  104178. }
  104179. else if (uniform.semantic && (uniform.source || uniform.node)) {
  104180. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  104181. if (source === null) {
  104182. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  104183. }
  104184. if (source === null) {
  104185. continue;
  104186. }
  104187. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  104188. }
  104189. }
  104190. else {
  104191. var value = materialValues[technique.uniforms[unif]];
  104192. if (!value) {
  104193. continue;
  104194. }
  104195. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  104196. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  104197. if (texture === null || texture === undefined) {
  104198. continue;
  104199. }
  104200. shaderMaterial.getEffect().setTexture(unif, texture);
  104201. }
  104202. else {
  104203. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  104204. }
  104205. }
  104206. }
  104207. onSuccess(shaderMaterial);
  104208. };
  104209. /**
  104210. * Prepare uniforms to send the only one time
  104211. * Loads the appropriate textures
  104212. */
  104213. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  104214. var materialValues = material.values || technique.parameters;
  104215. var techniqueUniforms = technique.uniforms;
  104216. /**
  104217. * Prepare values here (not matrices)
  104218. */
  104219. for (var unif in unTreatedUniforms) {
  104220. var uniform = unTreatedUniforms[unif];
  104221. var type = uniform.type;
  104222. var value = materialValues[techniqueUniforms[unif]];
  104223. if (value === undefined) {
  104224. // In case the value is the same for all materials
  104225. value = uniform.value;
  104226. }
  104227. if (!value) {
  104228. continue;
  104229. }
  104230. var onLoadTexture = function (uniformName) {
  104231. return function (texture) {
  104232. if (uniform.value && uniformName) {
  104233. // Static uniform
  104234. shaderMaterial.setTexture(uniformName, texture);
  104235. delete unTreatedUniforms[uniformName];
  104236. }
  104237. };
  104238. };
  104239. // Texture (sampler2D)
  104240. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  104241. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  104242. }
  104243. // Others
  104244. else {
  104245. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  104246. // Static uniform
  104247. delete unTreatedUniforms[unif];
  104248. }
  104249. }
  104250. }
  104251. };
  104252. /**
  104253. * Shader compilation failed
  104254. */
  104255. var onShaderCompileError = function (program, shaderMaterial, onError) {
  104256. return function (effect, error) {
  104257. shaderMaterial.dispose(true);
  104258. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  104259. };
  104260. };
  104261. /**
  104262. * Shader compilation success
  104263. */
  104264. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  104265. return function (_) {
  104266. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  104267. shaderMaterial.onBind = function (mesh) {
  104268. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  104269. };
  104270. };
  104271. };
  104272. /**
  104273. * Returns the appropriate uniform if already handled by babylon
  104274. */
  104275. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  104276. for (var unif in technique.uniforms) {
  104277. var uniform = technique.uniforms[unif];
  104278. var uniformParameter = technique.parameters[uniform];
  104279. if (tokenizer.currentIdentifier === unif) {
  104280. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  104281. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  104282. if (transformIndex !== -1) {
  104283. delete unTreatedUniforms[unif];
  104284. return babylonTransforms[transformIndex];
  104285. }
  104286. }
  104287. }
  104288. }
  104289. return tokenizer.currentIdentifier;
  104290. };
  104291. /**
  104292. * All shaders loaded. Create materials one by one
  104293. */
  104294. var importMaterials = function (gltfRuntime) {
  104295. // Create materials
  104296. for (var mat in gltfRuntime.materials) {
  104297. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  104298. }
  104299. };
  104300. /**
  104301. * Implementation of the base glTF spec
  104302. */
  104303. var GLTFLoaderBase = /** @class */ (function () {
  104304. function GLTFLoaderBase() {
  104305. }
  104306. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  104307. var gltfRuntime = {
  104308. extensions: {},
  104309. accessors: {},
  104310. buffers: {},
  104311. bufferViews: {},
  104312. meshes: {},
  104313. lights: {},
  104314. cameras: {},
  104315. nodes: {},
  104316. images: {},
  104317. textures: {},
  104318. shaders: {},
  104319. programs: {},
  104320. samplers: {},
  104321. techniques: {},
  104322. materials: {},
  104323. animations: {},
  104324. skins: {},
  104325. extensionsUsed: [],
  104326. scenes: {},
  104327. buffersCount: 0,
  104328. shaderscount: 0,
  104329. scene: scene,
  104330. rootUrl: rootUrl,
  104331. loadedBufferCount: 0,
  104332. loadedBufferViews: {},
  104333. loadedShaderCount: 0,
  104334. importOnlyMeshes: false,
  104335. dummyNodes: []
  104336. };
  104337. // Parse
  104338. if (parsedData.extensions) {
  104339. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  104340. }
  104341. if (parsedData.extensionsUsed) {
  104342. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  104343. }
  104344. if (parsedData.buffers) {
  104345. parseBuffers(parsedData.buffers, gltfRuntime);
  104346. }
  104347. if (parsedData.bufferViews) {
  104348. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  104349. }
  104350. if (parsedData.accessors) {
  104351. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  104352. }
  104353. if (parsedData.meshes) {
  104354. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  104355. }
  104356. if (parsedData.lights) {
  104357. parseObject(parsedData.lights, "lights", gltfRuntime);
  104358. }
  104359. if (parsedData.cameras) {
  104360. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  104361. }
  104362. if (parsedData.nodes) {
  104363. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  104364. }
  104365. if (parsedData.images) {
  104366. parseObject(parsedData.images, "images", gltfRuntime);
  104367. }
  104368. if (parsedData.textures) {
  104369. parseObject(parsedData.textures, "textures", gltfRuntime);
  104370. }
  104371. if (parsedData.shaders) {
  104372. parseShaders(parsedData.shaders, gltfRuntime);
  104373. }
  104374. if (parsedData.programs) {
  104375. parseObject(parsedData.programs, "programs", gltfRuntime);
  104376. }
  104377. if (parsedData.samplers) {
  104378. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  104379. }
  104380. if (parsedData.techniques) {
  104381. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  104382. }
  104383. if (parsedData.materials) {
  104384. parseObject(parsedData.materials, "materials", gltfRuntime);
  104385. }
  104386. if (parsedData.animations) {
  104387. parseObject(parsedData.animations, "animations", gltfRuntime);
  104388. }
  104389. if (parsedData.skins) {
  104390. parseObject(parsedData.skins, "skins", gltfRuntime);
  104391. }
  104392. if (parsedData.scenes) {
  104393. gltfRuntime.scenes = parsedData.scenes;
  104394. }
  104395. if (parsedData.scene && parsedData.scenes) {
  104396. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  104397. }
  104398. return gltfRuntime;
  104399. };
  104400. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104401. var buffer = gltfRuntime.buffers[id];
  104402. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  104403. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  104404. }
  104405. else {
  104406. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  104407. if (request) {
  104408. onError(request.status + " " + request.statusText);
  104409. }
  104410. });
  104411. }
  104412. };
  104413. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104414. var texture = gltfRuntime.textures[id];
  104415. if (!texture || !texture.source) {
  104416. onError("");
  104417. return;
  104418. }
  104419. if (texture.babylonTexture) {
  104420. onSuccess(null);
  104421. return;
  104422. }
  104423. var source = gltfRuntime.images[texture.source];
  104424. if (BABYLON.Tools.IsBase64(source.uri)) {
  104425. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  104426. }
  104427. else {
  104428. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  104429. if (request) {
  104430. onError(request.status + " " + request.statusText);
  104431. }
  104432. });
  104433. }
  104434. };
  104435. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104436. var texture = gltfRuntime.textures[id];
  104437. if (texture.babylonTexture) {
  104438. onSuccess(texture.babylonTexture);
  104439. return;
  104440. }
  104441. var sampler = gltfRuntime.samplers[texture.sampler];
  104442. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  104443. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  104444. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  104445. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  104446. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  104447. var blob = new Blob([buffer]);
  104448. var blobURL = URL.createObjectURL(blob);
  104449. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  104450. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  104451. if (sampler.wrapS !== undefined) {
  104452. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  104453. }
  104454. if (sampler.wrapT !== undefined) {
  104455. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  104456. }
  104457. newTexture.name = id;
  104458. texture.babylonTexture = newTexture;
  104459. onSuccess(newTexture);
  104460. };
  104461. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104462. var shader = gltfRuntime.shaders[id];
  104463. if (BABYLON.Tools.IsBase64(shader.uri)) {
  104464. var shaderString = atob(shader.uri.split(",")[1]);
  104465. if (onSuccess) {
  104466. onSuccess(shaderString);
  104467. }
  104468. }
  104469. else {
  104470. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  104471. if (request && onError) {
  104472. onError(request.status + " " + request.statusText);
  104473. }
  104474. });
  104475. }
  104476. };
  104477. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104478. var material = gltfRuntime.materials[id];
  104479. if (!material.technique) {
  104480. if (onError) {
  104481. onError("No technique found.");
  104482. }
  104483. return;
  104484. }
  104485. var technique = gltfRuntime.techniques[material.technique];
  104486. if (!technique) {
  104487. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  104488. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  104489. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104490. onSuccess(defaultMaterial);
  104491. return;
  104492. }
  104493. var program = gltfRuntime.programs[technique.program];
  104494. var states = technique.states;
  104495. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  104496. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  104497. var newVertexShader = "";
  104498. var newPixelShader = "";
  104499. var vertexTokenizer = new Tokenizer(vertexShader);
  104500. var pixelTokenizer = new Tokenizer(pixelShader);
  104501. var unTreatedUniforms = {};
  104502. var uniforms = [];
  104503. var attributes = [];
  104504. var samplers = [];
  104505. // Fill uniform, sampler2D and attributes
  104506. for (var unif in technique.uniforms) {
  104507. var uniform = technique.uniforms[unif];
  104508. var uniformParameter = technique.parameters[uniform];
  104509. unTreatedUniforms[unif] = uniformParameter;
  104510. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  104511. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  104512. if (transformIndex !== -1) {
  104513. uniforms.push(babylonTransforms[transformIndex]);
  104514. delete unTreatedUniforms[unif];
  104515. }
  104516. else {
  104517. uniforms.push(unif);
  104518. }
  104519. }
  104520. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  104521. samplers.push(unif);
  104522. }
  104523. else {
  104524. uniforms.push(unif);
  104525. }
  104526. }
  104527. for (var attr in technique.attributes) {
  104528. var attribute = technique.attributes[attr];
  104529. var attributeParameter = technique.parameters[attribute];
  104530. if (attributeParameter.semantic) {
  104531. attributes.push(getAttribute(attributeParameter));
  104532. }
  104533. }
  104534. // Configure vertex shader
  104535. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  104536. var tokenType = vertexTokenizer.currentToken;
  104537. if (tokenType !== ETokenType.IDENTIFIER) {
  104538. newVertexShader += vertexTokenizer.currentString;
  104539. continue;
  104540. }
  104541. var foundAttribute = false;
  104542. for (var attr in technique.attributes) {
  104543. var attribute = technique.attributes[attr];
  104544. var attributeParameter = technique.parameters[attribute];
  104545. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  104546. newVertexShader += getAttribute(attributeParameter);
  104547. foundAttribute = true;
  104548. break;
  104549. }
  104550. }
  104551. if (foundAttribute) {
  104552. continue;
  104553. }
  104554. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  104555. }
  104556. // Configure pixel shader
  104557. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  104558. var tokenType = pixelTokenizer.currentToken;
  104559. if (tokenType !== ETokenType.IDENTIFIER) {
  104560. newPixelShader += pixelTokenizer.currentString;
  104561. continue;
  104562. }
  104563. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  104564. }
  104565. // Create shader material
  104566. var shaderPath = {
  104567. vertex: program.vertexShader + id,
  104568. fragment: program.fragmentShader + id
  104569. };
  104570. var options = {
  104571. attributes: attributes,
  104572. uniforms: uniforms,
  104573. samplers: samplers,
  104574. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  104575. };
  104576. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  104577. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  104578. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  104579. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  104580. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  104581. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104582. if (states && states.functions) {
  104583. var functions = states.functions;
  104584. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  104585. shaderMaterial.backFaceCulling = false;
  104586. }
  104587. var blendFunc = functions.blendFuncSeparate;
  104588. if (blendFunc) {
  104589. 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) {
  104590. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  104591. }
  104592. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104593. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  104594. }
  104595. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104596. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  104597. }
  104598. 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) {
  104599. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  104600. }
  104601. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104602. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  104603. }
  104604. 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) {
  104605. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  104606. }
  104607. }
  104608. }
  104609. };
  104610. return GLTFLoaderBase;
  104611. }());
  104612. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  104613. /**
  104614. * glTF V1 Loader
  104615. */
  104616. var GLTFLoader = /** @class */ (function () {
  104617. function GLTFLoader() {
  104618. // #region Stubs for IGLTFLoader interface
  104619. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  104620. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  104621. this.compileMaterials = false;
  104622. this.useClipPlane = false;
  104623. this.compileShadowGenerators = false;
  104624. this.transparencyAsCoverage = false;
  104625. this._normalizeAnimationGroupsToBeginAtZero = true;
  104626. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104627. this.onMeshLoadedObservable = new BABYLON.Observable();
  104628. this.onTextureLoadedObservable = new BABYLON.Observable();
  104629. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104630. this.onCameraLoadedObservable = new BABYLON.Observable();
  104631. this.onCompleteObservable = new BABYLON.Observable();
  104632. this.onDisposeObservable = new BABYLON.Observable();
  104633. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104634. this.state = null;
  104635. }
  104636. GLTFLoader.RegisterExtension = function (extension) {
  104637. if (GLTFLoader.Extensions[extension.name]) {
  104638. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  104639. return;
  104640. }
  104641. GLTFLoader.Extensions[extension.name] = extension;
  104642. };
  104643. GLTFLoader.prototype.dispose = function () { };
  104644. // #endregion
  104645. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  104646. var _this = this;
  104647. scene.useRightHandedSystem = true;
  104648. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  104649. gltfRuntime.importOnlyMeshes = true;
  104650. if (meshesNames === "") {
  104651. gltfRuntime.importMeshesNames = [];
  104652. }
  104653. else if (typeof meshesNames === "string") {
  104654. gltfRuntime.importMeshesNames = [meshesNames];
  104655. }
  104656. else if (meshesNames && !(meshesNames instanceof Array)) {
  104657. gltfRuntime.importMeshesNames = [meshesNames];
  104658. }
  104659. else {
  104660. gltfRuntime.importMeshesNames = [];
  104661. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  104662. }
  104663. // Create nodes
  104664. _this._createNodes(gltfRuntime);
  104665. var meshes = new Array();
  104666. var skeletons = new Array();
  104667. // Fill arrays of meshes and skeletons
  104668. for (var nde in gltfRuntime.nodes) {
  104669. var node = gltfRuntime.nodes[nde];
  104670. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  104671. meshes.push(node.babylonNode);
  104672. }
  104673. }
  104674. for (var skl in gltfRuntime.skins) {
  104675. var skin = gltfRuntime.skins[skl];
  104676. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  104677. skeletons.push(skin.babylonSkeleton);
  104678. }
  104679. }
  104680. // Load buffers, shaders, materials, etc.
  104681. _this._loadBuffersAsync(gltfRuntime, function () {
  104682. _this._loadShadersAsync(gltfRuntime, function () {
  104683. importMaterials(gltfRuntime);
  104684. postLoad(gltfRuntime);
  104685. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  104686. onSuccess(meshes, skeletons);
  104687. }
  104688. });
  104689. }, onProgress);
  104690. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  104691. onSuccess(meshes, skeletons);
  104692. }
  104693. }, onError);
  104694. return true;
  104695. };
  104696. /**
  104697. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  104698. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104699. * @param scene the scene the meshes should be added to
  104700. * @param data gltf data containing information of the meshes in a loaded file
  104701. * @param rootUrl root url to load from
  104702. * @param onProgress event that fires when loading progress has occured
  104703. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104704. */
  104705. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104706. var _this = this;
  104707. return new Promise(function (resolve, reject) {
  104708. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  104709. resolve({
  104710. meshes: meshes,
  104711. particleSystems: [],
  104712. skeletons: skeletons,
  104713. animationGroups: []
  104714. });
  104715. }, onProgress, function (message) {
  104716. reject(new Error(message));
  104717. });
  104718. });
  104719. };
  104720. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  104721. var _this = this;
  104722. scene.useRightHandedSystem = true;
  104723. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  104724. // Load runtime extensios
  104725. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  104726. // Create nodes
  104727. _this._createNodes(gltfRuntime);
  104728. // Load buffers, shaders, materials, etc.
  104729. _this._loadBuffersAsync(gltfRuntime, function () {
  104730. _this._loadShadersAsync(gltfRuntime, function () {
  104731. importMaterials(gltfRuntime);
  104732. postLoad(gltfRuntime);
  104733. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  104734. onSuccess();
  104735. }
  104736. });
  104737. });
  104738. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  104739. onSuccess();
  104740. }
  104741. }, onError);
  104742. }, onError);
  104743. };
  104744. /**
  104745. * Imports all objects from a loaded gltf file and adds them to the scene
  104746. * @param scene the scene the objects should be added to
  104747. * @param data gltf data containing information of the meshes in a loaded file
  104748. * @param rootUrl root url to load from
  104749. * @param onProgress event that fires when loading progress has occured
  104750. * @returns a promise which completes when objects have been loaded to the scene
  104751. */
  104752. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104753. var _this = this;
  104754. return new Promise(function (resolve, reject) {
  104755. _this._loadAsync(scene, data, rootUrl, function () {
  104756. resolve();
  104757. }, onProgress, function (message) {
  104758. reject(new Error(message));
  104759. });
  104760. });
  104761. };
  104762. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  104763. var hasShaders = false;
  104764. var processShader = function (sha, shader) {
  104765. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  104766. if (shaderString instanceof ArrayBuffer) {
  104767. return;
  104768. }
  104769. gltfRuntime.loadedShaderCount++;
  104770. if (shaderString) {
  104771. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  104772. }
  104773. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  104774. onload();
  104775. }
  104776. }, function () {
  104777. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  104778. });
  104779. };
  104780. for (var sha in gltfRuntime.shaders) {
  104781. hasShaders = true;
  104782. var shader = gltfRuntime.shaders[sha];
  104783. if (shader) {
  104784. processShader.bind(this, sha, shader)();
  104785. }
  104786. else {
  104787. BABYLON.Tools.Error("No shader named: " + sha);
  104788. }
  104789. }
  104790. if (!hasShaders) {
  104791. onload();
  104792. }
  104793. };
  104794. ;
  104795. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  104796. var hasBuffers = false;
  104797. var processBuffer = function (buf, buffer) {
  104798. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  104799. gltfRuntime.loadedBufferCount++;
  104800. if (bufferView) {
  104801. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  104802. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  104803. }
  104804. gltfRuntime.loadedBufferViews[buf] = bufferView;
  104805. }
  104806. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  104807. onLoad();
  104808. }
  104809. }, function () {
  104810. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  104811. });
  104812. };
  104813. for (var buf in gltfRuntime.buffers) {
  104814. hasBuffers = true;
  104815. var buffer = gltfRuntime.buffers[buf];
  104816. if (buffer) {
  104817. processBuffer.bind(this, buf, buffer)();
  104818. }
  104819. else {
  104820. BABYLON.Tools.Error("No buffer named: " + buf);
  104821. }
  104822. }
  104823. if (!hasBuffers) {
  104824. onLoad();
  104825. }
  104826. };
  104827. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  104828. var currentScene = gltfRuntime.currentScene;
  104829. if (currentScene) {
  104830. // Only one scene even if multiple scenes are defined
  104831. for (var i = 0; i < currentScene.nodes.length; i++) {
  104832. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104833. }
  104834. }
  104835. else {
  104836. // Load all scenes
  104837. for (var thing in gltfRuntime.scenes) {
  104838. currentScene = gltfRuntime.scenes[thing];
  104839. for (var i = 0; i < currentScene.nodes.length; i++) {
  104840. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104841. }
  104842. }
  104843. }
  104844. };
  104845. GLTFLoader.Extensions = {};
  104846. return GLTFLoader;
  104847. }());
  104848. GLTF1.GLTFLoader = GLTFLoader;
  104849. ;
  104850. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  104851. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104852. })(BABYLON || (BABYLON = {}));
  104853. //# sourceMappingURL=babylon.glTFLoader.js.map
  104854. var BABYLON;
  104855. (function (BABYLON) {
  104856. var GLTF1;
  104857. (function (GLTF1) {
  104858. /**
  104859. * Utils functions for GLTF
  104860. */
  104861. var GLTFUtils = /** @class */ (function () {
  104862. function GLTFUtils() {
  104863. }
  104864. /**
  104865. * Sets the given "parameter" matrix
  104866. * @param scene: the {BABYLON.Scene} object
  104867. * @param source: the source node where to pick the matrix
  104868. * @param parameter: the GLTF technique parameter
  104869. * @param uniformName: the name of the shader's uniform
  104870. * @param shaderMaterial: the shader material
  104871. */
  104872. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  104873. var mat = null;
  104874. if (parameter.semantic === "MODEL") {
  104875. mat = source.getWorldMatrix();
  104876. }
  104877. else if (parameter.semantic === "PROJECTION") {
  104878. mat = scene.getProjectionMatrix();
  104879. }
  104880. else if (parameter.semantic === "VIEW") {
  104881. mat = scene.getViewMatrix();
  104882. }
  104883. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  104884. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  104885. }
  104886. else if (parameter.semantic === "MODELVIEW") {
  104887. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  104888. }
  104889. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  104890. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  104891. }
  104892. else if (parameter.semantic === "MODELINVERSE") {
  104893. mat = source.getWorldMatrix().invert();
  104894. }
  104895. else if (parameter.semantic === "VIEWINVERSE") {
  104896. mat = scene.getViewMatrix().invert();
  104897. }
  104898. else if (parameter.semantic === "PROJECTIONINVERSE") {
  104899. mat = scene.getProjectionMatrix().invert();
  104900. }
  104901. else if (parameter.semantic === "MODELVIEWINVERSE") {
  104902. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  104903. }
  104904. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  104905. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  104906. }
  104907. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  104908. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  104909. }
  104910. else {
  104911. debugger;
  104912. }
  104913. if (mat) {
  104914. switch (parameter.type) {
  104915. case GLTF1.EParameterType.FLOAT_MAT2:
  104916. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  104917. break;
  104918. case GLTF1.EParameterType.FLOAT_MAT3:
  104919. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  104920. break;
  104921. case GLTF1.EParameterType.FLOAT_MAT4:
  104922. shaderMaterial.setMatrix(uniformName, mat);
  104923. break;
  104924. default: break;
  104925. }
  104926. }
  104927. };
  104928. /**
  104929. * Sets the given "parameter" matrix
  104930. * @param shaderMaterial: the shader material
  104931. * @param uniform: the name of the shader's uniform
  104932. * @param value: the value of the uniform
  104933. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  104934. */
  104935. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  104936. switch (type) {
  104937. case GLTF1.EParameterType.FLOAT:
  104938. shaderMaterial.setFloat(uniform, value);
  104939. return true;
  104940. case GLTF1.EParameterType.FLOAT_VEC2:
  104941. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  104942. return true;
  104943. case GLTF1.EParameterType.FLOAT_VEC3:
  104944. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  104945. return true;
  104946. case GLTF1.EParameterType.FLOAT_VEC4:
  104947. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  104948. return true;
  104949. default: return false;
  104950. }
  104951. };
  104952. /**
  104953. * Returns the wrap mode of the texture
  104954. * @param mode: the mode value
  104955. */
  104956. GLTFUtils.GetWrapMode = function (mode) {
  104957. switch (mode) {
  104958. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  104959. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  104960. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104961. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104962. }
  104963. };
  104964. /**
  104965. * Returns the byte stride giving an accessor
  104966. * @param accessor: the GLTF accessor objet
  104967. */
  104968. GLTFUtils.GetByteStrideFromType = function (accessor) {
  104969. // Needs this function since "byteStride" isn't requiered in glTF format
  104970. var type = accessor.type;
  104971. switch (type) {
  104972. case "VEC2": return 2;
  104973. case "VEC3": return 3;
  104974. case "VEC4": return 4;
  104975. case "MAT2": return 4;
  104976. case "MAT3": return 9;
  104977. case "MAT4": return 16;
  104978. default: return 1;
  104979. }
  104980. };
  104981. /**
  104982. * Returns the texture filter mode giving a mode value
  104983. * @param mode: the filter mode value
  104984. */
  104985. GLTFUtils.GetTextureFilterMode = function (mode) {
  104986. switch (mode) {
  104987. case GLTF1.ETextureFilterType.LINEAR:
  104988. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  104989. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104990. case GLTF1.ETextureFilterType.NEAREST:
  104991. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  104992. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  104993. }
  104994. };
  104995. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  104996. var byteOffset = bufferView.byteOffset + byteOffset;
  104997. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  104998. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  104999. throw new Error("Buffer access is out of range");
  105000. }
  105001. var buffer = loadedBufferView.buffer;
  105002. byteOffset += loadedBufferView.byteOffset;
  105003. switch (componentType) {
  105004. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  105005. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  105006. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  105007. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  105008. default: return new Float32Array(buffer, byteOffset, byteLength);
  105009. }
  105010. };
  105011. /**
  105012. * Returns a buffer from its accessor
  105013. * @param gltfRuntime: the GLTF runtime
  105014. * @param accessor: the GLTF accessor
  105015. */
  105016. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  105017. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  105018. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  105019. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  105020. };
  105021. /**
  105022. * Decodes a buffer view into a string
  105023. * @param view: the buffer view
  105024. */
  105025. GLTFUtils.DecodeBufferToText = function (view) {
  105026. var result = "";
  105027. var length = view.byteLength;
  105028. for (var i = 0; i < length; ++i) {
  105029. result += String.fromCharCode(view[i]);
  105030. }
  105031. return result;
  105032. };
  105033. /**
  105034. * Returns the default material of gltf. Related to
  105035. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  105036. * @param scene: the Babylon.js scene
  105037. */
  105038. GLTFUtils.GetDefaultMaterial = function (scene) {
  105039. if (!GLTFUtils._DefaultMaterial) {
  105040. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  105041. "precision highp float;",
  105042. "",
  105043. "uniform mat4 worldView;",
  105044. "uniform mat4 projection;",
  105045. "",
  105046. "attribute vec3 position;",
  105047. "",
  105048. "void main(void)",
  105049. "{",
  105050. " gl_Position = projection * worldView * vec4(position, 1.0);",
  105051. "}"
  105052. ].join("\n");
  105053. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  105054. "precision highp float;",
  105055. "",
  105056. "uniform vec4 u_emission;",
  105057. "",
  105058. "void main(void)",
  105059. "{",
  105060. " gl_FragColor = u_emission;",
  105061. "}"
  105062. ].join("\n");
  105063. var shaderPath = {
  105064. vertex: "GLTFDefaultMaterial",
  105065. fragment: "GLTFDefaultMaterial"
  105066. };
  105067. var options = {
  105068. attributes: ["position"],
  105069. uniforms: ["worldView", "projection", "u_emission"],
  105070. samplers: new Array(),
  105071. needAlphaBlending: false
  105072. };
  105073. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  105074. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  105075. }
  105076. return GLTFUtils._DefaultMaterial;
  105077. };
  105078. // The GLTF default material
  105079. GLTFUtils._DefaultMaterial = null;
  105080. return GLTFUtils;
  105081. }());
  105082. GLTF1.GLTFUtils = GLTFUtils;
  105083. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105084. })(BABYLON || (BABYLON = {}));
  105085. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  105086. var BABYLON;
  105087. (function (BABYLON) {
  105088. var GLTF1;
  105089. (function (GLTF1) {
  105090. var GLTFLoaderExtension = /** @class */ (function () {
  105091. function GLTFLoaderExtension(name) {
  105092. this._name = name;
  105093. }
  105094. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  105095. get: function () {
  105096. return this._name;
  105097. },
  105098. enumerable: true,
  105099. configurable: true
  105100. });
  105101. /**
  105102. * Defines an override for loading the runtime
  105103. * Return true to stop further extensions from loading the runtime
  105104. */
  105105. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105106. return false;
  105107. };
  105108. /**
  105109. * Defines an onverride for creating gltf runtime
  105110. * Return true to stop further extensions from creating the runtime
  105111. */
  105112. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105113. return false;
  105114. };
  105115. /**
  105116. * Defines an override for loading buffers
  105117. * Return true to stop further extensions from loading this buffer
  105118. */
  105119. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105120. return false;
  105121. };
  105122. /**
  105123. * Defines an override for loading texture buffers
  105124. * Return true to stop further extensions from loading this texture data
  105125. */
  105126. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105127. return false;
  105128. };
  105129. /**
  105130. * Defines an override for creating textures
  105131. * Return true to stop further extensions from loading this texture
  105132. */
  105133. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  105134. return false;
  105135. };
  105136. /**
  105137. * Defines an override for loading shader strings
  105138. * Return true to stop further extensions from loading this shader data
  105139. */
  105140. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105141. return false;
  105142. };
  105143. /**
  105144. * Defines an override for loading materials
  105145. * Return true to stop further extensions from loading this material
  105146. */
  105147. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105148. return false;
  105149. };
  105150. // ---------
  105151. // Utilities
  105152. // ---------
  105153. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105154. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105155. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  105156. }, function () {
  105157. setTimeout(function () {
  105158. if (!onSuccess) {
  105159. return;
  105160. }
  105161. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  105162. });
  105163. });
  105164. };
  105165. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105166. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105167. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  105168. }, function () {
  105169. setTimeout(function () {
  105170. onSuccess();
  105171. });
  105172. });
  105173. };
  105174. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105175. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105176. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  105177. }, function () {
  105178. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  105179. });
  105180. };
  105181. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  105182. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  105183. if (buffer) {
  105184. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  105185. }
  105186. }, onError);
  105187. };
  105188. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105189. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105190. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  105191. }, function () {
  105192. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  105193. });
  105194. };
  105195. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105196. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105197. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  105198. }, function () {
  105199. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  105200. });
  105201. };
  105202. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105203. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105204. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  105205. }, function () {
  105206. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  105207. });
  105208. };
  105209. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  105210. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105211. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  105212. }, function () {
  105213. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  105214. });
  105215. };
  105216. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  105217. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  105218. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  105219. if (func(loaderExtension)) {
  105220. return;
  105221. }
  105222. }
  105223. defaultFunc();
  105224. };
  105225. return GLTFLoaderExtension;
  105226. }());
  105227. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  105228. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105229. })(BABYLON || (BABYLON = {}));
  105230. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  105231. var BABYLON;
  105232. (function (BABYLON) {
  105233. var GLTF1;
  105234. (function (GLTF1) {
  105235. var BinaryExtensionBufferName = "binary_glTF";
  105236. ;
  105237. ;
  105238. var GLTFBinaryExtension = /** @class */ (function (_super) {
  105239. __extends(GLTFBinaryExtension, _super);
  105240. function GLTFBinaryExtension() {
  105241. return _super.call(this, "KHR_binary_glTF") || this;
  105242. }
  105243. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105244. var extensionsUsed = data.json.extensionsUsed;
  105245. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  105246. return false;
  105247. }
  105248. this._bin = data.bin;
  105249. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  105250. return true;
  105251. };
  105252. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105253. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  105254. return false;
  105255. }
  105256. if (id !== BinaryExtensionBufferName) {
  105257. return false;
  105258. }
  105259. onSuccess(this._bin);
  105260. return true;
  105261. };
  105262. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105263. var texture = gltfRuntime.textures[id];
  105264. var source = gltfRuntime.images[texture.source];
  105265. if (!source.extensions || !(this.name in source.extensions)) {
  105266. return false;
  105267. }
  105268. var sourceExt = source.extensions[this.name];
  105269. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  105270. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  105271. onSuccess(buffer);
  105272. return true;
  105273. };
  105274. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105275. var shader = gltfRuntime.shaders[id];
  105276. if (!shader.extensions || !(this.name in shader.extensions)) {
  105277. return false;
  105278. }
  105279. var binaryExtensionShader = shader.extensions[this.name];
  105280. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  105281. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  105282. setTimeout(function () {
  105283. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  105284. onSuccess(shaderString);
  105285. });
  105286. return true;
  105287. };
  105288. return GLTFBinaryExtension;
  105289. }(GLTF1.GLTFLoaderExtension));
  105290. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  105291. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  105292. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105293. })(BABYLON || (BABYLON = {}));
  105294. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  105295. var BABYLON;
  105296. (function (BABYLON) {
  105297. var GLTF1;
  105298. (function (GLTF1) {
  105299. ;
  105300. ;
  105301. ;
  105302. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  105303. __extends(GLTFMaterialsCommonExtension, _super);
  105304. function GLTFMaterialsCommonExtension() {
  105305. return _super.call(this, "KHR_materials_common") || this;
  105306. }
  105307. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105308. if (!gltfRuntime.extensions)
  105309. return false;
  105310. var extension = gltfRuntime.extensions[this.name];
  105311. if (!extension)
  105312. return false;
  105313. // Create lights
  105314. var lights = extension.lights;
  105315. if (lights) {
  105316. for (var thing in lights) {
  105317. var light = lights[thing];
  105318. switch (light.type) {
  105319. case "ambient":
  105320. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  105321. var ambient = light.ambient;
  105322. if (ambient) {
  105323. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  105324. }
  105325. break;
  105326. case "point":
  105327. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  105328. var point = light.point;
  105329. if (point) {
  105330. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  105331. }
  105332. break;
  105333. case "directional":
  105334. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  105335. var directional = light.directional;
  105336. if (directional) {
  105337. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  105338. }
  105339. break;
  105340. case "spot":
  105341. var spot = light.spot;
  105342. if (spot) {
  105343. 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);
  105344. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  105345. }
  105346. break;
  105347. default:
  105348. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  105349. break;
  105350. }
  105351. }
  105352. }
  105353. return false;
  105354. };
  105355. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105356. var material = gltfRuntime.materials[id];
  105357. if (!material || !material.extensions)
  105358. return false;
  105359. var extension = material.extensions[this.name];
  105360. if (!extension)
  105361. return false;
  105362. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  105363. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  105364. if (extension.technique === "CONSTANT") {
  105365. standardMaterial.disableLighting = true;
  105366. }
  105367. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  105368. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  105369. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  105370. // Ambient
  105371. if (typeof extension.values.ambient === "string") {
  105372. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  105373. }
  105374. else {
  105375. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  105376. }
  105377. // Diffuse
  105378. if (typeof extension.values.diffuse === "string") {
  105379. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  105380. }
  105381. else {
  105382. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  105383. }
  105384. // Emission
  105385. if (typeof extension.values.emission === "string") {
  105386. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  105387. }
  105388. else {
  105389. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  105390. }
  105391. // Specular
  105392. if (typeof extension.values.specular === "string") {
  105393. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  105394. }
  105395. else {
  105396. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  105397. }
  105398. return true;
  105399. };
  105400. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  105401. // Create buffer from texture url
  105402. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  105403. // Create texture from buffer
  105404. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  105405. }, onError);
  105406. };
  105407. return GLTFMaterialsCommonExtension;
  105408. }(GLTF1.GLTFLoaderExtension));
  105409. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  105410. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  105411. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105412. })(BABYLON || (BABYLON = {}));
  105413. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  105414. var BABYLON;
  105415. (function (BABYLON) {
  105416. var GLTF2;
  105417. (function (GLTF2) {
  105418. /** @hidden */
  105419. var _ArrayItem = /** @class */ (function () {
  105420. function _ArrayItem() {
  105421. }
  105422. /** @hidden */
  105423. _ArrayItem.Assign = function (values) {
  105424. if (values) {
  105425. for (var index = 0; index < values.length; index++) {
  105426. values[index]._index = index;
  105427. }
  105428. }
  105429. };
  105430. return _ArrayItem;
  105431. }());
  105432. GLTF2._ArrayItem = _ArrayItem;
  105433. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105434. })(BABYLON || (BABYLON = {}));
  105435. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  105436. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  105437. /**
  105438. * Defines the module used to import/export glTF 2.0 assets
  105439. */
  105440. var BABYLON;
  105441. (function (BABYLON) {
  105442. var GLTF2;
  105443. (function (GLTF2) {
  105444. /**
  105445. * Loader for loading a glTF 2.0 asset
  105446. */
  105447. var GLTFLoader = /** @class */ (function () {
  105448. function GLTFLoader() {
  105449. /** @hidden */
  105450. this._completePromises = new Array();
  105451. /** @hidden */
  105452. this._onReadyObservable = new BABYLON.Observable();
  105453. this._disposed = false;
  105454. this._state = null;
  105455. this._extensions = {};
  105456. this._defaultSampler = {};
  105457. this._defaultBabylonMaterials = {};
  105458. this._requests = new Array();
  105459. /**
  105460. * Mode that determines the coordinate system to use.
  105461. */
  105462. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  105463. /**
  105464. * Mode that determines what animations will start.
  105465. */
  105466. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  105467. /**
  105468. * Defines if the loader should compile materials.
  105469. */
  105470. this.compileMaterials = false;
  105471. /**
  105472. * Defines if the loader should also compile materials with clip planes.
  105473. */
  105474. this.useClipPlane = false;
  105475. /**
  105476. * Defines if the loader should compile shadow generators.
  105477. */
  105478. this.compileShadowGenerators = false;
  105479. /**
  105480. * Defines if the Alpha blended materials are only applied as coverage.
  105481. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  105482. * If true, no extra effects are applied to transparent pixels.
  105483. */
  105484. this.transparencyAsCoverage = false;
  105485. /** @hidden */
  105486. this._normalizeAnimationGroupsToBeginAtZero = true;
  105487. /**
  105488. * Function called before loading a url referenced by the asset.
  105489. */
  105490. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  105491. /**
  105492. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105493. */
  105494. this.onMeshLoadedObservable = new BABYLON.Observable();
  105495. /**
  105496. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  105497. */
  105498. this.onTextureLoadedObservable = new BABYLON.Observable();
  105499. /**
  105500. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  105501. */
  105502. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105503. /**
  105504. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  105505. */
  105506. this.onCameraLoadedObservable = new BABYLON.Observable();
  105507. /**
  105508. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  105509. * For assets with LODs, raised when all of the LODs are complete.
  105510. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  105511. */
  105512. this.onCompleteObservable = new BABYLON.Observable();
  105513. /**
  105514. * Observable raised after the loader is disposed.
  105515. */
  105516. this.onDisposeObservable = new BABYLON.Observable();
  105517. /**
  105518. * Observable raised after a loader extension is created.
  105519. * Set additional options for a loader extension in this event.
  105520. */
  105521. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105522. }
  105523. /** @hidden */
  105524. GLTFLoader._Register = function (name, factory) {
  105525. if (GLTFLoader._ExtensionFactories[name]) {
  105526. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  105527. return;
  105528. }
  105529. GLTFLoader._ExtensionFactories[name] = factory;
  105530. // Keep the order of registration so that extensions registered first are called first.
  105531. GLTFLoader._ExtensionNames.push(name);
  105532. };
  105533. Object.defineProperty(GLTFLoader.prototype, "state", {
  105534. /**
  105535. * Loader state or null if the loader is not active.
  105536. */
  105537. get: function () {
  105538. return this._state;
  105539. },
  105540. enumerable: true,
  105541. configurable: true
  105542. });
  105543. /**
  105544. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105545. */
  105546. GLTFLoader.prototype.dispose = function () {
  105547. if (this._disposed) {
  105548. return;
  105549. }
  105550. this._disposed = true;
  105551. this.onDisposeObservable.notifyObservers(this);
  105552. this.onDisposeObservable.clear();
  105553. this._clear();
  105554. };
  105555. /**
  105556. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  105557. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  105558. * @param scene the scene the meshes should be added to
  105559. * @param data the glTF data to load
  105560. * @param rootUrl root url to load from
  105561. * @param onProgress event that fires when loading progress has occured
  105562. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  105563. */
  105564. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105565. var _this = this;
  105566. return Promise.resolve().then(function () {
  105567. _this._babylonScene = scene;
  105568. _this._rootUrl = rootUrl;
  105569. _this._progressCallback = onProgress;
  105570. _this._loadData(data);
  105571. var nodes = null;
  105572. if (meshesNames) {
  105573. var nodeMap_1 = {};
  105574. if (_this._gltf.nodes) {
  105575. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  105576. var node = _a[_i];
  105577. if (node.name) {
  105578. nodeMap_1[node.name] = node;
  105579. }
  105580. }
  105581. }
  105582. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  105583. nodes = names.map(function (name) {
  105584. var node = nodeMap_1[name];
  105585. if (!node) {
  105586. throw new Error("Failed to find node '" + name + "'");
  105587. }
  105588. return node;
  105589. });
  105590. }
  105591. return _this._loadAsync(nodes).then(function () {
  105592. return {
  105593. meshes: _this._getMeshes(),
  105594. particleSystems: [],
  105595. skeletons: _this._getSkeletons(),
  105596. animationGroups: _this._getAnimationGroups()
  105597. };
  105598. });
  105599. });
  105600. };
  105601. /**
  105602. * Imports all objects from the loaded glTF data and adds them to the scene
  105603. * @param scene the scene the objects should be added to
  105604. * @param data the glTF data to load
  105605. * @param rootUrl root url to load from
  105606. * @param onProgress event that fires when loading progress has occured
  105607. * @returns a promise which completes when objects have been loaded to the scene
  105608. */
  105609. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105610. var _this = this;
  105611. return Promise.resolve().then(function () {
  105612. _this._babylonScene = scene;
  105613. _this._rootUrl = rootUrl;
  105614. _this._progressCallback = onProgress;
  105615. _this._loadData(data);
  105616. return _this._loadAsync(null);
  105617. });
  105618. };
  105619. GLTFLoader.prototype._loadAsync = function (nodes) {
  105620. var _this = this;
  105621. return Promise.resolve().then(function () {
  105622. _this._state = BABYLON.GLTFLoaderState.LOADING;
  105623. _this._loadExtensions();
  105624. _this._checkExtensions();
  105625. var promises = new Array();
  105626. if (nodes) {
  105627. promises.push(_this._loadNodesAsync(nodes));
  105628. }
  105629. else {
  105630. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  105631. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  105632. }
  105633. if (_this.compileMaterials) {
  105634. promises.push(_this._compileMaterialsAsync());
  105635. }
  105636. if (_this.compileShadowGenerators) {
  105637. promises.push(_this._compileShadowGeneratorsAsync());
  105638. }
  105639. var resultPromise = Promise.all(promises).then(function () {
  105640. _this._state = BABYLON.GLTFLoaderState.READY;
  105641. _this._onReadyObservable.notifyObservers(_this);
  105642. _this._startAnimations();
  105643. });
  105644. resultPromise.then(function () {
  105645. if (_this._rootBabylonMesh) {
  105646. _this._rootBabylonMesh.setEnabled(true);
  105647. }
  105648. BABYLON.Tools.SetImmediate(function () {
  105649. if (!_this._disposed) {
  105650. Promise.all(_this._completePromises).then(function () {
  105651. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  105652. _this.onCompleteObservable.notifyObservers(_this);
  105653. _this.onCompleteObservable.clear();
  105654. _this._clear();
  105655. }).catch(function (error) {
  105656. BABYLON.Tools.Error("glTF Loader: " + error.message);
  105657. _this._clear();
  105658. });
  105659. }
  105660. });
  105661. });
  105662. return resultPromise;
  105663. }).catch(function (error) {
  105664. if (!_this._disposed) {
  105665. BABYLON.Tools.Error("glTF Loader: " + error.message);
  105666. _this._clear();
  105667. throw error;
  105668. }
  105669. });
  105670. };
  105671. GLTFLoader.prototype._loadData = function (data) {
  105672. this._gltf = data.json;
  105673. this._setupData();
  105674. if (data.bin) {
  105675. var buffers = this._gltf.buffers;
  105676. if (buffers && buffers[0] && !buffers[0].uri) {
  105677. var binaryBuffer = buffers[0];
  105678. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  105679. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  105680. }
  105681. binaryBuffer._data = Promise.resolve(data.bin);
  105682. }
  105683. else {
  105684. BABYLON.Tools.Warn("Unexpected BIN chunk");
  105685. }
  105686. }
  105687. };
  105688. GLTFLoader.prototype._setupData = function () {
  105689. GLTF2._ArrayItem.Assign(this._gltf.accessors);
  105690. GLTF2._ArrayItem.Assign(this._gltf.animations);
  105691. GLTF2._ArrayItem.Assign(this._gltf.buffers);
  105692. GLTF2._ArrayItem.Assign(this._gltf.bufferViews);
  105693. GLTF2._ArrayItem.Assign(this._gltf.cameras);
  105694. GLTF2._ArrayItem.Assign(this._gltf.images);
  105695. GLTF2._ArrayItem.Assign(this._gltf.materials);
  105696. GLTF2._ArrayItem.Assign(this._gltf.meshes);
  105697. GLTF2._ArrayItem.Assign(this._gltf.nodes);
  105698. GLTF2._ArrayItem.Assign(this._gltf.samplers);
  105699. GLTF2._ArrayItem.Assign(this._gltf.scenes);
  105700. GLTF2._ArrayItem.Assign(this._gltf.skins);
  105701. GLTF2._ArrayItem.Assign(this._gltf.textures);
  105702. if (this._gltf.nodes) {
  105703. var nodeParents = {};
  105704. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  105705. var node = _a[_i];
  105706. if (node.children) {
  105707. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  105708. var index = _c[_b];
  105709. nodeParents[index] = node._index;
  105710. }
  105711. }
  105712. }
  105713. var rootNode = this._createRootNode();
  105714. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  105715. var node = _e[_d];
  105716. var parentIndex = nodeParents[node._index];
  105717. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  105718. }
  105719. }
  105720. };
  105721. GLTFLoader.prototype._loadExtensions = function () {
  105722. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  105723. var name_1 = _a[_i];
  105724. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  105725. this._extensions[name_1] = extension;
  105726. this.onExtensionLoadedObservable.notifyObservers(extension);
  105727. }
  105728. this.onExtensionLoadedObservable.clear();
  105729. };
  105730. GLTFLoader.prototype._checkExtensions = function () {
  105731. if (this._gltf.extensionsRequired) {
  105732. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  105733. var name_2 = _a[_i];
  105734. var extension = this._extensions[name_2];
  105735. if (!extension || !extension.enabled) {
  105736. throw new Error("Require extension " + name_2 + " is not available");
  105737. }
  105738. }
  105739. }
  105740. };
  105741. GLTFLoader.prototype._createRootNode = function () {
  105742. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  105743. this._rootBabylonMesh.setEnabled(false);
  105744. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  105745. switch (this.coordinateSystemMode) {
  105746. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  105747. if (!this._babylonScene.useRightHandedSystem) {
  105748. rootNode.rotation = [0, 1, 0, 0];
  105749. rootNode.scale = [1, 1, -1];
  105750. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  105751. }
  105752. break;
  105753. }
  105754. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  105755. this._babylonScene.useRightHandedSystem = true;
  105756. break;
  105757. }
  105758. default: {
  105759. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  105760. }
  105761. }
  105762. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  105763. return rootNode;
  105764. };
  105765. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  105766. var promises = new Array();
  105767. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  105768. var node = nodes_1[_i];
  105769. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  105770. }
  105771. promises.push(this._loadAnimationsAsync());
  105772. return Promise.all(promises).then(function () { });
  105773. };
  105774. /** @hidden */
  105775. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  105776. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  105777. if (promise) {
  105778. return promise;
  105779. }
  105780. var promises = new Array();
  105781. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  105782. var index = _a[_i];
  105783. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  105784. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  105785. }
  105786. promises.push(this._loadAnimationsAsync());
  105787. return Promise.all(promises).then(function () { });
  105788. };
  105789. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  105790. if (node._primitiveBabylonMeshes) {
  105791. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  105792. var babylonMesh = _a[_i];
  105793. callback(babylonMesh);
  105794. }
  105795. }
  105796. else {
  105797. callback(node._babylonMesh);
  105798. }
  105799. };
  105800. GLTFLoader.prototype._getMeshes = function () {
  105801. var meshes = new Array();
  105802. // Root mesh is always first.
  105803. meshes.push(this._rootBabylonMesh);
  105804. var nodes = this._gltf.nodes;
  105805. if (nodes) {
  105806. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  105807. var node = nodes_2[_i];
  105808. if (node._babylonMesh) {
  105809. meshes.push(node._babylonMesh);
  105810. }
  105811. if (node._primitiveBabylonMeshes) {
  105812. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  105813. var babylonMesh = _b[_a];
  105814. meshes.push(babylonMesh);
  105815. }
  105816. }
  105817. }
  105818. }
  105819. return meshes;
  105820. };
  105821. GLTFLoader.prototype._getSkeletons = function () {
  105822. var skeletons = new Array();
  105823. var skins = this._gltf.skins;
  105824. if (skins) {
  105825. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  105826. var skin = skins_1[_i];
  105827. if (skin._babylonSkeleton) {
  105828. skeletons.push(skin._babylonSkeleton);
  105829. }
  105830. }
  105831. }
  105832. return skeletons;
  105833. };
  105834. GLTFLoader.prototype._getAnimationGroups = function () {
  105835. var animationGroups = new Array();
  105836. var animations = this._gltf.animations;
  105837. if (animations) {
  105838. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  105839. var animation = animations_1[_i];
  105840. if (animation._babylonAnimationGroup) {
  105841. animationGroups.push(animation._babylonAnimationGroup);
  105842. }
  105843. }
  105844. }
  105845. return animationGroups;
  105846. };
  105847. GLTFLoader.prototype._startAnimations = function () {
  105848. switch (this.animationStartMode) {
  105849. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  105850. // do nothing
  105851. break;
  105852. }
  105853. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  105854. var babylonAnimationGroups = this._getAnimationGroups();
  105855. if (babylonAnimationGroups.length !== 0) {
  105856. babylonAnimationGroups[0].start(true);
  105857. }
  105858. break;
  105859. }
  105860. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  105861. var babylonAnimationGroups = this._getAnimationGroups();
  105862. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  105863. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  105864. babylonAnimationGroup.start(true);
  105865. }
  105866. break;
  105867. }
  105868. default: {
  105869. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  105870. return;
  105871. }
  105872. }
  105873. };
  105874. /** @hidden */
  105875. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  105876. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  105877. if (promise) {
  105878. return promise;
  105879. }
  105880. if (node._babylonMesh) {
  105881. throw new Error(context + ": Invalid recursive node hierarchy");
  105882. }
  105883. var promises = new Array();
  105884. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  105885. node._babylonMesh = babylonMesh;
  105886. GLTFLoader._LoadTransform(node, babylonMesh);
  105887. if (node.mesh != undefined) {
  105888. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  105889. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  105890. }
  105891. if (node.camera != undefined) {
  105892. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  105893. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  105894. }
  105895. if (node.children) {
  105896. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  105897. var index = _a[_i];
  105898. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  105899. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  105900. }
  105901. }
  105902. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  105903. return Promise.all(promises).then(function () { });
  105904. };
  105905. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  105906. var _this = this;
  105907. var promises = new Array();
  105908. var primitives = mesh.primitives;
  105909. if (!primitives || primitives.length === 0) {
  105910. throw new Error(context + ": Primitives are missing");
  105911. }
  105912. GLTF2._ArrayItem.Assign(primitives);
  105913. if (primitives.length === 1) {
  105914. var primitive = primitives[0];
  105915. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  105916. }
  105917. else {
  105918. node._primitiveBabylonMeshes = [];
  105919. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  105920. var primitive = primitives_1[_i];
  105921. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  105922. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  105923. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  105924. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  105925. }
  105926. }
  105927. if (node.skin != undefined) {
  105928. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  105929. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  105930. }
  105931. return Promise.all(promises).then(function () {
  105932. _this._forEachPrimitive(node, function (babylonMesh) {
  105933. babylonMesh._refreshBoundingInfo(true);
  105934. });
  105935. });
  105936. };
  105937. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  105938. var _this = this;
  105939. var promises = new Array();
  105940. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  105941. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  105942. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  105943. babylonGeometry.applyToMesh(babylonMesh);
  105944. });
  105945. }));
  105946. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  105947. if (primitive.material == undefined) {
  105948. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  105949. }
  105950. else {
  105951. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  105952. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  105953. babylonMesh.material = babylonMaterial;
  105954. }));
  105955. }
  105956. return Promise.all(promises).then(function () { });
  105957. };
  105958. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  105959. var _this = this;
  105960. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  105961. if (promise) {
  105962. return promise;
  105963. }
  105964. var attributes = primitive.attributes;
  105965. if (!attributes) {
  105966. throw new Error(context + ": Attributes are missing");
  105967. }
  105968. var promises = new Array();
  105969. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  105970. if (primitive.indices == undefined) {
  105971. babylonMesh.isUnIndexed = true;
  105972. }
  105973. else {
  105974. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  105975. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  105976. babylonGeometry.setIndices(data);
  105977. }));
  105978. }
  105979. var loadAttribute = function (attribute, kind, callback) {
  105980. if (attributes[attribute] == undefined) {
  105981. return;
  105982. }
  105983. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  105984. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  105985. babylonMesh._delayInfo.push(kind);
  105986. }
  105987. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  105988. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  105989. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  105990. }));
  105991. if (callback) {
  105992. callback(accessor);
  105993. }
  105994. };
  105995. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  105996. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  105997. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  105998. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  105999. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  106000. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  106001. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  106002. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  106003. if (accessor.type === "VEC4" /* VEC4 */) {
  106004. babylonMesh.hasVertexAlpha = true;
  106005. }
  106006. });
  106007. return Promise.all(promises).then(function () {
  106008. return babylonGeometry;
  106009. });
  106010. };
  106011. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  106012. if (!primitive.targets) {
  106013. return;
  106014. }
  106015. if (node._numMorphTargets == undefined) {
  106016. node._numMorphTargets = primitive.targets.length;
  106017. }
  106018. else if (primitive.targets.length !== node._numMorphTargets) {
  106019. throw new Error(context + ": Primitives do not have the same number of targets");
  106020. }
  106021. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  106022. for (var index = 0; index < primitive.targets.length; index++) {
  106023. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  106024. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  106025. // TODO: tell the target whether it has positions, normals, tangents
  106026. }
  106027. };
  106028. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  106029. if (!primitive.targets) {
  106030. return Promise.resolve();
  106031. }
  106032. var promises = new Array();
  106033. var morphTargetManager = babylonMesh.morphTargetManager;
  106034. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  106035. var babylonMorphTarget = morphTargetManager.getTarget(index);
  106036. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  106037. }
  106038. return Promise.all(promises).then(function () { });
  106039. };
  106040. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  106041. var _this = this;
  106042. var promises = new Array();
  106043. var loadAttribute = function (attribute, kind, setData) {
  106044. if (attributes[attribute] == undefined) {
  106045. return;
  106046. }
  106047. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  106048. if (!babylonVertexBuffer) {
  106049. return;
  106050. }
  106051. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  106052. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  106053. setData(babylonVertexBuffer, data);
  106054. }));
  106055. };
  106056. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  106057. babylonVertexBuffer.forEach(data.length, function (value, index) {
  106058. data[index] += value;
  106059. });
  106060. babylonMorphTarget.setPositions(data);
  106061. });
  106062. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  106063. babylonVertexBuffer.forEach(data.length, function (value, index) {
  106064. data[index] += value;
  106065. });
  106066. babylonMorphTarget.setNormals(data);
  106067. });
  106068. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  106069. var dataIndex = 0;
  106070. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  106071. // Tangent data for morph targets is stored as xyz delta.
  106072. // The vertexData.tangent is stored as xyzw.
  106073. // So we need to skip every fourth vertexData.tangent.
  106074. if (((index + 1) % 4) !== 0) {
  106075. data[dataIndex++] += value;
  106076. }
  106077. });
  106078. babylonMorphTarget.setTangents(data);
  106079. });
  106080. return Promise.all(promises).then(function () { });
  106081. };
  106082. GLTFLoader._LoadTransform = function (node, babylonNode) {
  106083. var position = BABYLON.Vector3.Zero();
  106084. var rotation = BABYLON.Quaternion.Identity();
  106085. var scaling = BABYLON.Vector3.One();
  106086. if (node.matrix) {
  106087. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  106088. matrix.decompose(scaling, rotation, position);
  106089. }
  106090. else {
  106091. if (node.translation)
  106092. position = BABYLON.Vector3.FromArray(node.translation);
  106093. if (node.rotation)
  106094. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  106095. if (node.scale)
  106096. scaling = BABYLON.Vector3.FromArray(node.scale);
  106097. }
  106098. babylonNode.position = position;
  106099. babylonNode.rotationQuaternion = rotation;
  106100. babylonNode.scaling = scaling;
  106101. };
  106102. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  106103. var _this = this;
  106104. var assignSkeleton = function (skeleton) {
  106105. _this._forEachPrimitive(node, function (babylonMesh) {
  106106. babylonMesh.skeleton = skeleton;
  106107. });
  106108. // Ignore the TRS of skinned nodes.
  106109. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  106110. node._babylonMesh.parent = _this._rootBabylonMesh;
  106111. node._babylonMesh.position = BABYLON.Vector3.Zero();
  106112. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  106113. node._babylonMesh.scaling = BABYLON.Vector3.One();
  106114. };
  106115. if (skin._loaded) {
  106116. return skin._loaded.then(function () {
  106117. assignSkeleton(skin._babylonSkeleton);
  106118. });
  106119. }
  106120. var skeletonId = "skeleton" + skin._index;
  106121. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  106122. skin._babylonSkeleton = babylonSkeleton;
  106123. this._loadBones(context, skin);
  106124. assignSkeleton(babylonSkeleton);
  106125. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  106126. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  106127. }));
  106128. };
  106129. GLTFLoader.prototype._loadBones = function (context, skin) {
  106130. var babylonBones = {};
  106131. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  106132. var index = _a[_i];
  106133. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  106134. this._loadBone(node, skin, babylonBones);
  106135. }
  106136. };
  106137. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  106138. var babylonBone = babylonBones[node._index];
  106139. if (babylonBone) {
  106140. return babylonBone;
  106141. }
  106142. var babylonParentBone = null;
  106143. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  106144. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  106145. }
  106146. var boneIndex = skin.joints.indexOf(node._index);
  106147. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  106148. babylonBones[node._index] = babylonBone;
  106149. node._babylonBones = node._babylonBones || [];
  106150. node._babylonBones.push(babylonBone);
  106151. return babylonBone;
  106152. };
  106153. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  106154. if (skin.inverseBindMatrices == undefined) {
  106155. return Promise.resolve(null);
  106156. }
  106157. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  106158. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  106159. };
  106160. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  106161. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  106162. var babylonBone = _a[_i];
  106163. var baseMatrix = BABYLON.Matrix.Identity();
  106164. var boneIndex = babylonBone._index;
  106165. if (inverseBindMatricesData && boneIndex !== -1) {
  106166. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  106167. baseMatrix.invertToRef(baseMatrix);
  106168. }
  106169. var babylonParentBone = babylonBone.getParent();
  106170. if (babylonParentBone) {
  106171. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  106172. }
  106173. babylonBone.updateMatrix(baseMatrix, false, false);
  106174. babylonBone._updateDifferenceMatrix(undefined, false);
  106175. }
  106176. };
  106177. GLTFLoader.prototype._getNodeMatrix = function (node) {
  106178. return node.matrix ?
  106179. BABYLON.Matrix.FromArray(node.matrix) :
  106180. 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());
  106181. };
  106182. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  106183. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  106184. babylonCamera.parent = babylonMesh;
  106185. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  106186. switch (camera.type) {
  106187. case "perspective" /* PERSPECTIVE */: {
  106188. var perspective = camera.perspective;
  106189. if (!perspective) {
  106190. throw new Error(context + ": Camera perspective properties are missing");
  106191. }
  106192. babylonCamera.fov = perspective.yfov;
  106193. babylonCamera.minZ = perspective.znear;
  106194. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  106195. break;
  106196. }
  106197. case "orthographic" /* ORTHOGRAPHIC */: {
  106198. if (!camera.orthographic) {
  106199. throw new Error(context + ": Camera orthographic properties are missing");
  106200. }
  106201. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  106202. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  106203. babylonCamera.orthoRight = camera.orthographic.xmag;
  106204. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  106205. babylonCamera.orthoTop = camera.orthographic.ymag;
  106206. babylonCamera.minZ = camera.orthographic.znear;
  106207. babylonCamera.maxZ = camera.orthographic.zfar;
  106208. break;
  106209. }
  106210. default: {
  106211. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  106212. }
  106213. }
  106214. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  106215. };
  106216. GLTFLoader.prototype._loadAnimationsAsync = function () {
  106217. var animations = this._gltf.animations;
  106218. if (!animations) {
  106219. return Promise.resolve();
  106220. }
  106221. var promises = new Array();
  106222. for (var index = 0; index < animations.length; index++) {
  106223. var animation = animations[index];
  106224. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  106225. }
  106226. return Promise.all(promises).then(function () { });
  106227. };
  106228. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  106229. var _this = this;
  106230. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  106231. animation._babylonAnimationGroup = babylonAnimationGroup;
  106232. var promises = new Array();
  106233. GLTF2._ArrayItem.Assign(animation.channels);
  106234. GLTF2._ArrayItem.Assign(animation.samplers);
  106235. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  106236. var channel = _a[_i];
  106237. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  106238. }
  106239. return Promise.all(promises).then(function () {
  106240. babylonAnimationGroup.normalize(_this._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  106241. });
  106242. };
  106243. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  106244. var _this = this;
  106245. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  106246. // Ignore animations that have no animation targets.
  106247. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  106248. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  106249. return Promise.resolve();
  106250. }
  106251. // Ignore animations targeting TRS of skinned nodes.
  106252. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  106253. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  106254. return Promise.resolve();
  106255. }
  106256. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  106257. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  106258. var targetPath;
  106259. var animationType;
  106260. switch (channel.target.path) {
  106261. case "translation" /* TRANSLATION */: {
  106262. targetPath = "position";
  106263. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106264. break;
  106265. }
  106266. case "rotation" /* ROTATION */: {
  106267. targetPath = "rotationQuaternion";
  106268. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106269. break;
  106270. }
  106271. case "scale" /* SCALE */: {
  106272. targetPath = "scaling";
  106273. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106274. break;
  106275. }
  106276. case "weights" /* WEIGHTS */: {
  106277. targetPath = "influence";
  106278. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  106279. break;
  106280. }
  106281. default: {
  106282. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  106283. }
  106284. }
  106285. var outputBufferOffset = 0;
  106286. var getNextOutputValue;
  106287. switch (targetPath) {
  106288. case "position": {
  106289. getNextOutputValue = function () {
  106290. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  106291. outputBufferOffset += 3;
  106292. return value;
  106293. };
  106294. break;
  106295. }
  106296. case "rotationQuaternion": {
  106297. getNextOutputValue = function () {
  106298. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  106299. outputBufferOffset += 4;
  106300. return value;
  106301. };
  106302. break;
  106303. }
  106304. case "scaling": {
  106305. getNextOutputValue = function () {
  106306. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  106307. outputBufferOffset += 3;
  106308. return value;
  106309. };
  106310. break;
  106311. }
  106312. case "influence": {
  106313. getNextOutputValue = function () {
  106314. var value = new Array(targetNode._numMorphTargets);
  106315. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  106316. value[i] = data.output[outputBufferOffset++];
  106317. }
  106318. return value;
  106319. };
  106320. break;
  106321. }
  106322. }
  106323. var getNextKey;
  106324. switch (data.interpolation) {
  106325. case "STEP" /* STEP */: {
  106326. getNextKey = function (frameIndex) { return ({
  106327. frame: data.input[frameIndex],
  106328. value: getNextOutputValue(),
  106329. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  106330. }); };
  106331. break;
  106332. }
  106333. case "LINEAR" /* LINEAR */: {
  106334. getNextKey = function (frameIndex) { return ({
  106335. frame: data.input[frameIndex],
  106336. value: getNextOutputValue()
  106337. }); };
  106338. break;
  106339. }
  106340. case "CUBICSPLINE" /* CUBICSPLINE */: {
  106341. getNextKey = function (frameIndex) { return ({
  106342. frame: data.input[frameIndex],
  106343. inTangent: getNextOutputValue(),
  106344. value: getNextOutputValue(),
  106345. outTangent: getNextOutputValue()
  106346. }); };
  106347. break;
  106348. }
  106349. }
  106350. var keys = new Array(data.input.length);
  106351. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  106352. keys[frameIndex] = getNextKey(frameIndex);
  106353. }
  106354. if (targetPath === "influence") {
  106355. var _loop_1 = function (targetIndex) {
  106356. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  106357. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  106358. babylonAnimation.setKeys(keys.map(function (key) { return ({
  106359. frame: key.frame,
  106360. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  106361. value: key.value[targetIndex],
  106362. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  106363. }); }));
  106364. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  106365. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  106366. var babylonAnimationClone = babylonAnimation.clone();
  106367. morphTarget.animations.push(babylonAnimationClone);
  106368. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  106369. });
  106370. };
  106371. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  106372. _loop_1(targetIndex);
  106373. }
  106374. }
  106375. else {
  106376. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  106377. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  106378. babylonAnimation.setKeys(keys);
  106379. if (targetNode._babylonBones) {
  106380. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  106381. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  106382. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  106383. babylonAnimationTarget.animations.push(babylonAnimation);
  106384. }
  106385. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  106386. }
  106387. else {
  106388. targetNode._babylonMesh.animations.push(babylonAnimation);
  106389. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  106390. }
  106391. }
  106392. });
  106393. };
  106394. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  106395. if (sampler._data) {
  106396. return sampler._data;
  106397. }
  106398. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  106399. switch (interpolation) {
  106400. case "STEP" /* STEP */:
  106401. case "LINEAR" /* LINEAR */:
  106402. case "CUBICSPLINE" /* CUBICSPLINE */: {
  106403. break;
  106404. }
  106405. default: {
  106406. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  106407. }
  106408. }
  106409. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  106410. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  106411. sampler._data = Promise.all([
  106412. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  106413. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  106414. ]).then(function (_a) {
  106415. var inputData = _a[0], outputData = _a[1];
  106416. return {
  106417. input: inputData,
  106418. interpolation: interpolation,
  106419. output: outputData,
  106420. };
  106421. });
  106422. return sampler._data;
  106423. };
  106424. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  106425. if (buffer._data) {
  106426. return buffer._data;
  106427. }
  106428. if (!buffer.uri) {
  106429. throw new Error(context + ": Uri is missing");
  106430. }
  106431. buffer._data = this._loadUriAsync(context, buffer.uri);
  106432. return buffer._data;
  106433. };
  106434. /** @hidden */
  106435. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  106436. if (bufferView._data) {
  106437. return bufferView._data;
  106438. }
  106439. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  106440. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  106441. try {
  106442. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  106443. }
  106444. catch (e) {
  106445. throw new Error(context + ": " + e.message);
  106446. }
  106447. });
  106448. return bufferView._data;
  106449. };
  106450. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  106451. if (accessor.type !== "SCALAR" /* SCALAR */) {
  106452. throw new Error(context + ": Invalid type " + accessor.type);
  106453. }
  106454. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  106455. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  106456. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  106457. throw new Error(context + ": Invalid component type " + accessor.componentType);
  106458. }
  106459. if (accessor._data) {
  106460. return accessor._data;
  106461. }
  106462. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  106463. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  106464. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  106465. });
  106466. return accessor._data;
  106467. };
  106468. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  106469. // TODO: support normalized and stride
  106470. var _this = this;
  106471. if (accessor.componentType !== 5126 /* FLOAT */) {
  106472. throw new Error("Invalid component type " + accessor.componentType);
  106473. }
  106474. if (accessor._data) {
  106475. return accessor._data;
  106476. }
  106477. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  106478. var length = numComponents * accessor.count;
  106479. if (accessor.bufferView == undefined) {
  106480. accessor._data = Promise.resolve(new Float32Array(length));
  106481. }
  106482. else {
  106483. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  106484. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  106485. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  106486. });
  106487. }
  106488. if (accessor.sparse) {
  106489. var sparse_1 = accessor.sparse;
  106490. accessor._data = accessor._data.then(function (data) {
  106491. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  106492. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  106493. return Promise.all([
  106494. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  106495. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  106496. ]).then(function (_a) {
  106497. var indicesData = _a[0], valuesData = _a[1];
  106498. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  106499. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  106500. var valuesIndex = 0;
  106501. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  106502. var dataIndex = indices[indicesIndex] * numComponents;
  106503. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  106504. data[dataIndex++] = values[valuesIndex++];
  106505. }
  106506. }
  106507. return data;
  106508. });
  106509. });
  106510. }
  106511. return accessor._data;
  106512. };
  106513. /** @hidden */
  106514. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  106515. var _this = this;
  106516. if (bufferView._babylonBuffer) {
  106517. return bufferView._babylonBuffer;
  106518. }
  106519. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  106520. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  106521. });
  106522. return bufferView._babylonBuffer;
  106523. };
  106524. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  106525. var _this = this;
  106526. if (accessor._babylonVertexBuffer) {
  106527. return accessor._babylonVertexBuffer;
  106528. }
  106529. if (accessor.sparse) {
  106530. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  106531. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  106532. });
  106533. }
  106534. else {
  106535. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  106536. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  106537. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  106538. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  106539. });
  106540. }
  106541. return accessor._babylonVertexBuffer;
  106542. };
  106543. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  106544. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  106545. if (!babylonMaterial) {
  106546. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  106547. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  106548. babylonMaterial.metallic = 1;
  106549. babylonMaterial.roughness = 1;
  106550. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106551. }
  106552. return babylonMaterial;
  106553. };
  106554. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  106555. var promises = new Array();
  106556. // Ensure metallic workflow
  106557. babylonMaterial.metallic = 1;
  106558. babylonMaterial.roughness = 1;
  106559. var properties = material.pbrMetallicRoughness;
  106560. if (properties) {
  106561. if (properties.baseColorFactor) {
  106562. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  106563. babylonMaterial.alpha = properties.baseColorFactor[3];
  106564. }
  106565. else {
  106566. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106567. }
  106568. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  106569. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  106570. if (properties.baseColorTexture) {
  106571. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  106572. babylonMaterial.albedoTexture = texture;
  106573. }));
  106574. }
  106575. if (properties.metallicRoughnessTexture) {
  106576. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  106577. babylonMaterial.metallicTexture = texture;
  106578. }));
  106579. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  106580. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  106581. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  106582. }
  106583. }
  106584. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106585. return Promise.all(promises).then(function () { });
  106586. };
  106587. /** @hidden */
  106588. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106589. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  106590. if (promise) {
  106591. return promise;
  106592. }
  106593. material._babylonData = material._babylonData || {};
  106594. var babylonData = material._babylonData[babylonDrawMode];
  106595. if (!babylonData) {
  106596. var promises = new Array();
  106597. var name_3 = material.name || "materialSG_" + material._index;
  106598. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  106599. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  106600. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  106601. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106602. babylonData = {
  106603. material: babylonMaterial,
  106604. meshes: [],
  106605. loaded: Promise.all(promises).then(function () { })
  106606. };
  106607. material._babylonData[babylonDrawMode] = babylonData;
  106608. }
  106609. babylonData.meshes.push(babylonMesh);
  106610. assign(babylonData.material);
  106611. return babylonData.loaded;
  106612. };
  106613. /** @hidden */
  106614. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  106615. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  106616. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  106617. babylonMaterial.fillMode = drawMode;
  106618. babylonMaterial.enableSpecularAntiAliasing = true;
  106619. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  106620. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  106621. return babylonMaterial;
  106622. };
  106623. /** @hidden */
  106624. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  106625. var promises = new Array();
  106626. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  106627. if (material.doubleSided) {
  106628. babylonMaterial.backFaceCulling = false;
  106629. babylonMaterial.twoSidedLighting = true;
  106630. }
  106631. if (material.normalTexture) {
  106632. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  106633. babylonMaterial.bumpTexture = texture;
  106634. }));
  106635. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  106636. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  106637. if (material.normalTexture.scale != undefined) {
  106638. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  106639. }
  106640. }
  106641. if (material.occlusionTexture) {
  106642. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  106643. babylonMaterial.ambientTexture = texture;
  106644. }));
  106645. babylonMaterial.useAmbientInGrayScale = true;
  106646. if (material.occlusionTexture.strength != undefined) {
  106647. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  106648. }
  106649. }
  106650. if (material.emissiveTexture) {
  106651. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  106652. babylonMaterial.emissiveTexture = texture;
  106653. }));
  106654. }
  106655. return Promise.all(promises).then(function () { });
  106656. };
  106657. /** @hidden */
  106658. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  106659. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  106660. switch (alphaMode) {
  106661. case "OPAQUE" /* OPAQUE */: {
  106662. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  106663. break;
  106664. }
  106665. case "MASK" /* MASK */: {
  106666. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  106667. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  106668. if (babylonMaterial.albedoTexture) {
  106669. babylonMaterial.albedoTexture.hasAlpha = true;
  106670. }
  106671. break;
  106672. }
  106673. case "BLEND" /* BLEND */: {
  106674. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  106675. if (babylonMaterial.albedoTexture) {
  106676. babylonMaterial.albedoTexture.hasAlpha = true;
  106677. babylonMaterial.useAlphaFromAlbedoTexture = true;
  106678. }
  106679. break;
  106680. }
  106681. default: {
  106682. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  106683. }
  106684. }
  106685. };
  106686. /** @hidden */
  106687. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  106688. var _this = this;
  106689. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  106690. if (promise) {
  106691. return promise;
  106692. }
  106693. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  106694. context = "#/textures/" + textureInfo.index;
  106695. var promises = new Array();
  106696. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  106697. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  106698. var deferred = new BABYLON.Deferred();
  106699. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  106700. if (!_this._disposed) {
  106701. deferred.resolve();
  106702. }
  106703. }, function (message, exception) {
  106704. if (!_this._disposed) {
  106705. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  106706. }
  106707. });
  106708. promises.push(deferred.promise);
  106709. babylonTexture.name = texture.name || "texture" + texture._index;
  106710. babylonTexture.wrapU = samplerData.wrapU;
  106711. babylonTexture.wrapV = samplerData.wrapV;
  106712. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  106713. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  106714. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  106715. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  106716. babylonTexture.updateURL(dataUrl, blob);
  106717. }));
  106718. assign(babylonTexture);
  106719. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  106720. return Promise.all(promises).then(function () { });
  106721. };
  106722. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  106723. if (!sampler._data) {
  106724. sampler._data = {
  106725. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  106726. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  106727. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  106728. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  106729. };
  106730. }
  106731. ;
  106732. return sampler._data;
  106733. };
  106734. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  106735. if (image._blob) {
  106736. return image._blob;
  106737. }
  106738. var promise;
  106739. if (image.uri) {
  106740. promise = this._loadUriAsync(context, image.uri);
  106741. }
  106742. else {
  106743. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  106744. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  106745. }
  106746. image._blob = promise.then(function (data) {
  106747. return new Blob([data], { type: image.mimeType });
  106748. });
  106749. return image._blob;
  106750. };
  106751. /** @hidden */
  106752. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  106753. var _this = this;
  106754. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  106755. if (promise) {
  106756. return promise;
  106757. }
  106758. if (!GLTFLoader._ValidateUri(uri)) {
  106759. throw new Error(context + ": Uri '" + uri + "' is invalid");
  106760. }
  106761. if (BABYLON.Tools.IsBase64(uri)) {
  106762. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  106763. }
  106764. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  106765. return new Promise(function (resolve, reject) {
  106766. if (!_this._disposed) {
  106767. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  106768. if (!_this._disposed) {
  106769. resolve(new Uint8Array(data));
  106770. }
  106771. }, function (event) {
  106772. if (!_this._disposed) {
  106773. try {
  106774. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  106775. request_1._lengthComputable = event.lengthComputable;
  106776. request_1._loaded = event.loaded;
  106777. request_1._total = event.total;
  106778. _this._onProgress();
  106779. }
  106780. }
  106781. catch (e) {
  106782. reject(e);
  106783. }
  106784. }
  106785. }, _this._babylonScene.database, true, function (request, exception) {
  106786. if (!_this._disposed) {
  106787. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  106788. }
  106789. });
  106790. _this._requests.push(request_1);
  106791. }
  106792. });
  106793. });
  106794. };
  106795. GLTFLoader.prototype._onProgress = function () {
  106796. if (!this._progressCallback) {
  106797. return;
  106798. }
  106799. var lengthComputable = true;
  106800. var loaded = 0;
  106801. var total = 0;
  106802. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  106803. var request = _a[_i];
  106804. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  106805. return;
  106806. }
  106807. lengthComputable = lengthComputable && request._lengthComputable;
  106808. loaded += request._loaded;
  106809. total += request._total;
  106810. }
  106811. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  106812. };
  106813. /** @hidden */
  106814. GLTFLoader._GetProperty = function (context, array, index) {
  106815. if (!array || index == undefined || !array[index]) {
  106816. throw new Error(context + ": Failed to find index (" + index + ")");
  106817. }
  106818. return array[index];
  106819. };
  106820. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  106821. // Set defaults if undefined
  106822. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  106823. switch (mode) {
  106824. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  106825. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  106826. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106827. default:
  106828. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  106829. return BABYLON.Texture.WRAP_ADDRESSMODE;
  106830. }
  106831. };
  106832. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  106833. // Set defaults if undefined
  106834. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  106835. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  106836. if (magFilter === 9729 /* LINEAR */) {
  106837. switch (minFilter) {
  106838. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  106839. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  106840. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  106841. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  106842. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  106843. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  106844. default:
  106845. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  106846. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  106847. }
  106848. }
  106849. else {
  106850. if (magFilter !== 9728 /* NEAREST */) {
  106851. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  106852. }
  106853. switch (minFilter) {
  106854. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  106855. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  106856. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  106857. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  106858. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  106859. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  106860. default:
  106861. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  106862. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  106863. }
  106864. }
  106865. };
  106866. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  106867. var buffer = bufferView.buffer;
  106868. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  106869. try {
  106870. switch (componentType) {
  106871. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  106872. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  106873. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  106874. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  106875. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  106876. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  106877. default: throw new Error("Invalid component type " + componentType);
  106878. }
  106879. }
  106880. catch (e) {
  106881. throw new Error(context + ": " + e);
  106882. }
  106883. };
  106884. GLTFLoader._GetNumComponents = function (context, type) {
  106885. switch (type) {
  106886. case "SCALAR": return 1;
  106887. case "VEC2": return 2;
  106888. case "VEC3": return 3;
  106889. case "VEC4": return 4;
  106890. case "MAT2": return 4;
  106891. case "MAT3": return 9;
  106892. case "MAT4": return 16;
  106893. }
  106894. throw new Error(context + ": Invalid type (" + type + ")");
  106895. };
  106896. GLTFLoader._ValidateUri = function (uri) {
  106897. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  106898. };
  106899. GLTFLoader._GetDrawMode = function (context, mode) {
  106900. if (mode == undefined) {
  106901. mode = 4 /* TRIANGLES */;
  106902. }
  106903. switch (mode) {
  106904. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  106905. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  106906. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  106907. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  106908. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  106909. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  106910. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  106911. }
  106912. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  106913. };
  106914. GLTFLoader.prototype._compileMaterialsAsync = function () {
  106915. var promises = new Array();
  106916. if (this._gltf.materials) {
  106917. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  106918. var material = _a[_i];
  106919. if (material._babylonData) {
  106920. for (var babylonDrawMode in material._babylonData) {
  106921. var babylonData = material._babylonData[babylonDrawMode];
  106922. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  106923. var babylonMesh = _c[_b];
  106924. // Ensure nonUniformScaling is set if necessary.
  106925. babylonMesh.computeWorldMatrix(true);
  106926. var babylonMaterial = babylonData.material;
  106927. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  106928. if (this.useClipPlane) {
  106929. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  106930. }
  106931. }
  106932. }
  106933. }
  106934. }
  106935. }
  106936. return Promise.all(promises).then(function () { });
  106937. };
  106938. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  106939. var promises = new Array();
  106940. var lights = this._babylonScene.lights;
  106941. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  106942. var light = lights_1[_i];
  106943. var generator = light.getShadowGenerator();
  106944. if (generator) {
  106945. promises.push(generator.forceCompilationAsync());
  106946. }
  106947. }
  106948. return Promise.all(promises).then(function () { });
  106949. };
  106950. GLTFLoader.prototype._clear = function () {
  106951. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  106952. var request = _a[_i];
  106953. request.abort();
  106954. }
  106955. this._requests.length = 0;
  106956. delete this._gltf;
  106957. delete this._babylonScene;
  106958. this._completePromises.length = 0;
  106959. this._onReadyObservable.clear();
  106960. for (var name_4 in this._extensions) {
  106961. this._extensions[name_4].dispose();
  106962. }
  106963. this._extensions = {};
  106964. delete this._rootBabylonMesh;
  106965. delete this._progressCallback;
  106966. this.onMeshLoadedObservable.clear();
  106967. this.onTextureLoadedObservable.clear();
  106968. this.onMaterialLoadedObservable.clear();
  106969. this.onCameraLoadedObservable.clear();
  106970. };
  106971. /** @hidden */
  106972. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  106973. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  106974. var name_5 = _a[_i];
  106975. var extension = this._extensions[name_5];
  106976. if (extension.enabled) {
  106977. var promise = actionAsync(extension);
  106978. if (promise) {
  106979. return promise;
  106980. }
  106981. }
  106982. }
  106983. return null;
  106984. };
  106985. GLTFLoader._ExtensionNames = new Array();
  106986. GLTFLoader._ExtensionFactories = {};
  106987. return GLTFLoader;
  106988. }());
  106989. GLTF2.GLTFLoader = GLTFLoader;
  106990. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  106991. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106992. })(BABYLON || (BABYLON = {}));
  106993. //# sourceMappingURL=babylon.glTFLoader.js.map
  106994. var BABYLON;
  106995. (function (BABYLON) {
  106996. var GLTF2;
  106997. (function (GLTF2) {
  106998. /**
  106999. * Abstract class that can be implemented to extend existing glTF loader behavior.
  107000. */
  107001. var GLTFLoaderExtension = /** @class */ (function () {
  107002. function GLTFLoaderExtension(loader) {
  107003. this.enabled = true;
  107004. this._loader = loader;
  107005. }
  107006. GLTFLoaderExtension.prototype.dispose = function () {
  107007. delete this._loader;
  107008. };
  107009. // #region Overridable Methods
  107010. /** Override this method to modify the default behavior for loading scenes. */
  107011. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  107012. /** Override this method to modify the default behavior for loading nodes. */
  107013. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  107014. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  107015. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  107016. /** Override this method to modify the default behavior for loading materials. */
  107017. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  107018. /** Override this method to modify the default behavior for loading textures. */
  107019. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  107020. /** Override this method to modify the default behavior for loading uris. */
  107021. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  107022. // #endregion
  107023. /** Helper method called by a loader extension to load an glTF extension. */
  107024. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  107025. if (!property.extensions) {
  107026. return null;
  107027. }
  107028. var extensions = property.extensions;
  107029. var extension = extensions[this.name];
  107030. if (!extension) {
  107031. return null;
  107032. }
  107033. // Clear out the extension before executing the action to avoid recursing into the same property.
  107034. delete extensions[this.name];
  107035. try {
  107036. return actionAsync(context + "/extensions/" + this.name, extension);
  107037. }
  107038. finally {
  107039. // Restore the extension after executing the action.
  107040. extensions[this.name] = extension;
  107041. }
  107042. };
  107043. /** Helper method called by the loader to allow extensions to override loading scenes. */
  107044. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  107045. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  107046. };
  107047. /** Helper method called by the loader to allow extensions to override loading nodes. */
  107048. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  107049. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  107050. };
  107051. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  107052. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  107053. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  107054. };
  107055. /** Helper method called by the loader to allow extensions to override loading materials. */
  107056. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  107057. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  107058. };
  107059. /** Helper method called by the loader to allow extensions to override loading textures. */
  107060. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  107061. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  107062. };
  107063. /** Helper method called by the loader to allow extensions to override loading uris. */
  107064. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  107065. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  107066. };
  107067. return GLTFLoaderExtension;
  107068. }());
  107069. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  107070. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107071. })(BABYLON || (BABYLON = {}));
  107072. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107073. var BABYLON;
  107074. (function (BABYLON) {
  107075. var GLTF2;
  107076. (function (GLTF2) {
  107077. var Extensions;
  107078. (function (Extensions) {
  107079. var NAME = "MSFT_lod";
  107080. /**
  107081. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  107082. */
  107083. var MSFT_lod = /** @class */ (function (_super) {
  107084. __extends(MSFT_lod, _super);
  107085. function MSFT_lod(loader) {
  107086. var _this = _super.call(this, loader) || this;
  107087. _this.name = NAME;
  107088. /**
  107089. * Maximum number of LODs to load, starting from the lowest LOD.
  107090. */
  107091. _this.maxLODsToLoad = Number.MAX_VALUE;
  107092. /**
  107093. * Observable raised when all node LODs of one level are loaded.
  107094. * The event data is the index of the loaded LOD starting from zero.
  107095. * Dispose the loader to cancel the loading of the next level of LODs.
  107096. */
  107097. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  107098. /**
  107099. * Observable raised when all material LODs of one level are loaded.
  107100. * The event data is the index of the loaded LOD starting from zero.
  107101. * Dispose the loader to cancel the loading of the next level of LODs.
  107102. */
  107103. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  107104. _this._loadingNodeLOD = null;
  107105. _this._loadNodeSignals = {};
  107106. _this._loadNodePromises = new Array();
  107107. _this._loadingMaterialLOD = null;
  107108. _this._loadMaterialSignals = {};
  107109. _this._loadMaterialPromises = new Array();
  107110. _this._loader._onReadyObservable.addOnce(function () {
  107111. var _loop_1 = function (indexLOD) {
  107112. Promise.all(_this._loadNodePromises[indexLOD]).then(function () {
  107113. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  107114. });
  107115. };
  107116. for (var indexLOD = 0; indexLOD < _this._loadNodePromises.length; indexLOD++) {
  107117. _loop_1(indexLOD);
  107118. }
  107119. var _loop_2 = function (indexLOD) {
  107120. Promise.all(_this._loadMaterialPromises[indexLOD]).then(function () {
  107121. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  107122. });
  107123. };
  107124. for (var indexLOD = 0; indexLOD < _this._loadMaterialPromises.length; indexLOD++) {
  107125. _loop_2(indexLOD);
  107126. }
  107127. });
  107128. return _this;
  107129. }
  107130. MSFT_lod.prototype.dispose = function () {
  107131. _super.prototype.dispose.call(this);
  107132. this._loadingNodeLOD = null;
  107133. this._loadNodeSignals = {};
  107134. this._loadingMaterialLOD = null;
  107135. this._loadMaterialSignals = {};
  107136. this.onMaterialLODsLoadedObservable.clear();
  107137. this.onNodeLODsLoadedObservable.clear();
  107138. };
  107139. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  107140. var _this = this;
  107141. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  107142. var firstPromise;
  107143. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  107144. var _loop_3 = function (indexLOD) {
  107145. var nodeLOD = nodeLODs[indexLOD];
  107146. if (indexLOD !== 0) {
  107147. _this._loadingNodeLOD = nodeLOD;
  107148. if (!_this._loadNodeSignals[nodeLOD._index]) {
  107149. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  107150. }
  107151. }
  107152. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  107153. if (indexLOD !== 0) {
  107154. var previousNodeLOD = nodeLODs[indexLOD - 1];
  107155. if (previousNodeLOD._babylonMesh) {
  107156. previousNodeLOD._babylonMesh.dispose(false, true);
  107157. delete previousNodeLOD._babylonMesh;
  107158. }
  107159. }
  107160. if (indexLOD !== nodeLODs.length - 1) {
  107161. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  107162. if (_this._loadNodeSignals[nodeIndex]) {
  107163. _this._loadNodeSignals[nodeIndex].resolve();
  107164. delete _this._loadNodeSignals[nodeIndex];
  107165. }
  107166. }
  107167. });
  107168. if (indexLOD === 0) {
  107169. firstPromise = promise;
  107170. }
  107171. else {
  107172. _this._loader._completePromises.push(promise);
  107173. _this._loadingNodeLOD = null;
  107174. }
  107175. _this._loadNodePromises[indexLOD] = _this._loadNodePromises[indexLOD] || [];
  107176. _this._loadNodePromises[indexLOD].push(promise);
  107177. };
  107178. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  107179. _loop_3(indexLOD);
  107180. }
  107181. return firstPromise;
  107182. });
  107183. };
  107184. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  107185. var _this = this;
  107186. // Don't load material LODs if already loading a node LOD.
  107187. if (this._loadingNodeLOD) {
  107188. return null;
  107189. }
  107190. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  107191. var firstPromise;
  107192. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  107193. var _loop_4 = function (indexLOD) {
  107194. var materialLOD = materialLODs[indexLOD];
  107195. if (indexLOD !== 0) {
  107196. _this._loadingMaterialLOD = materialLOD;
  107197. if (!_this._loadMaterialSignals[materialLOD._index]) {
  107198. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  107199. }
  107200. }
  107201. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  107202. if (indexLOD !== 0) {
  107203. var babylonDataLOD = materialLOD._babylonData;
  107204. assign(babylonDataLOD[babylonDrawMode].material);
  107205. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  107206. if (previousBabylonDataLOD[babylonDrawMode]) {
  107207. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  107208. delete previousBabylonDataLOD[babylonDrawMode];
  107209. }
  107210. }
  107211. if (indexLOD !== materialLODs.length - 1) {
  107212. var materialIndex = materialLODs[indexLOD + 1]._index;
  107213. if (_this._loadMaterialSignals[materialIndex]) {
  107214. _this._loadMaterialSignals[materialIndex].resolve();
  107215. delete _this._loadMaterialSignals[materialIndex];
  107216. }
  107217. }
  107218. });
  107219. if (indexLOD === 0) {
  107220. firstPromise = promise;
  107221. }
  107222. else {
  107223. _this._loader._completePromises.push(promise);
  107224. _this._loadingMaterialLOD = null;
  107225. }
  107226. _this._loadMaterialPromises[indexLOD] = _this._loadMaterialPromises[indexLOD] || [];
  107227. _this._loadMaterialPromises[indexLOD].push(promise);
  107228. };
  107229. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  107230. _loop_4(indexLOD);
  107231. }
  107232. return firstPromise;
  107233. });
  107234. };
  107235. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  107236. var _this = this;
  107237. // Defer the loading of uris if loading a material or node LOD.
  107238. if (this._loadingMaterialLOD) {
  107239. var index = this._loadingMaterialLOD._index;
  107240. return this._loadMaterialSignals[index].promise.then(function () {
  107241. return _this._loader._loadUriAsync(context, uri);
  107242. });
  107243. }
  107244. else if (this._loadingNodeLOD) {
  107245. var index = this._loadingNodeLOD._index;
  107246. return this._loadNodeSignals[index].promise.then(function () {
  107247. return _this._loader._loadUriAsync(context, uri);
  107248. });
  107249. }
  107250. return null;
  107251. };
  107252. /**
  107253. * Gets an array of LOD properties from lowest to highest.
  107254. */
  107255. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  107256. if (this.maxLODsToLoad <= 0) {
  107257. throw new Error("maxLODsToLoad must be greater than zero");
  107258. }
  107259. var properties = new Array();
  107260. for (var i = ids.length - 1; i >= 0; i--) {
  107261. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  107262. if (properties.length === this.maxLODsToLoad) {
  107263. return properties;
  107264. }
  107265. }
  107266. properties.push(property);
  107267. return properties;
  107268. };
  107269. return MSFT_lod;
  107270. }(GLTF2.GLTFLoaderExtension));
  107271. Extensions.MSFT_lod = MSFT_lod;
  107272. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  107273. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107274. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107275. })(BABYLON || (BABYLON = {}));
  107276. //# sourceMappingURL=MSFT_lod.js.map
  107277. var BABYLON;
  107278. (function (BABYLON) {
  107279. var GLTF2;
  107280. (function (GLTF2) {
  107281. var Extensions;
  107282. (function (Extensions) {
  107283. var NAME = "MSFT_minecraftMesh";
  107284. /** @hidden */
  107285. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  107286. __extends(MSFT_minecraftMesh, _super);
  107287. function MSFT_minecraftMesh(loader) {
  107288. var _this = _super.call(this, loader) || this;
  107289. _this.name = NAME;
  107290. _this._onMaterialLoaded = function (material) {
  107291. if (material.needAlphaBlending()) {
  107292. material.forceDepthWrite = true;
  107293. material.separateCullingPass = true;
  107294. }
  107295. material.backFaceCulling = material.forceDepthWrite;
  107296. material.twoSidedLighting = true;
  107297. };
  107298. var meshes = loader._gltf.meshes;
  107299. if (meshes && meshes.length) {
  107300. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  107301. var mesh = meshes_1[_i];
  107302. if (mesh && mesh.extras && mesh.extras.MSFT_minecraftMesh) {
  107303. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  107304. break;
  107305. }
  107306. }
  107307. }
  107308. return _this;
  107309. }
  107310. return MSFT_minecraftMesh;
  107311. }(GLTF2.GLTFLoaderExtension));
  107312. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  107313. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  107314. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107315. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107316. })(BABYLON || (BABYLON = {}));
  107317. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  107318. var BABYLON;
  107319. (function (BABYLON) {
  107320. var GLTF2;
  107321. (function (GLTF2) {
  107322. var Extensions;
  107323. (function (Extensions) {
  107324. var NAME = "MSFT_sRGBFactors";
  107325. /** @hidden */
  107326. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  107327. __extends(MSFT_sRGBFactors, _super);
  107328. function MSFT_sRGBFactors(loader) {
  107329. var _this = _super.call(this, loader) || this;
  107330. _this.name = NAME;
  107331. _this._onMaterialLoaded = function (material) {
  107332. if (!material.albedoTexture) {
  107333. material.albedoColor.toLinearSpaceToRef(material.albedoColor);
  107334. }
  107335. if (!material.reflectivityTexture) {
  107336. material.reflectivityColor.toLinearSpaceToRef(material.reflectivityColor);
  107337. }
  107338. };
  107339. var materials = loader._gltf.materials;
  107340. if (materials && materials.length) {
  107341. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  107342. var material = materials_1[_i];
  107343. if (material && material.extras && material.extras.MSFT_sRGBFactors) {
  107344. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  107345. break;
  107346. }
  107347. }
  107348. }
  107349. return _this;
  107350. }
  107351. return MSFT_sRGBFactors;
  107352. }(GLTF2.GLTFLoaderExtension));
  107353. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  107354. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  107355. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107356. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107357. })(BABYLON || (BABYLON = {}));
  107358. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  107359. var BABYLON;
  107360. (function (BABYLON) {
  107361. var GLTF2;
  107362. (function (GLTF2) {
  107363. var Extensions;
  107364. (function (Extensions) {
  107365. var NAME = "KHR_draco_mesh_compression";
  107366. /**
  107367. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  107368. */
  107369. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  107370. __extends(KHR_draco_mesh_compression, _super);
  107371. function KHR_draco_mesh_compression(loader) {
  107372. var _this = _super.call(this, loader) || this;
  107373. _this.name = NAME;
  107374. _this._dracoCompression = null;
  107375. // Disable extension if decoder is not available.
  107376. if (!BABYLON.DracoCompression.DecoderAvailable) {
  107377. _this.enabled = false;
  107378. }
  107379. return _this;
  107380. }
  107381. KHR_draco_mesh_compression.prototype.dispose = function () {
  107382. if (this._dracoCompression) {
  107383. this._dracoCompression.dispose();
  107384. }
  107385. _super.prototype.dispose.call(this);
  107386. };
  107387. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107388. var _this = this;
  107389. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  107390. if (primitive.mode != undefined) {
  107391. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  107392. primitive.mode !== 4 /* TRIANGLES */) {
  107393. throw new Error(context + ": Unsupported mode " + primitive.mode);
  107394. }
  107395. // TODO: handle triangle strips
  107396. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  107397. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  107398. }
  107399. }
  107400. var attributes = {};
  107401. var loadAttribute = function (name, kind) {
  107402. var uniqueId = extension.attributes[name];
  107403. if (uniqueId == undefined) {
  107404. return;
  107405. }
  107406. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107407. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107408. babylonMesh._delayInfo.push(kind);
  107409. }
  107410. attributes[kind] = uniqueId;
  107411. };
  107412. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107413. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  107414. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  107415. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  107416. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  107417. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  107418. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  107419. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  107420. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  107421. if (!bufferView._dracoBabylonGeometry) {
  107422. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  107423. if (!_this._dracoCompression) {
  107424. _this._dracoCompression = new BABYLON.DracoCompression();
  107425. }
  107426. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  107427. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  107428. babylonVertexData.applyToGeometry(babylonGeometry);
  107429. return babylonGeometry;
  107430. }).catch(function (error) {
  107431. throw new Error(context + ": " + error.message);
  107432. });
  107433. });
  107434. }
  107435. return bufferView._dracoBabylonGeometry;
  107436. });
  107437. };
  107438. return KHR_draco_mesh_compression;
  107439. }(GLTF2.GLTFLoaderExtension));
  107440. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  107441. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  107442. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107443. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107444. })(BABYLON || (BABYLON = {}));
  107445. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  107446. var BABYLON;
  107447. (function (BABYLON) {
  107448. var GLTF2;
  107449. (function (GLTF2) {
  107450. var Extensions;
  107451. (function (Extensions) {
  107452. var NAME = "KHR_materials_pbrSpecularGlossiness";
  107453. /**
  107454. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  107455. */
  107456. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  107457. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  107458. function KHR_materials_pbrSpecularGlossiness() {
  107459. var _this = _super !== null && _super.apply(this, arguments) || this;
  107460. _this.name = NAME;
  107461. return _this;
  107462. }
  107463. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  107464. var _this = this;
  107465. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  107466. material._babylonData = material._babylonData || {};
  107467. var babylonData = material._babylonData[babylonDrawMode];
  107468. if (!babylonData) {
  107469. var promises = new Array();
  107470. var name_1 = material.name || "materialSG_" + material._index;
  107471. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  107472. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  107473. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  107474. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107475. babylonData = {
  107476. material: babylonMaterial,
  107477. meshes: [],
  107478. loaded: Promise.all(promises).then(function () { })
  107479. };
  107480. material._babylonData[babylonDrawMode] = babylonData;
  107481. }
  107482. babylonData.meshes.push(babylonMesh);
  107483. assign(babylonData.material);
  107484. return babylonData.loaded;
  107485. });
  107486. };
  107487. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  107488. var promises = new Array();
  107489. if (properties.diffuseFactor) {
  107490. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  107491. babylonMaterial.alpha = properties.diffuseFactor[3];
  107492. }
  107493. else {
  107494. babylonMaterial.albedoColor = BABYLON.Color3.White();
  107495. }
  107496. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  107497. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  107498. if (properties.diffuseTexture) {
  107499. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  107500. babylonMaterial.albedoTexture = texture;
  107501. }));
  107502. }
  107503. if (properties.specularGlossinessTexture) {
  107504. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  107505. babylonMaterial.reflectivityTexture = texture;
  107506. }));
  107507. babylonMaterial.reflectivityTexture.hasAlpha = true;
  107508. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  107509. }
  107510. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  107511. return Promise.all(promises).then(function () { });
  107512. };
  107513. return KHR_materials_pbrSpecularGlossiness;
  107514. }(GLTF2.GLTFLoaderExtension));
  107515. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  107516. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  107517. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107518. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107519. })(BABYLON || (BABYLON = {}));
  107520. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  107521. var BABYLON;
  107522. (function (BABYLON) {
  107523. var GLTF2;
  107524. (function (GLTF2) {
  107525. var Extensions;
  107526. (function (Extensions) {
  107527. var NAME = "KHR_materials_unlit";
  107528. /**
  107529. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  107530. */
  107531. var KHR_materials_unlit = /** @class */ (function (_super) {
  107532. __extends(KHR_materials_unlit, _super);
  107533. function KHR_materials_unlit() {
  107534. var _this = _super !== null && _super.apply(this, arguments) || this;
  107535. _this.name = NAME;
  107536. return _this;
  107537. }
  107538. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  107539. var _this = this;
  107540. return this._loadExtensionAsync(context, material, function () {
  107541. material._babylonData = material._babylonData || {};
  107542. var babylonData = material._babylonData[babylonDrawMode];
  107543. if (!babylonData) {
  107544. var name_1 = material.name || "materialUnlit_" + material._index;
  107545. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  107546. babylonMaterial.unlit = true;
  107547. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  107548. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107549. babylonData = {
  107550. material: babylonMaterial,
  107551. meshes: [],
  107552. loaded: promise
  107553. };
  107554. material._babylonData[babylonDrawMode] = babylonData;
  107555. }
  107556. babylonData.meshes.push(babylonMesh);
  107557. assign(babylonData.material);
  107558. return babylonData.loaded;
  107559. });
  107560. };
  107561. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  107562. var promises = new Array();
  107563. // Ensure metallic workflow
  107564. babylonMaterial.metallic = 1;
  107565. babylonMaterial.roughness = 1;
  107566. var properties = material.pbrMetallicRoughness;
  107567. if (properties) {
  107568. if (properties.baseColorFactor) {
  107569. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  107570. babylonMaterial.alpha = properties.baseColorFactor[3];
  107571. }
  107572. else {
  107573. babylonMaterial.albedoColor = BABYLON.Color3.White();
  107574. }
  107575. if (properties.baseColorTexture) {
  107576. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  107577. babylonMaterial.albedoTexture = texture;
  107578. }));
  107579. }
  107580. }
  107581. if (material.doubleSided) {
  107582. babylonMaterial.backFaceCulling = false;
  107583. babylonMaterial.twoSidedLighting = true;
  107584. }
  107585. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  107586. return Promise.all(promises).then(function () { });
  107587. };
  107588. return KHR_materials_unlit;
  107589. }(GLTF2.GLTFLoaderExtension));
  107590. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  107591. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  107592. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107593. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107594. })(BABYLON || (BABYLON = {}));
  107595. var BABYLON;
  107596. (function (BABYLON) {
  107597. var GLTF2;
  107598. (function (GLTF2) {
  107599. var Extensions;
  107600. (function (Extensions) {
  107601. var NAME = "KHR_lights";
  107602. var LightType;
  107603. (function (LightType) {
  107604. LightType["AMBIENT"] = "ambient";
  107605. LightType["DIRECTIONAL"] = "directional";
  107606. LightType["POINT"] = "point";
  107607. LightType["SPOT"] = "spot";
  107608. })(LightType || (LightType = {}));
  107609. /**
  107610. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  107611. */
  107612. var KHR_lights = /** @class */ (function (_super) {
  107613. __extends(KHR_lights, _super);
  107614. function KHR_lights() {
  107615. var _this = _super !== null && _super.apply(this, arguments) || this;
  107616. _this.name = NAME;
  107617. return _this;
  107618. }
  107619. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  107620. var _this = this;
  107621. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  107622. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  107623. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  107624. if (light.type !== LightType.AMBIENT) {
  107625. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  107626. }
  107627. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  107628. return promise;
  107629. });
  107630. };
  107631. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  107632. var _this = this;
  107633. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  107634. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  107635. var babylonLight;
  107636. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  107637. var name = node._babylonMesh.name;
  107638. switch (light.type) {
  107639. case LightType.AMBIENT: {
  107640. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  107641. }
  107642. case LightType.DIRECTIONAL: {
  107643. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  107644. break;
  107645. }
  107646. case LightType.POINT: {
  107647. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  107648. break;
  107649. }
  107650. case LightType.SPOT: {
  107651. var spotLight = light;
  107652. // TODO: support inner and outer cone angles
  107653. //const innerConeAngle = spotLight.innerConeAngle || 0;
  107654. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  107655. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  107656. break;
  107657. }
  107658. default: {
  107659. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  107660. }
  107661. }
  107662. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  107663. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  107664. babylonLight.parent = node._babylonMesh;
  107665. return promise;
  107666. });
  107667. };
  107668. Object.defineProperty(KHR_lights.prototype, "_lights", {
  107669. get: function () {
  107670. var extensions = this._loader._gltf.extensions;
  107671. if (!extensions || !extensions[this.name]) {
  107672. throw new Error("#/extensions: '" + this.name + "' not found");
  107673. }
  107674. var extension = extensions[this.name];
  107675. return extension.lights;
  107676. },
  107677. enumerable: true,
  107678. configurable: true
  107679. });
  107680. return KHR_lights;
  107681. }(GLTF2.GLTFLoaderExtension));
  107682. Extensions.KHR_lights = KHR_lights;
  107683. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  107684. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107685. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107686. })(BABYLON || (BABYLON = {}));
  107687. var BABYLON;
  107688. (function (BABYLON) {
  107689. var GLTF2;
  107690. (function (GLTF2) {
  107691. var Extensions;
  107692. (function (Extensions) {
  107693. var NAME = "KHR_texture_transform";
  107694. /**
  107695. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  107696. */
  107697. var KHR_texture_transform = /** @class */ (function (_super) {
  107698. __extends(KHR_texture_transform, _super);
  107699. function KHR_texture_transform() {
  107700. var _this = _super !== null && _super.apply(this, arguments) || this;
  107701. _this.name = NAME;
  107702. return _this;
  107703. }
  107704. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  107705. var _this = this;
  107706. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  107707. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  107708. if (extension.offset) {
  107709. babylonTexture.uOffset = extension.offset[0];
  107710. babylonTexture.vOffset = extension.offset[1];
  107711. }
  107712. // Always rotate around the origin.
  107713. babylonTexture.uRotationCenter = 0;
  107714. babylonTexture.vRotationCenter = 0;
  107715. if (extension.rotation) {
  107716. babylonTexture.wAng = -extension.rotation;
  107717. }
  107718. if (extension.scale) {
  107719. babylonTexture.uScale = extension.scale[0];
  107720. babylonTexture.vScale = extension.scale[1];
  107721. }
  107722. if (extension.texCoord != undefined) {
  107723. babylonTexture.coordinatesIndex = extension.texCoord;
  107724. }
  107725. assign(babylonTexture);
  107726. });
  107727. });
  107728. };
  107729. return KHR_texture_transform;
  107730. }(GLTF2.GLTFLoaderExtension));
  107731. Extensions.KHR_texture_transform = KHR_texture_transform;
  107732. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  107733. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107734. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107735. })(BABYLON || (BABYLON = {}));
  107736. return BABYLON;
  107737. });
  107738. /***/ }),
  107739. /* 24 */
  107740. /***/ (function(module, exports, __webpack_require__) {
  107741. module.exports = __webpack_require__(6);
  107742. /***/ }),
  107743. /* 25 */
  107744. /***/ (function(module, exports) {
  107745. var g;
  107746. // This works in non-strict mode
  107747. g = (function() {
  107748. return this;
  107749. })();
  107750. try {
  107751. // This works if eval is allowed (see CSP)
  107752. g = g || Function("return this")() || (1,eval)("this");
  107753. } catch(e) {
  107754. // This works if the window reference is available
  107755. if(typeof window === "object")
  107756. g = window;
  107757. }
  107758. // g can still be undefined, but nothing to do about it...
  107759. // We return undefined, instead of nothing here, so it's
  107760. // easier to handle this case. if(!global) { ...}
  107761. module.exports = g;
  107762. /***/ }),
  107763. /* 26 */
  107764. /***/ (function(module, exports) {
  107765. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  107766. module.exports = CANNON;
  107767. /***/ }),
  107768. /* 27 */
  107769. /***/ (function(module, exports) {
  107770. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  107771. module.exports = OIMO;
  107772. /***/ }),
  107773. /* 28 */
  107774. /***/ (function(module, exports) {
  107775. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  107776. module.exports = earcut;
  107777. /***/ }),
  107778. /* 29 */
  107779. /***/ (function(module, exports, __webpack_require__) {
  107780. "use strict";
  107781. Object.defineProperty(exports, "__esModule", { value: true });
  107782. var babylonjs_1 = __webpack_require__(0);
  107783. var configuration_1 = __webpack_require__(11);
  107784. var viewerModel_1 = __webpack_require__(4);
  107785. var helper_1 = __webpack_require__(2);
  107786. var viewerLabs_1 = __webpack_require__(31);
  107787. var _1 = __webpack_require__(33);
  107788. var SceneManager = /** @class */ (function () {
  107789. function SceneManager(_viewer) {
  107790. var _this = this;
  107791. this._viewer = _viewer;
  107792. this._animationBlendingEnabled = true;
  107793. this._mainColor = babylonjs_1.Color3.White();
  107794. this._reflectionColor = babylonjs_1.Color3.White();
  107795. this._white = babylonjs_1.Color3.White();
  107796. this._forceShadowUpdate = false;
  107797. this._processShadows = true;
  107798. this._groundEnabled = true;
  107799. this._groundMirrorEnabled = true;
  107800. this._defaultRenderingPipelineEnabled = false;
  107801. this._defaultRenderingPipelineShouldBuild = true;
  107802. // default from rendering pipeline
  107803. this._bloomEnabled = false;
  107804. // default from rendering pipeline
  107805. this._fxaaEnabled = false;
  107806. this._focusOnModel = function (model) {
  107807. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  107808. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  107809. var halfSizeVec = sizeVec.scale(0.5);
  107810. var center = boundingInfo.min.add(halfSizeVec);
  107811. _this.camera.setTarget(center);
  107812. _this.camera.alpha = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.alpha) || _this.camera.alpha;
  107813. _this.camera.beta = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.beta) || _this.camera.beta;
  107814. _this.camera.radius = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.radius) || _this.camera.radius;
  107815. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  107816. // casting ais safe, due to the constraints tested before
  107817. (<ShadowLight>light).setDirectionToTarget(center);
  107818. });*/
  107819. };
  107820. this._cameraBehaviorMapping = {};
  107821. this.models = [];
  107822. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  107823. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  107824. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  107825. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  107826. this.onSceneInitObservable = new babylonjs_1.Observable();
  107827. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  107828. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  107829. this._viewer.onEngineInitObservable.add(function () {
  107830. _this._handleHardwareLimitations();
  107831. });
  107832. this.labs = new viewerLabs_1.ViewerLabs(this);
  107833. this.onSceneInitObservable.add(function (scene) {
  107834. var updateShadows = function () {
  107835. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  107836. var light = _a[_i];
  107837. var generator = light.getShadowGenerator();
  107838. if (generator) {
  107839. // Processing shadows if animates
  107840. var shadowMap = generator.getShadowMap();
  107841. if (shadowMap) {
  107842. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  107843. }
  107844. }
  107845. }
  107846. };
  107847. scene.registerBeforeRender(function () {
  107848. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  107849. // make sure all models are loaded
  107850. updateShadows();
  107851. _this._forceShadowUpdate = false;
  107852. }
  107853. else if (!(_this.models.every(function (model) {
  107854. if (!model.shadowsRenderedAfterLoad) {
  107855. model.shadowsRenderedAfterLoad = true;
  107856. return false;
  107857. }
  107858. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  107859. }))) {
  107860. updateShadows();
  107861. }
  107862. });
  107863. return _this._viewer.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  107864. });
  107865. this._viewer.onModelLoadedObservable.add(function (model) {
  107866. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  107867. var light = _a[_i];
  107868. var generator = light.getShadowGenerator();
  107869. if (generator) {
  107870. // Processing shadows if animates
  107871. var shadowMap = generator.getShadowMap();
  107872. if (shadowMap) {
  107873. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  107874. }
  107875. }
  107876. }
  107877. _this._focusOnModel(model);
  107878. });
  107879. }
  107880. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  107881. get: function () {
  107882. return this._defaultRenderingPipeline;
  107883. },
  107884. enumerable: true,
  107885. configurable: true
  107886. });
  107887. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  107888. /**
  107889. * Returns a boolean representing HDR support
  107890. */
  107891. get: function () {
  107892. return this._hdrSupport;
  107893. },
  107894. enumerable: true,
  107895. configurable: true
  107896. });
  107897. Object.defineProperty(SceneManager.prototype, "mainColor", {
  107898. /**
  107899. * Return the main color defined in the configuration.
  107900. */
  107901. get: function () {
  107902. return this._mainColor;
  107903. },
  107904. enumerable: true,
  107905. configurable: true
  107906. });
  107907. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  107908. get: function () {
  107909. return this._reflectionColor;
  107910. },
  107911. enumerable: true,
  107912. configurable: true
  107913. });
  107914. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  107915. get: function () {
  107916. return this._animationBlendingEnabled;
  107917. },
  107918. set: function (value) {
  107919. this.scene.animationPropertiesOverride = this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  107920. this.scene.animationPropertiesOverride.enableBlending = value;
  107921. this._animationBlendingEnabled = value;
  107922. },
  107923. enumerable: true,
  107924. configurable: true
  107925. });
  107926. Object.defineProperty(SceneManager.prototype, "processShadows", {
  107927. /**
  107928. * The flag defining whether shadows are rendered constantly or once.
  107929. */
  107930. get: function () {
  107931. return this._processShadows;
  107932. },
  107933. /**
  107934. * Should shadows be rendered every frame, or only once and stop.
  107935. * This can be used to optimize a scene.
  107936. *
  107937. * Not that the shadows will NOT disapear but will remain in place.
  107938. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  107939. */
  107940. set: function (process) {
  107941. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  107942. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  107943. var light = _a[_i];
  107944. var generator = light.getShadowGenerator();
  107945. if (generator) {
  107946. var shadowMap = generator.getShadowMap();
  107947. if (shadowMap) {
  107948. shadowMap.refreshRate = refreshType;
  107949. }
  107950. }
  107951. }
  107952. this._processShadows = process;
  107953. },
  107954. enumerable: true,
  107955. configurable: true
  107956. });
  107957. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  107958. get: function () {
  107959. return this._groundEnabled;
  107960. },
  107961. set: function (newValue) {
  107962. if (newValue === this._groundEnabled)
  107963. return;
  107964. this._groundEnabled = newValue;
  107965. if (this.environmentHelper && this.environmentHelper.ground) {
  107966. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  107967. }
  107968. },
  107969. enumerable: true,
  107970. configurable: true
  107971. });
  107972. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  107973. /**
  107974. * gets wether the reflection is disabled.
  107975. */
  107976. get: function () {
  107977. return this._groundMirrorEnabled;
  107978. },
  107979. /**
  107980. * sets wether the reflection is disabled.
  107981. */
  107982. set: function (value) {
  107983. if (this._groundMirrorEnabled === value) {
  107984. return;
  107985. }
  107986. this._groundMirrorEnabled = value;
  107987. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  107988. if (!value) {
  107989. this.environmentHelper.groundMaterial.reflectionTexture = null;
  107990. }
  107991. else {
  107992. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  107993. }
  107994. }
  107995. },
  107996. enumerable: true,
  107997. configurable: true
  107998. });
  107999. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  108000. get: function () {
  108001. return this._defaultRenderingPipelineEnabled;
  108002. },
  108003. set: function (value) {
  108004. if (value === this._defaultRenderingPipelineEnabled) {
  108005. return;
  108006. }
  108007. this._defaultRenderingPipelineEnabled = value;
  108008. this._rebuildPostprocesses();
  108009. if (this._defaultRenderingPipeline) {
  108010. this._defaultRenderingPipelineShouldBuild = false;
  108011. this._defaultRenderingPipeline.prepare();
  108012. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  108013. }
  108014. },
  108015. enumerable: true,
  108016. configurable: true
  108017. });
  108018. /**
  108019. * Sets the engine flags to unlock all babylon features.
  108020. * Can also be configured using the scene.flags configuration object
  108021. */
  108022. SceneManager.prototype.unlockBabylonFeatures = function () {
  108023. this.scene.shadowsEnabled = true;
  108024. this.scene.particlesEnabled = true;
  108025. this.scene.postProcessesEnabled = true;
  108026. this.scene.collisionsEnabled = true;
  108027. this.scene.lightsEnabled = true;
  108028. this.scene.texturesEnabled = true;
  108029. this.scene.lensFlaresEnabled = true;
  108030. this.scene.proceduralTexturesEnabled = true;
  108031. this.scene.renderTargetsEnabled = true;
  108032. this.scene.spritesEnabled = true;
  108033. this.scene.skeletonsEnabled = true;
  108034. this.scene.audioEnabled = true;
  108035. };
  108036. /**
  108037. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  108038. */
  108039. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  108040. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  108041. // if the scen exists, dispose it.
  108042. if (this.scene) {
  108043. this.scene.dispose();
  108044. }
  108045. // create a new scene
  108046. this.scene = new babylonjs_1.Scene(this._viewer.engine);
  108047. // set a default PBR material
  108048. if (!sceneConfiguration.defaultMaterial) {
  108049. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  108050. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  108051. defaultMaterial.microSurface = 0.6;
  108052. if (this.scene.defaultMaterial) {
  108053. this.scene.defaultMaterial.dispose();
  108054. }
  108055. this.scene.defaultMaterial = defaultMaterial;
  108056. }
  108057. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  108058. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  108059. this._mainColor = babylonjs_1.Color3.White();
  108060. /*if (sceneConfiguration.glow) {
  108061. let options: Partial<IGlowLayerOptions> = {
  108062. mainTextureFixedSize: 512
  108063. };
  108064. if (typeof sceneConfiguration.glow === 'object') {
  108065. options = sceneConfiguration.glow
  108066. }
  108067. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  108068. }*/
  108069. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  108070. };
  108071. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  108072. if (clearModels === void 0) { clearModels = true; }
  108073. if (clearLights === void 0) { clearLights = false; }
  108074. if (clearModels) {
  108075. this.models.forEach(function (m) { return m.dispose(); });
  108076. this.models.length = 0;
  108077. }
  108078. if (clearLights) {
  108079. this.scene.lights.forEach(function (l) { return l.dispose(); });
  108080. }
  108081. };
  108082. /**
  108083. * This will update the scene's configuration, including camera, lights, environment.
  108084. * @param newConfiguration the delta that should be configured. This includes only the changes
  108085. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  108086. */
  108087. SceneManager.prototype.updateConfiguration = function (newConfiguration, globalConfiguration) {
  108088. var _this = this;
  108089. if (newConfiguration.lab) {
  108090. if (newConfiguration.lab.assetsRootURL) {
  108091. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  108092. }
  108093. }
  108094. // update scene configuration
  108095. if (newConfiguration.scene) {
  108096. this._configureScene(newConfiguration.scene);
  108097. }
  108098. // optimizer
  108099. if (newConfiguration.optimizer !== undefined) {
  108100. this._configureOptimizer(newConfiguration.optimizer);
  108101. }
  108102. // configure model
  108103. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  108104. this._configureModel(newConfiguration.model);
  108105. }*/
  108106. // lights
  108107. this._configureLights(newConfiguration.lights);
  108108. // environment
  108109. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  108110. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  108111. }
  108112. // camera
  108113. this._configureCamera(newConfiguration.camera);
  108114. if (newConfiguration.lab) {
  108115. if (newConfiguration.lab.environmentMap) {
  108116. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  108117. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  108118. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  108119. });
  108120. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  108121. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  108122. }
  108123. }
  108124. // rendering piplines
  108125. if (newConfiguration.lab.defaultRenderingPipelines) {
  108126. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  108127. if (typeof pipelineConfig === 'boolean') {
  108128. this.defaultRenderingPipelineEnabled = pipelineConfig;
  108129. }
  108130. else {
  108131. this.defaultRenderingPipelineEnabled = true;
  108132. }
  108133. }
  108134. if (newConfiguration.lab.environmentMainColor) {
  108135. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  108136. this.environmentHelper.setMainColor(mainColor);
  108137. }
  108138. if (newConfiguration.lab.globalLightRotation !== undefined) {
  108139. // rotate all lights that are shadow lights
  108140. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  108141. // casting and '!' are safe, due to the constraints tested before
  108142. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  108143. });
  108144. this._forceShadowUpdate = true;
  108145. }
  108146. }
  108147. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  108148. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  108149. }
  108150. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  108151. this._defaultRenderingPipelineShouldBuild = false;
  108152. this._defaultRenderingPipeline.prepare();
  108153. }
  108154. };
  108155. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  108156. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._viewer.configuration)) {
  108157. if (this._defaultRenderingPipeline) {
  108158. this._defaultRenderingPipeline.dispose();
  108159. this._defaultRenderingPipeline = null;
  108160. this.scene.autoClearDepthAndStencil = true;
  108161. this.scene.autoClear = true;
  108162. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  108163. }
  108164. return;
  108165. }
  108166. var pipelineConfig = configuration || (this._viewer.configuration.lab && this._viewer.configuration.lab.defaultRenderingPipelines);
  108167. if (pipelineConfig) {
  108168. if (!this._defaultRenderingPipeline) {
  108169. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  108170. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  108171. }
  108172. this.scene.autoClear = false;
  108173. this.scene.autoClearDepthAndStencil = false;
  108174. this._defaultRenderingPipelineShouldBuild = true;
  108175. var bloomEnabled = this._bloomEnabled;
  108176. if (typeof pipelineConfig !== 'boolean') {
  108177. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  108178. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  108179. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  108180. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  108181. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  108182. }
  108183. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  108184. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  108185. }
  108186. };
  108187. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  108188. get: function () {
  108189. return this._bloomEnabled;
  108190. },
  108191. set: function (value) {
  108192. if (this._bloomEnabled === value) {
  108193. return;
  108194. }
  108195. this._bloomEnabled = value;
  108196. this._rebuildPostprocesses();
  108197. if (this._defaultRenderingPipeline) {
  108198. this._defaultRenderingPipelineShouldBuild = false;
  108199. this._defaultRenderingPipeline.prepare();
  108200. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  108201. }
  108202. },
  108203. enumerable: true,
  108204. configurable: true
  108205. });
  108206. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  108207. get: function () {
  108208. return this._fxaaEnabled;
  108209. },
  108210. set: function (value) {
  108211. if (this._fxaaEnabled === value) {
  108212. return;
  108213. }
  108214. this._fxaaEnabled = value;
  108215. this._rebuildPostprocesses();
  108216. if (this._defaultRenderingPipeline) {
  108217. this._defaultRenderingPipelineShouldBuild = false;
  108218. this._defaultRenderingPipeline.prepare();
  108219. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  108220. }
  108221. },
  108222. enumerable: true,
  108223. configurable: true
  108224. });
  108225. /**
  108226. * internally configure the scene using the provided configuration.
  108227. * The scene will not be recreated, but just updated.
  108228. * @param sceneConfig the (new) scene configuration
  108229. */
  108230. SceneManager.prototype._configureScene = function (sceneConfig) {
  108231. // sanity check!
  108232. if (!this.scene) {
  108233. return;
  108234. }
  108235. var cc = sceneConfig.clearColor;
  108236. var oldcc = this.scene.clearColor;
  108237. if (cc) {
  108238. if (cc.r !== undefined) {
  108239. oldcc.r = cc.r;
  108240. }
  108241. if (cc.g !== undefined) {
  108242. oldcc.g = cc.g;
  108243. }
  108244. if (cc.b !== undefined) {
  108245. oldcc.b = cc.b;
  108246. }
  108247. if (cc.a !== undefined) {
  108248. oldcc.a = cc.a;
  108249. }
  108250. }
  108251. // image processing configuration - optional.
  108252. if (sceneConfig.imageProcessingConfiguration) {
  108253. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  108254. }
  108255. //animation properties override
  108256. if (sceneConfig.animationPropertiesOverride) {
  108257. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  108258. }
  108259. if (sceneConfig.environmentTexture) {
  108260. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  108261. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  108262. this.scene.environmentTexture.dispose();
  108263. }
  108264. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  108265. this.scene.environmentTexture = environmentTexture;
  108266. }
  108267. }
  108268. if (sceneConfig.debug === true) {
  108269. this.scene.debugLayer.show();
  108270. }
  108271. else if (sceneConfig.debug === false) {
  108272. if (this.scene.debugLayer.isVisible()) {
  108273. this.scene.debugLayer.hide();
  108274. }
  108275. }
  108276. if (sceneConfig.disableHdr) {
  108277. this._handleHardwareLimitations(false);
  108278. }
  108279. else {
  108280. this._handleHardwareLimitations(true);
  108281. }
  108282. if (sceneConfig.renderInBackground !== undefined) {
  108283. this._viewer.renderInBackground = !!sceneConfig.renderInBackground;
  108284. }
  108285. if (this.camera && sceneConfig.disableCameraControl) {
  108286. this.camera.detachControl(this._viewer.canvas);
  108287. }
  108288. else if (this.camera && sceneConfig.disableCameraControl === false) {
  108289. this.camera.attachControl(this._viewer.canvas);
  108290. }
  108291. // process mainColor changes:
  108292. if (sceneConfig.mainColor) {
  108293. this._mainColor = this._mainColor || babylonjs_1.Color3.White();
  108294. var mc = sceneConfig.mainColor;
  108295. if (mc.r !== undefined) {
  108296. this._mainColor.r = mc.r;
  108297. }
  108298. if (mc.g !== undefined) {
  108299. this._mainColor.g = mc.g;
  108300. }
  108301. if (mc.b !== undefined) {
  108302. this._mainColor.b = mc.b;
  108303. }
  108304. this._reflectionColor.copyFrom(this.mainColor);
  108305. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._viewer.configuration) || 0;
  108306. // reflection color
  108307. this._reflectionColor.toLinearSpaceToRef(this._reflectionColor);
  108308. this._reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this._reflectionColor);
  108309. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this._reflectionColor, environmentTint);
  108310. this._reflectionColor.copyFrom(tmpColor3);
  108311. //update the environment, if exists
  108312. if (this.environmentHelper) {
  108313. if (this.environmentHelper.groundMaterial) {
  108314. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  108315. }
  108316. if (this.environmentHelper.skyboxMaterial) {
  108317. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  108318. }
  108319. }
  108320. }
  108321. if (sceneConfig.defaultMaterial) {
  108322. var conf = sceneConfig.defaultMaterial;
  108323. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  108324. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  108325. this.scene.defaultMaterial.dispose();
  108326. if (conf.materialType === 'standard') {
  108327. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  108328. }
  108329. else {
  108330. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  108331. }
  108332. }
  108333. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  108334. }
  108335. if (sceneConfig.flags) {
  108336. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  108337. }
  108338. this.onSceneConfiguredObservable.notifyObservers({
  108339. sceneManager: this,
  108340. object: this.scene,
  108341. newConfiguration: sceneConfig
  108342. });
  108343. };
  108344. /**
  108345. * Configure the scene optimizer.
  108346. * The existing scene optimizer will be disposed and a new one will be created.
  108347. * @param optimizerConfig the (new) optimizer configuration
  108348. */
  108349. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  108350. var _this = this;
  108351. if (typeof optimizerConfig === 'boolean') {
  108352. if (this.sceneOptimizer) {
  108353. this.sceneOptimizer.stop();
  108354. this.sceneOptimizer.dispose();
  108355. delete this.sceneOptimizer;
  108356. }
  108357. if (optimizerConfig) {
  108358. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  108359. this.sceneOptimizer.start();
  108360. }
  108361. }
  108362. else {
  108363. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  108364. // check for degradation
  108365. if (optimizerConfig.degradation) {
  108366. switch (optimizerConfig.degradation) {
  108367. case "low":
  108368. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  108369. break;
  108370. case "moderate":
  108371. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  108372. break;
  108373. case "hight":
  108374. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  108375. break;
  108376. }
  108377. }
  108378. if (this.sceneOptimizer) {
  108379. this.sceneOptimizer.stop();
  108380. this.sceneOptimizer.dispose();
  108381. }
  108382. if (optimizerConfig.custom) {
  108383. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  108384. if (customOptimizer_1) {
  108385. optimizerOptions.addCustomOptimization(function () {
  108386. return customOptimizer_1(_this._viewer);
  108387. }, function () {
  108388. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  108389. });
  108390. }
  108391. }
  108392. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  108393. this.sceneOptimizer.start();
  108394. }
  108395. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  108396. sceneManager: this,
  108397. object: this.sceneOptimizer,
  108398. newConfiguration: optimizerConfig
  108399. });
  108400. };
  108401. /**
  108402. * configure all models using the configuration.
  108403. * @param modelConfiguration the configuration to use to reconfigure the models
  108404. */
  108405. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  108406. this.models.forEach(model => {
  108407. model.updateConfiguration(modelConfiguration);
  108408. });
  108409. this.onModelsConfiguredObservable.notifyObservers({
  108410. sceneManager: this,
  108411. object: this.models,
  108412. newConfiguration: modelConfiguration
  108413. });
  108414. }*/
  108415. /**
  108416. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  108417. * @param cameraConfig the new camera configuration
  108418. * @param model optionally use the model to configure the camera.
  108419. */
  108420. SceneManager.prototype._configureCamera = function (cameraConfig) {
  108421. var _this = this;
  108422. if (cameraConfig === void 0) { cameraConfig = {}; }
  108423. if (!this.scene.activeCamera) {
  108424. var attachControl = true;
  108425. if (this._viewer.configuration.scene && this._viewer.configuration.scene.disableCameraControl) {
  108426. attachControl = false;
  108427. }
  108428. this.scene.createDefaultCamera(true, true, attachControl);
  108429. this.camera = this.scene.activeCamera;
  108430. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  108431. }
  108432. if (cameraConfig.position) {
  108433. var newPosition = this.camera.position.clone();
  108434. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  108435. this.camera.setPosition(newPosition);
  108436. }
  108437. if (cameraConfig.target) {
  108438. var newTarget = this.camera.target.clone();
  108439. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  108440. this.camera.setTarget(newTarget);
  108441. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  108442. this._focusOnModel(this.models[0]);
  108443. }*/
  108444. if (cameraConfig.rotation) {
  108445. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  108446. }
  108447. if (cameraConfig.behaviors) {
  108448. for (var name_1 in cameraConfig.behaviors) {
  108449. if (cameraConfig.behaviors[name_1] !== undefined) {
  108450. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  108451. }
  108452. }
  108453. }
  108454. ;
  108455. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  108456. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  108457. });
  108458. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108459. var sceneDiagonalLenght = sceneDiagonal.length();
  108460. if (isFinite(sceneDiagonalLenght))
  108461. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  108462. else {
  108463. this.camera.upperRadiusLimit = 10;
  108464. }
  108465. // sanity check!
  108466. if (this.scene.imageProcessingConfiguration) {
  108467. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  108468. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  108469. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._viewer.configuration);
  108470. }
  108471. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  108472. this.onCameraConfiguredObservable.notifyObservers({
  108473. sceneManager: this,
  108474. object: this.camera,
  108475. newConfiguration: cameraConfig
  108476. });
  108477. };
  108478. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  108479. var _this = this;
  108480. if (!skyboxConifguration && !groundConfiguration) {
  108481. if (this.environmentHelper) {
  108482. this.environmentHelper.dispose();
  108483. delete this.environmentHelper;
  108484. }
  108485. ;
  108486. }
  108487. else {
  108488. var options = {
  108489. createGround: !!groundConfiguration && this._groundEnabled,
  108490. createSkybox: !!skyboxConifguration,
  108491. setupImageProcessing: false,
  108492. };
  108493. // will that cause problems with model ground configuration?
  108494. /*if (model) {
  108495. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  108496. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  108497. const halfSizeVec = sizeVec.scale(0.5);
  108498. const center = boundingInfo.min.add(halfSizeVec);
  108499. options.groundYBias = -center.y;
  108500. }*/
  108501. if (groundConfiguration) {
  108502. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  108503. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  108504. if (groundSize) {
  108505. options.groundSize = groundSize;
  108506. }
  108507. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  108508. if (groundConfig_1.shadowLevel !== undefined) {
  108509. options.groundShadowLevel = groundConfig_1.shadowLevel;
  108510. }
  108511. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  108512. if (groundConfig_1.texture) {
  108513. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  108514. }
  108515. if (groundConfig_1.color) {
  108516. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  108517. }
  108518. if (groundConfig_1.opacity !== undefined) {
  108519. options.groundOpacity = groundConfig_1.opacity;
  108520. }
  108521. if (groundConfig_1.mirror) {
  108522. options.enableGroundMirror = true;
  108523. // to prevent undefines
  108524. if (typeof groundConfig_1.mirror === "object") {
  108525. if (groundConfig_1.mirror.amount !== undefined)
  108526. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  108527. if (groundConfig_1.mirror.sizeRatio !== undefined)
  108528. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  108529. if (groundConfig_1.mirror.blurKernel !== undefined)
  108530. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  108531. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  108532. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  108533. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  108534. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  108535. if (this._defaultPipelineTextureType !== undefined)
  108536. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  108537. }
  108538. }
  108539. }
  108540. var postInitSkyboxMaterial = false;
  108541. if (skyboxConifguration) {
  108542. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  108543. if (conf.material && conf.material.imageProcessingConfiguration) {
  108544. options.setupImageProcessing = false; // will be configured later manually.
  108545. }
  108546. var skyboxSize = conf.scale;
  108547. if (skyboxSize) {
  108548. options.skyboxSize = skyboxSize;
  108549. }
  108550. options.sizeAuto = !options.skyboxSize;
  108551. if (conf.color) {
  108552. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  108553. }
  108554. if (conf.cubeTexture && conf.cubeTexture.url) {
  108555. if (typeof conf.cubeTexture.url === "string") {
  108556. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  108557. }
  108558. else {
  108559. // init later!
  108560. postInitSkyboxMaterial = true;
  108561. }
  108562. }
  108563. if (conf.material) {
  108564. postInitSkyboxMaterial = true;
  108565. }
  108566. }
  108567. options.setupImageProcessing = false; // TMP
  108568. if (!this.environmentHelper) {
  108569. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  108570. }
  108571. else {
  108572. // unlikely, but there might be a new scene! we need to dispose.
  108573. // get the scene used by the envHelper
  108574. var scene = this.environmentHelper.rootMesh.getScene();
  108575. // is it a different scene? Oh no!
  108576. if (scene !== this.scene) {
  108577. this.environmentHelper.dispose();
  108578. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  108579. }
  108580. else {
  108581. this.environmentHelper.updateOptions(options);
  108582. }
  108583. }
  108584. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  108585. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  108586. }
  108587. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  108588. if (this.environmentHelper.groundMaterial && groundConfig) {
  108589. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  108590. if (groundConfig.material) {
  108591. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  108592. }
  108593. if (this.environmentHelper.groundMirror) {
  108594. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  108595. // TODO user camera exposure value to set the mirror clear color
  108596. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  108597. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  108598. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  108599. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  108600. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  108601. this.environmentHelper.groundMirror.clearColor.a = 1;
  108602. if (!this.groundMirrorEnabled) {
  108603. this.environmentHelper.groundMaterial.reflectionTexture = null;
  108604. }
  108605. }
  108606. }
  108607. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  108608. if (skyboxMaterial) {
  108609. skyboxMaterial._perceptualColor = this.mainColor;
  108610. if (postInitSkyboxMaterial) {
  108611. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  108612. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  108613. }
  108614. }
  108615. }
  108616. }
  108617. this._viewer.onModelLoadedObservable.add(function (model) {
  108618. _this._updateGroundMirrorRenderList(model);
  108619. });
  108620. this.onEnvironmentConfiguredObservable.notifyObservers({
  108621. sceneManager: this,
  108622. object: this.environmentHelper,
  108623. newConfiguration: {
  108624. skybox: skyboxConifguration,
  108625. ground: groundConfiguration
  108626. }
  108627. });
  108628. };
  108629. /**
  108630. * configure the lights.
  108631. *
  108632. * @param lightsConfiguration the (new) light(s) configuration
  108633. * @param model optionally use the model to configure the camera.
  108634. */
  108635. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  108636. var _this = this;
  108637. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  108638. // sanity check!
  108639. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  108640. if (!lightKeys.length) {
  108641. if (!this.scene.lights.length)
  108642. this.scene.createDefaultLight(true);
  108643. }
  108644. else {
  108645. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  108646. // compare to the global (!) configuration object and dispose unneeded:
  108647. var lightsToConfigure_1 = Object.keys(this._viewer.configuration.lights || []);
  108648. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  108649. lightsAvailable_1.forEach(function (lName) {
  108650. if (lightsToConfigure_1.indexOf(lName) === -1) {
  108651. _this.scene.getLightByName(lName).dispose();
  108652. }
  108653. });
  108654. }
  108655. lightKeys.forEach(function (name, idx) {
  108656. var lightConfig = { type: 0 };
  108657. if (typeof lightsConfiguration[name] === 'object') {
  108658. lightConfig = lightsConfiguration[name];
  108659. }
  108660. if (typeof lightsConfiguration[name] === 'number') {
  108661. lightConfig.type = lightsConfiguration[name];
  108662. }
  108663. lightConfig.name = name;
  108664. var light;
  108665. // light is not already available
  108666. if (lightsAvailable_1.indexOf(name) === -1) {
  108667. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  108668. if (!constructor)
  108669. return;
  108670. light = constructor();
  108671. }
  108672. else {
  108673. // available? get it from the scene
  108674. light = _this.scene.getLightByName(name);
  108675. if (typeof lightsConfiguration[name] === 'boolean') {
  108676. lightConfig.type = light.getTypeID();
  108677. }
  108678. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  108679. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  108680. light.dispose();
  108681. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  108682. if (!constructor)
  108683. return;
  108684. light = constructor();
  108685. }
  108686. }
  108687. // if config set the light to false, dispose it.
  108688. if (lightsConfiguration[name] === false) {
  108689. light.dispose();
  108690. return;
  108691. }
  108692. //enabled
  108693. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  108694. light.setEnabled(enabled);
  108695. helper_1.extendClassWithConfig(light, lightConfig);
  108696. //position. Some lights don't support shadows
  108697. if (light instanceof babylonjs_1.ShadowLight) {
  108698. // set default values
  108699. light.shadowMinZ = light.shadowMinZ || 0.2;
  108700. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  108701. if (lightConfig.target) {
  108702. if (light.setDirectionToTarget) {
  108703. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  108704. light.setDirectionToTarget(target);
  108705. }
  108706. }
  108707. else if (lightConfig.direction) {
  108708. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  108709. light.direction = direction;
  108710. }
  108711. var isShadowEnabled = false;
  108712. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  108713. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  108714. isShadowEnabled = true;
  108715. }
  108716. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  108717. var spotLight = light;
  108718. if (lightConfig.spotAngle !== undefined) {
  108719. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  108720. }
  108721. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  108722. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  108723. }
  108724. isShadowEnabled = true;
  108725. }
  108726. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  108727. if (lightConfig.shadowFieldOfView) {
  108728. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  108729. }
  108730. isShadowEnabled = true;
  108731. }
  108732. var shadowGenerator_1 = light.getShadowGenerator();
  108733. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  108734. var bufferSize = lightConfig.shadowBufferSize || 256;
  108735. if (!shadowGenerator_1) {
  108736. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  108737. }
  108738. var blurKernel = _this.getBlurKernel(light, bufferSize);
  108739. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  108740. shadowGenerator_1.blurKernel = blurKernel;
  108741. //override defaults
  108742. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  108743. // add the focues meshes to the shadow list
  108744. _this._viewer.onModelLoadedObservable.add(function (model) {
  108745. _this._updateShadowRenderList(shadowGenerator_1, model);
  108746. });
  108747. //if (model) {
  108748. _this._updateShadowRenderList(shadowGenerator_1);
  108749. //}
  108750. }
  108751. else if (shadowGenerator_1) {
  108752. shadowGenerator_1.dispose();
  108753. }
  108754. }
  108755. });
  108756. // render priority
  108757. var globalLightsConfiguration_1 = this._viewer.configuration.lights || {};
  108758. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  108759. var configuration = globalLightsConfiguration_1[name];
  108760. var light = _this.scene.getLightByName(name);
  108761. // sanity check
  108762. if (!light)
  108763. return;
  108764. light.renderPriority = -idx;
  108765. });
  108766. }
  108767. this.onLightsConfiguredObservable.notifyObservers({
  108768. sceneManager: this,
  108769. object: this.scene.lights,
  108770. newConfiguration: lightsConfiguration
  108771. });
  108772. };
  108773. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  108774. var focusMeshes = model ? model.meshes : this.scene.meshes;
  108775. // add the focues meshes to the shadow list
  108776. var shadownMap = shadowGenerator.getShadowMap();
  108777. if (!shadownMap)
  108778. return;
  108779. if (resetList && shadownMap.renderList) {
  108780. shadownMap.renderList.length = 0;
  108781. }
  108782. else {
  108783. shadownMap.renderList = shadownMap.renderList || [];
  108784. }
  108785. for (var index = 0; index < focusMeshes.length; index++) {
  108786. var mesh = focusMeshes[index];
  108787. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  108788. shadownMap.renderList.push(mesh);
  108789. }
  108790. }
  108791. if (!this._shadowGroundPlane) {
  108792. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  108793. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  108794. shadowGroundPlane.useVertexColors = false;
  108795. //material isn't ever used in rendering, just used to set back face culling
  108796. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  108797. shadowGroundPlane.material.backFaceCulling = false;
  108798. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  108799. shadowGroundPlane.freezeWorldMatrix();
  108800. this._shadowGroundPlane = shadowGroundPlane;
  108801. this.scene.removeMesh(shadowGroundPlane);
  108802. }
  108803. }
  108804. else {
  108805. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  108806. this._shadowGroundPlane.dispose();
  108807. this._shadowGroundPlane = null;
  108808. }
  108809. }
  108810. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  108811. shadownMap.renderList.push(this._shadowGroundPlane);
  108812. }
  108813. };
  108814. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  108815. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  108816. var focusMeshes = model ? model.meshes : this.scene.meshes;
  108817. var renderList = this.environmentHelper.groundMirror.renderList;
  108818. if (resetList) {
  108819. renderList.length = 0;
  108820. }
  108821. for (var index = 0; index < focusMeshes.length; index++) {
  108822. var mesh = focusMeshes[index];
  108823. if (renderList.indexOf(mesh) === -1) {
  108824. renderList.push(mesh);
  108825. }
  108826. }
  108827. }
  108828. };
  108829. /**
  108830. * Gets the shadow map blur kernel according to the light configuration.
  108831. * @param light The light used to generate the shadows
  108832. * @param bufferSize The size of the shadow map
  108833. * @return the kernel blur size
  108834. */
  108835. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  108836. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  108837. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  108838. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  108839. }
  108840. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  108841. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  108842. }
  108843. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  108844. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  108845. }
  108846. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  108847. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  108848. return blurKernel;
  108849. };
  108850. /**
  108851. * Alters render settings to reduce features based on hardware feature limitations
  108852. * @param enableHDR Allows the viewer to run in HDR mode.
  108853. */
  108854. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  108855. if (enableHDR === void 0) { enableHDR = true; }
  108856. //flip rendering settings switches based on hardware support
  108857. var maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  108858. var maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  108859. //shadows are disabled if there's not enough varyings for a single shadow
  108860. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  108861. this._maxShadows = 0;
  108862. }
  108863. else {
  108864. this._maxShadows = 3;
  108865. }
  108866. //can we render to any >= 16-bit targets (required for HDR)
  108867. var caps = this._viewer.engine.getCaps();
  108868. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  108869. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  108870. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  108871. if (linearHalfFloatTargets) {
  108872. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  108873. this._shadowGeneratorBias = 0.002;
  108874. }
  108875. else if (linearFloatTargets) {
  108876. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  108877. this._shadowGeneratorBias = 0.001;
  108878. }
  108879. else {
  108880. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  108881. this._shadowGeneratorBias = 0.001;
  108882. }
  108883. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  108884. };
  108885. /**
  108886. * Dispoe the entire viewer including the scene and the engine
  108887. */
  108888. SceneManager.prototype.dispose = function () {
  108889. // this.onCameraConfiguredObservable.clear();
  108890. this.onEnvironmentConfiguredObservable.clear();
  108891. this.onLightsConfiguredObservable.clear();
  108892. this.onModelsConfiguredObservable.clear();
  108893. this.onSceneConfiguredObservable.clear();
  108894. this.onSceneInitObservable.clear();
  108895. this.onSceneOptimizerConfiguredObservable.clear();
  108896. if (this.sceneOptimizer) {
  108897. this.sceneOptimizer.stop();
  108898. this.sceneOptimizer.dispose();
  108899. }
  108900. if (this.environmentHelper) {
  108901. this.environmentHelper.dispose();
  108902. }
  108903. this.models.forEach(function (model) {
  108904. model.dispose();
  108905. });
  108906. if (this._defaultRenderingPipeline) {
  108907. this._defaultRenderingPipeline.dispose();
  108908. }
  108909. this.models.length = 0;
  108910. if (this.scene) {
  108911. this.scene.dispose();
  108912. }
  108913. };
  108914. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  108915. var behavior;
  108916. var type;
  108917. if (typeof behaviorConfig === 'object') {
  108918. type = behaviorConfig.type;
  108919. }
  108920. else if (typeof behaviorConfig === 'number') {
  108921. type = behaviorConfig;
  108922. }
  108923. else {
  108924. type = this._cameraBehaviorMapping[name];
  108925. }
  108926. if (type === undefined)
  108927. return;
  108928. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  108929. var enabled = true;
  108930. if (typeof behaviorConfig === 'boolean') {
  108931. enabled = behaviorConfig;
  108932. }
  108933. // constructing behavior
  108934. switch (type) {
  108935. case 0 /* AUTOROTATION */:
  108936. this.camera.useAutoRotationBehavior = enabled;
  108937. behavior = this.camera.autoRotationBehavior;
  108938. break;
  108939. case 1 /* BOUNCING */:
  108940. this.camera.useBouncingBehavior = enabled;
  108941. behavior = this.camera.bouncingBehavior;
  108942. break;
  108943. case 2 /* FRAMING */:
  108944. this.camera.useFramingBehavior = enabled;
  108945. behavior = this.camera.framingBehavior;
  108946. break;
  108947. default:
  108948. behavior = null;
  108949. break;
  108950. }
  108951. if (behavior) {
  108952. this._cameraBehaviorMapping[name] = type;
  108953. if (typeof behaviorConfig === "object") {
  108954. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  108955. }
  108956. }
  108957. // post attach configuration. Some functionalities require the attached camera.
  108958. switch (type) {
  108959. case 0 /* AUTOROTATION */:
  108960. break;
  108961. case 1 /* BOUNCING */:
  108962. break;
  108963. case 2 /* FRAMING */:
  108964. this._viewer.onModelLoadedObservable.add(function (model) {
  108965. if (config.zoomOnBoundingInfo) {
  108966. behavior.zoomOnMeshHierarchy(model.rootMesh);
  108967. }
  108968. });
  108969. break;
  108970. }
  108971. };
  108972. return SceneManager;
  108973. }());
  108974. exports.SceneManager = SceneManager;
  108975. /***/ }),
  108976. /* 30 */
  108977. /***/ (function(module, exports, __webpack_require__) {
  108978. "use strict";
  108979. Object.defineProperty(exports, "__esModule", { value: true });
  108980. /**
  108981. * Animation play mode enum - is the animation looping or playing once
  108982. */
  108983. var AnimationPlayMode;
  108984. (function (AnimationPlayMode) {
  108985. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  108986. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  108987. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  108988. /**
  108989. * An enum representing the current state of an animation object
  108990. */
  108991. var AnimationState;
  108992. (function (AnimationState) {
  108993. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  108994. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  108995. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  108996. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  108997. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  108998. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  108999. /**
  109000. * The different type of easing functions available
  109001. */
  109002. var EasingFunction;
  109003. (function (EasingFunction) {
  109004. EasingFunction[EasingFunction["Linear"] = 0] = "Linear";
  109005. EasingFunction[EasingFunction["CircleEase"] = 1] = "CircleEase";
  109006. EasingFunction[EasingFunction["BackEase"] = 2] = "BackEase";
  109007. EasingFunction[EasingFunction["BounceEase"] = 3] = "BounceEase";
  109008. EasingFunction[EasingFunction["CubicEase"] = 4] = "CubicEase";
  109009. EasingFunction[EasingFunction["ElasticEase"] = 5] = "ElasticEase";
  109010. EasingFunction[EasingFunction["ExponentialEase"] = 6] = "ExponentialEase";
  109011. EasingFunction[EasingFunction["PowerEase"] = 7] = "PowerEase";
  109012. EasingFunction[EasingFunction["QuadraticEase"] = 8] = "QuadraticEase";
  109013. EasingFunction[EasingFunction["QuarticEase"] = 9] = "QuarticEase";
  109014. EasingFunction[EasingFunction["QuinticEase"] = 10] = "QuinticEase";
  109015. EasingFunction[EasingFunction["SineEase"] = 11] = "SineEase";
  109016. })(EasingFunction = exports.EasingFunction || (exports.EasingFunction = {}));
  109017. /**
  109018. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  109019. * native GroupAnimation class.
  109020. */
  109021. var GroupModelAnimation = /** @class */ (function () {
  109022. /**
  109023. * Create a new GroupModelAnimation object using an AnimationGroup object
  109024. * @param _animationGroup The aniamtion group to base the class on
  109025. */
  109026. function GroupModelAnimation(_animationGroup) {
  109027. var _this = this;
  109028. this._animationGroup = _animationGroup;
  109029. this._state = 0 /* INIT */;
  109030. this._playMode = 1 /* LOOP */;
  109031. this._animationGroup.onAnimationEndObservable.add(function () {
  109032. _this.stop();
  109033. _this._state = 4 /* ENDED */;
  109034. });
  109035. }
  109036. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  109037. /**
  109038. * Get the animation's name
  109039. */
  109040. get: function () {
  109041. return this._animationGroup.name;
  109042. },
  109043. enumerable: true,
  109044. configurable: true
  109045. });
  109046. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  109047. /**
  109048. * Get the current animation's state
  109049. */
  109050. get: function () {
  109051. return this._state;
  109052. },
  109053. enumerable: true,
  109054. configurable: true
  109055. });
  109056. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  109057. /**
  109058. * Gets the speed ratio to use for all animations
  109059. */
  109060. get: function () {
  109061. return this._animationGroup.speedRatio;
  109062. },
  109063. /**
  109064. * Sets the speed ratio to use for all animations
  109065. */
  109066. set: function (value) {
  109067. this._animationGroup.speedRatio = value;
  109068. },
  109069. enumerable: true,
  109070. configurable: true
  109071. });
  109072. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  109073. /**
  109074. * Get the max numbers of frame available in the animation group
  109075. *
  109076. * In correlation to an arry, this would be ".length"
  109077. */
  109078. get: function () {
  109079. return this._animationGroup.to - this._animationGroup.from;
  109080. },
  109081. enumerable: true,
  109082. configurable: true
  109083. });
  109084. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  109085. /**
  109086. * Get the current frame playing right now.
  109087. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  109088. *
  109089. * In correlation to an array, this would be the current index
  109090. */
  109091. get: function () {
  109092. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  109093. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  109094. }
  109095. else {
  109096. return 0;
  109097. }
  109098. },
  109099. enumerable: true,
  109100. configurable: true
  109101. });
  109102. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  109103. /**
  109104. * Get the FPS value of this animation
  109105. */
  109106. get: function () {
  109107. // get the first currentFrame found
  109108. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  109109. var animatable = this._animationGroup.animatables[i];
  109110. var animations = animatable.getAnimations();
  109111. if (!animations || !animations.length) {
  109112. continue;
  109113. }
  109114. for (var idx = 0; idx < animations.length; ++idx) {
  109115. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  109116. return animations[idx].animation.framePerSecond;
  109117. }
  109118. }
  109119. }
  109120. return 0;
  109121. },
  109122. enumerable: true,
  109123. configurable: true
  109124. });
  109125. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  109126. /**
  109127. * What is the animation'S play mode (looping or played once)
  109128. */
  109129. get: function () {
  109130. return this._playMode;
  109131. },
  109132. /**
  109133. * Set the play mode.
  109134. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  109135. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  109136. */
  109137. set: function (value) {
  109138. if (value === this._playMode) {
  109139. return;
  109140. }
  109141. this._playMode = value;
  109142. if (this.state === 1 /* PLAYING */) {
  109143. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  109144. }
  109145. else {
  109146. this._animationGroup.reset();
  109147. this._state = 0 /* INIT */;
  109148. }
  109149. },
  109150. enumerable: true,
  109151. configurable: true
  109152. });
  109153. /**
  109154. * Reset the animation group
  109155. */
  109156. GroupModelAnimation.prototype.reset = function () {
  109157. this._animationGroup.reset();
  109158. };
  109159. /**
  109160. * Restart the animation group
  109161. */
  109162. GroupModelAnimation.prototype.restart = function () {
  109163. if (this.state === 2 /* PAUSED */)
  109164. this._animationGroup.restart();
  109165. else
  109166. this.start();
  109167. };
  109168. /**
  109169. *
  109170. * @param frameNumber Go to a specific frame in the animation
  109171. */
  109172. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  109173. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  109174. };
  109175. /**
  109176. * Start playing the animation.
  109177. */
  109178. GroupModelAnimation.prototype.start = function () {
  109179. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  109180. if (this._animationGroup.isStarted) {
  109181. this._state = 1 /* PLAYING */;
  109182. }
  109183. };
  109184. /**
  109185. * Pause the animation
  109186. */
  109187. GroupModelAnimation.prototype.pause = function () {
  109188. this._animationGroup.pause();
  109189. this._state = 2 /* PAUSED */;
  109190. };
  109191. /**
  109192. * Stop the animation.
  109193. * This will fail silently if the animation group is already stopped.
  109194. */
  109195. GroupModelAnimation.prototype.stop = function () {
  109196. this._animationGroup.stop();
  109197. if (!this._animationGroup.isStarted) {
  109198. this._state = 3 /* STOPPED */;
  109199. }
  109200. };
  109201. /**
  109202. * Dispose this animation object.
  109203. */
  109204. GroupModelAnimation.prototype.dispose = function () {
  109205. this._animationGroup.dispose();
  109206. };
  109207. return GroupModelAnimation;
  109208. }());
  109209. exports.GroupModelAnimation = GroupModelAnimation;
  109210. /***/ }),
  109211. /* 31 */
  109212. /***/ (function(module, exports, __webpack_require__) {
  109213. "use strict";
  109214. Object.defineProperty(exports, "__esModule", { value: true });
  109215. var environmentSerializer_1 = __webpack_require__(32);
  109216. var babylonjs_1 = __webpack_require__(0);
  109217. var texture_1 = __webpack_require__(12);
  109218. /**
  109219. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  109220. * The APIs in all labs-related classes and configuration might change.
  109221. * Once stable, lab features will be moved to the publis API and configuration object.
  109222. */
  109223. var ViewerLabs = /** @class */ (function () {
  109224. function ViewerLabs(_sceneManager) {
  109225. this._sceneManager = _sceneManager;
  109226. this.environment = {
  109227. //irradiance
  109228. irradiancePolynomialCoefficients: {
  109229. x: new babylonjs_1.Vector3(0, 0, 0),
  109230. y: new babylonjs_1.Vector3(0, 0, 0),
  109231. z: new babylonjs_1.Vector3(0, 0, 0),
  109232. xx: new babylonjs_1.Vector3(0, 0, 0),
  109233. yy: new babylonjs_1.Vector3(0, 0, 0),
  109234. zz: new babylonjs_1.Vector3(0, 0, 0),
  109235. yz: new babylonjs_1.Vector3(0, 0, 0),
  109236. zx: new babylonjs_1.Vector3(0, 0, 0),
  109237. xy: new babylonjs_1.Vector3(0, 0, 0)
  109238. },
  109239. textureIntensityScale: 1.0
  109240. };
  109241. }
  109242. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  109243. var _this = this;
  109244. //@! todo: should loadEnvironment cancel any currently loading environments?
  109245. if (data instanceof ArrayBuffer) {
  109246. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  109247. if (onSuccess)
  109248. onSuccess(this.environment);
  109249. }
  109250. else if (typeof data === 'string') {
  109251. var url = this.getAssetUrl(data);
  109252. this._sceneManager.scene._loadFile(url, function (arrayBuffer) {
  109253. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  109254. if (onSuccess)
  109255. onSuccess(_this.environment);
  109256. }, function (progressEvent) { if (onProgress)
  109257. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  109258. if (onError) {
  109259. onError(e);
  109260. }
  109261. });
  109262. }
  109263. else {
  109264. //data assumed to be PBREnvironment object
  109265. this.environment = data;
  109266. if (onSuccess)
  109267. onSuccess(data);
  109268. }
  109269. };
  109270. /**
  109271. * Applies an `EnvironmentMapConfiguration` to the scene
  109272. * @param environmentMapConfiguration Environment map configuration to apply
  109273. */
  109274. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  109275. if (!this.environment)
  109276. return;
  109277. //set orientation
  109278. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  109279. // Add env texture to the scene.
  109280. if (this.environment.specularTexture) {
  109281. // IE crashes when disposing the old texture and setting a new one
  109282. if (!this._sceneManager.scene.environmentTexture) {
  109283. this._sceneManager.scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._sceneManager.scene, this.environment.specularTexture, false, true);
  109284. }
  109285. if (this._sceneManager.scene.environmentTexture) {
  109286. this._sceneManager.scene.environmentTexture.level = this.environment.textureIntensityScale;
  109287. this._sceneManager.scene.environmentTexture.invertZ = true;
  109288. this._sceneManager.scene.environmentTexture.lodLevelInAlpha = true;
  109289. var poly = this._sceneManager.scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  109290. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  109291. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  109292. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  109293. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  109294. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  109295. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  109296. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  109297. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  109298. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  109299. this._sceneManager.scene.environmentTexture.sphericalPolynomial = poly;
  109300. //set orientation
  109301. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._sceneManager.scene.environmentTexture.getReflectionTextureMatrix());
  109302. }
  109303. }
  109304. };
  109305. /**
  109306. * Get an environment asset url by using the configuration if the path is not absolute.
  109307. * @param url Asset url
  109308. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  109309. */
  109310. ViewerLabs.prototype.getAssetUrl = function (url) {
  109311. var returnUrl = url;
  109312. if (url && url.toLowerCase().indexOf("//") === -1) {
  109313. if (!this.assetsRootURL) {
  109314. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  109315. return url;
  109316. }
  109317. returnUrl = this.assetsRootURL + returnUrl;
  109318. }
  109319. return returnUrl;
  109320. };
  109321. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  109322. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  109323. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  109324. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  109325. axis.normalize();
  109326. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  109327. babylonjs_1.Matrix.TranslationToRef(babylonjs_1.Tmp.Vector3[0].x, babylonjs_1.Tmp.Vector3[0].y, babylonjs_1.Tmp.Vector3[0].z, babylonjs_1.Tmp.Matrix[0]);
  109328. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  109329. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  109330. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  109331. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  109332. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  109333. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  109334. shadowLight.setDirectionToTarget(target);
  109335. };
  109336. return ViewerLabs;
  109337. }());
  109338. exports.ViewerLabs = ViewerLabs;
  109339. /***/ }),
  109340. /* 32 */
  109341. /***/ (function(module, exports, __webpack_require__) {
  109342. "use strict";
  109343. Object.defineProperty(exports, "__esModule", { value: true });
  109344. var babylonjs_1 = __webpack_require__(0);
  109345. var texture_1 = __webpack_require__(12);
  109346. /**
  109347. * A static class proving methods to aid parsing Spectre environment files
  109348. */
  109349. var EnvironmentDeserializer = /** @class */ (function () {
  109350. function EnvironmentDeserializer() {
  109351. }
  109352. /**
  109353. * Parses an arraybuffer into a new PBREnvironment object
  109354. * @param arrayBuffer The arraybuffer of the Spectre environment file
  109355. * @return a PBREnvironment object
  109356. */
  109357. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  109358. var environment = {
  109359. //irradiance
  109360. irradiancePolynomialCoefficients: {
  109361. x: new babylonjs_1.Vector3(0, 0, 0),
  109362. y: new babylonjs_1.Vector3(0, 0, 0),
  109363. z: new babylonjs_1.Vector3(0, 0, 0),
  109364. xx: new babylonjs_1.Vector3(0, 0, 0),
  109365. yy: new babylonjs_1.Vector3(0, 0, 0),
  109366. zz: new babylonjs_1.Vector3(0, 0, 0),
  109367. yz: new babylonjs_1.Vector3(0, 0, 0),
  109368. zx: new babylonjs_1.Vector3(0, 0, 0),
  109369. xy: new babylonjs_1.Vector3(0, 0, 0)
  109370. },
  109371. //specular
  109372. textureIntensityScale: 1.0,
  109373. };
  109374. //read .env
  109375. var littleEndian = false;
  109376. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  109377. var dataView = new DataView(arrayBuffer);
  109378. var pos = 0;
  109379. for (var i = 0; i < magicBytes.length; i++) {
  109380. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  109381. babylonjs_1.Tools.Error('Not a Spectre environment map');
  109382. }
  109383. }
  109384. var version = dataView.getUint16(pos, littleEndian);
  109385. pos += 2;
  109386. if (version !== 1) {
  109387. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  109388. }
  109389. //read json descriptor - collect characters up to null terminator
  109390. var descriptorString = '';
  109391. var charCode = 0x00;
  109392. while ((charCode = dataView.getUint8(pos++))) {
  109393. descriptorString += String.fromCharCode(charCode);
  109394. }
  109395. var descriptor = JSON.parse(descriptorString);
  109396. var payloadPos = pos;
  109397. //irradiance
  109398. switch (descriptor.irradiance.type) {
  109399. case 'irradiance_sh_coefficients_9':
  109400. //irradiance
  109401. var harmonics = descriptor.irradiance;
  109402. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  109403. //harmonics now represent radiance
  109404. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  109405. break;
  109406. default:
  109407. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  109408. }
  109409. //specular
  109410. switch (descriptor.specular.type) {
  109411. case 'cubemap_faces':
  109412. var specularDescriptor = descriptor.specular;
  109413. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  109414. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  109415. var mipmaps = specularDescriptor.mipmaps;
  109416. var imageType = specularDescriptor.imageType;
  109417. for (var l = 0; l < mipmaps.length; l++) {
  109418. var faceRanges = mipmaps[l];
  109419. specularTexture.source[l] = [];
  109420. for (var i = 0; i < 6; i++) {
  109421. var range = faceRanges[i];
  109422. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  109423. switch (imageType) {
  109424. case 'png':
  109425. //construct image element from bytes
  109426. var image = new Image();
  109427. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  109428. image.src = src;
  109429. specularTexture.source[l][i] = image;
  109430. break;
  109431. default:
  109432. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  109433. }
  109434. }
  109435. }
  109436. break;
  109437. default:
  109438. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  109439. }
  109440. return environment;
  109441. };
  109442. /**
  109443. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  109444. * L = (1/pi) * E * rho
  109445. *
  109446. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  109447. * @param harmonics Spherical harmonic coefficients (9)
  109448. */
  109449. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  109450. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  109451. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  109452. // (The pixel shader must apply albedo after texture fetches, etc).
  109453. };
  109454. /**
  109455. * Convert spherical harmonics to spherical polynomial coefficients
  109456. * @param harmonics Spherical harmonic coefficients (9)
  109457. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  109458. */
  109459. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  109460. var rPi = 1 / Math.PI;
  109461. //x
  109462. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  109463. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  109464. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  109465. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  109466. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  109467. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  109468. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  109469. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  109470. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  109471. //xx
  109472. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  109473. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  109474. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  109475. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  109476. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  109477. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  109478. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  109479. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  109480. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  109481. //yz
  109482. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  109483. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  109484. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  109485. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  109486. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  109487. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  109488. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  109489. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  109490. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  109491. };
  109492. /**
  109493. * Multiplies harmonic coefficients in place
  109494. * @param harmonics Spherical harmonic coefficients (9)
  109495. * @param scaleFactor Value to multiply by
  109496. */
  109497. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  109498. harmonics.l00[0] *= scaleFactor;
  109499. harmonics.l00[1] *= scaleFactor;
  109500. harmonics.l00[2] *= scaleFactor;
  109501. harmonics.l1_1[0] *= scaleFactor;
  109502. harmonics.l1_1[1] *= scaleFactor;
  109503. harmonics.l1_1[2] *= scaleFactor;
  109504. harmonics.l10[0] *= scaleFactor;
  109505. harmonics.l10[1] *= scaleFactor;
  109506. harmonics.l10[2] *= scaleFactor;
  109507. harmonics.l11[0] *= scaleFactor;
  109508. harmonics.l11[1] *= scaleFactor;
  109509. harmonics.l11[2] *= scaleFactor;
  109510. harmonics.l2_2[0] *= scaleFactor;
  109511. harmonics.l2_2[1] *= scaleFactor;
  109512. harmonics.l2_2[2] *= scaleFactor;
  109513. harmonics.l2_1[0] *= scaleFactor;
  109514. harmonics.l2_1[1] *= scaleFactor;
  109515. harmonics.l2_1[2] *= scaleFactor;
  109516. harmonics.l20[0] *= scaleFactor;
  109517. harmonics.l20[1] *= scaleFactor;
  109518. harmonics.l20[2] *= scaleFactor;
  109519. harmonics.l21[0] *= scaleFactor;
  109520. harmonics.l21[1] *= scaleFactor;
  109521. harmonics.l21[2] *= scaleFactor;
  109522. harmonics.l22[0] *= scaleFactor;
  109523. harmonics.l22[1] *= scaleFactor;
  109524. harmonics.l22[2] *= scaleFactor;
  109525. };
  109526. return EnvironmentDeserializer;
  109527. }());
  109528. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  109529. /***/ }),
  109530. /* 33 */
  109531. /***/ (function(module, exports, __webpack_require__) {
  109532. "use strict";
  109533. Object.defineProperty(exports, "__esModule", { value: true });
  109534. var extended_1 = __webpack_require__(34);
  109535. var cache = {};
  109536. /**
  109537. *
  109538. * @param name the name of the custom optimizer configuration
  109539. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  109540. */
  109541. function getCustomOptimizerByName(name, upgrade) {
  109542. if (!cache[name]) {
  109543. switch (name) {
  109544. case 'extended':
  109545. if (upgrade) {
  109546. return extended_1.extendedUpgrade;
  109547. }
  109548. else {
  109549. return extended_1.extendedDegrade;
  109550. }
  109551. }
  109552. }
  109553. return cache[name];
  109554. }
  109555. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  109556. /***/ }),
  109557. /* 34 */
  109558. /***/ (function(module, exports, __webpack_require__) {
  109559. "use strict";
  109560. Object.defineProperty(exports, "__esModule", { value: true });
  109561. var babylonjs_1 = __webpack_require__(0);
  109562. /**
  109563. * A custom upgrade-oriented function configuration for the scene optimizer.
  109564. *
  109565. * @param viewer the viewer to optimize
  109566. */
  109567. function extendedUpgrade(viewer) {
  109568. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  109569. // if (!this.Scene.BackgroundHelper) {
  109570. // this.Scene.EngineScene.autoClear = false;
  109571. // this.Scene.BackgroundHelper = true;
  109572. // Would require a dedicated clear color;
  109573. // return false;
  109574. // }
  109575. if (viewer.engine.getHardwareScalingLevel() > 1) {
  109576. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, 1);
  109577. viewer.engine.setHardwareScalingLevel(scaling);
  109578. return false;
  109579. }
  109580. if (!viewer.sceneManager.scene.postProcessesEnabled) {
  109581. viewer.sceneManager.scene.postProcessesEnabled = true;
  109582. return false;
  109583. }
  109584. if (!viewer.sceneManager.groundEnabled) {
  109585. viewer.sceneManager.groundEnabled = true;
  109586. return false;
  109587. }
  109588. if (defaultPipeline && !viewer.sceneManager.fxaaEnabled) {
  109589. viewer.sceneManager.fxaaEnabled = true;
  109590. return false;
  109591. }
  109592. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  109593. if (viewer.engine.getHardwareScalingLevel() > hardwareScalingLevel) {
  109594. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  109595. viewer.engine.setHardwareScalingLevel(scaling);
  109596. return false;
  109597. }
  109598. if (!viewer.sceneManager.processShadows) {
  109599. viewer.sceneManager.processShadows = true;
  109600. return false;
  109601. }
  109602. if (defaultPipeline && !viewer.sceneManager.bloomEnabled) {
  109603. viewer.sceneManager.bloomEnabled = true;
  109604. return false;
  109605. }
  109606. if (!viewer.sceneManager.groundMirrorEnabled) {
  109607. viewer.sceneManager.groundMirrorEnabled = true;
  109608. return false;
  109609. }
  109610. return true;
  109611. }
  109612. exports.extendedUpgrade = extendedUpgrade;
  109613. /**
  109614. * A custom degrade-oriented function configuration for the scene optimizer.
  109615. *
  109616. * @param viewer the viewer to optimize
  109617. */
  109618. function extendedDegrade(viewer) {
  109619. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  109620. if (viewer.sceneManager.groundMirrorEnabled) {
  109621. viewer.sceneManager.groundMirrorEnabled = false;
  109622. return false;
  109623. }
  109624. if (defaultPipeline && viewer.sceneManager.bloomEnabled) {
  109625. viewer.sceneManager.bloomEnabled = false;
  109626. return false;
  109627. }
  109628. if (viewer.sceneManager.processShadows) {
  109629. viewer.sceneManager.processShadows = false;
  109630. return false;
  109631. }
  109632. if (viewer.engine.getHardwareScalingLevel() < 1) {
  109633. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1);
  109634. viewer.engine.setHardwareScalingLevel(scaling);
  109635. return false;
  109636. }
  109637. if (defaultPipeline && viewer.sceneManager.fxaaEnabled) {
  109638. viewer.sceneManager.fxaaEnabled = false;
  109639. return false;
  109640. }
  109641. if (viewer.sceneManager.groundEnabled) {
  109642. viewer.sceneManager.groundEnabled = false;
  109643. return false;
  109644. }
  109645. if (viewer.sceneManager.scene.postProcessesEnabled) {
  109646. viewer.sceneManager.scene.postProcessesEnabled = false;
  109647. return false;
  109648. }
  109649. if (viewer.engine.getHardwareScalingLevel() < 1.25) {
  109650. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1.25);
  109651. viewer.engine.setHardwareScalingLevel(scaling);
  109652. return false;
  109653. }
  109654. // if (this.Scene.BackgroundHelper) {
  109655. // this.Scene.EngineScene.autoClear = true;
  109656. // this.Scene.BackgroundHelper = false;
  109657. // Would require a dedicated clear color;
  109658. // return false;
  109659. // }
  109660. return true;
  109661. }
  109662. exports.extendedDegrade = extendedDegrade;
  109663. /***/ }),
  109664. /* 35 */
  109665. /***/ (function(module, exports, __webpack_require__) {
  109666. "use strict";
  109667. Object.defineProperty(exports, "__esModule", { value: true });
  109668. var babylonjs_1 = __webpack_require__(0);
  109669. var helper_1 = __webpack_require__(2);
  109670. var deepmerge = __webpack_require__(1);
  109671. /**
  109672. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  109673. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  109674. */
  109675. var TemplateManager = /** @class */ (function () {
  109676. function TemplateManager(containerElement) {
  109677. this.containerElement = containerElement;
  109678. this.templates = {};
  109679. this.onTemplateInit = new babylonjs_1.Observable();
  109680. this.onTemplateLoaded = new babylonjs_1.Observable();
  109681. this.onTemplateStateChange = new babylonjs_1.Observable();
  109682. this.onAllLoaded = new babylonjs_1.Observable();
  109683. this.onEventTriggered = new babylonjs_1.Observable();
  109684. this.eventManager = new eventManager_1.EventManager(this);
  109685. }
  109686. /**
  109687. * Initialize the template(s) for the viewer. Called bay the Viewer class
  109688. * @param templates the templates to be used to initialize the main template
  109689. */
  109690. TemplateManager.prototype.initTemplate = function (templates) {
  109691. var _this = this;
  109692. var internalInit = function (dependencyMap, name, parentTemplate) {
  109693. //init template
  109694. var template = _this.templates[name];
  109695. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  109696. return internalInit(dependencyMap[childName], childName, template);
  109697. });
  109698. // register the observers
  109699. //template.onLoaded.add(() => {
  109700. var addToParent = function () {
  109701. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  109702. template.appendTo(containingElement);
  109703. _this._checkLoadedState();
  109704. };
  109705. if (parentTemplate && !parentTemplate.parent) {
  109706. parentTemplate.onAppended.add(function () {
  109707. addToParent();
  109708. });
  109709. }
  109710. else {
  109711. addToParent();
  109712. }
  109713. //});
  109714. return template;
  109715. };
  109716. //build the html tree
  109717. return this._buildHTMLTree(templates).then(function (htmlTree) {
  109718. if (_this.templates['main']) {
  109719. internalInit(htmlTree, 'main');
  109720. }
  109721. else {
  109722. _this._checkLoadedState();
  109723. }
  109724. return;
  109725. });
  109726. };
  109727. /**
  109728. *
  109729. * This function will create a simple map with child-dependencies of the template html tree.
  109730. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  109731. * It is expected that the main template will be called main!
  109732. *
  109733. * @param templates
  109734. */
  109735. TemplateManager.prototype._buildHTMLTree = function (templates) {
  109736. var _this = this;
  109737. var promises = Object.keys(templates).map(function (name) {
  109738. // if the template was overridden
  109739. if (!templates[name])
  109740. return Promise.resolve(false);
  109741. // else - we have a template, let's do our job!
  109742. var template = new Template(name, templates[name]);
  109743. template.onLoaded.add(function () {
  109744. _this.onTemplateLoaded.notifyObservers(template);
  109745. });
  109746. template.onStateChange.add(function () {
  109747. _this.onTemplateStateChange.notifyObservers(template);
  109748. });
  109749. _this.onTemplateInit.notifyObservers(template);
  109750. // make sure the global onEventTriggered is called as well
  109751. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  109752. _this.templates[name] = template;
  109753. return template.initPromise;
  109754. });
  109755. return Promise.all(promises).then(function () {
  109756. var templateStructure = {};
  109757. // now iterate through all templates and check for children:
  109758. var buildTree = function (parentObject, name) {
  109759. _this.templates[name].isInHtmlTree = true;
  109760. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  109761. childNodes.forEach(function (element) {
  109762. parentObject[element] = {};
  109763. buildTree(parentObject[element], element);
  109764. });
  109765. };
  109766. if (_this.templates['main']) {
  109767. buildTree(templateStructure, "main");
  109768. }
  109769. return templateStructure;
  109770. });
  109771. };
  109772. /**
  109773. * Get the canvas in the template tree.
  109774. * There must be one and only one canvas inthe template.
  109775. */
  109776. TemplateManager.prototype.getCanvas = function () {
  109777. return this.containerElement.querySelector('canvas');
  109778. };
  109779. /**
  109780. * Get a specific template from the template tree
  109781. * @param name the name of the template to load
  109782. */
  109783. TemplateManager.prototype.getTemplate = function (name) {
  109784. return this.templates[name];
  109785. };
  109786. TemplateManager.prototype._checkLoadedState = function () {
  109787. var _this = this;
  109788. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  109789. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  109790. });
  109791. if (done) {
  109792. this.onAllLoaded.notifyObservers(this);
  109793. }
  109794. };
  109795. /**
  109796. * Dispose the template manager
  109797. */
  109798. TemplateManager.prototype.dispose = function () {
  109799. var _this = this;
  109800. // dispose all templates
  109801. Object.keys(this.templates).forEach(function (template) {
  109802. _this.templates[template].dispose();
  109803. });
  109804. this.templates = {};
  109805. this.eventManager.dispose();
  109806. this.onTemplateInit.clear();
  109807. this.onAllLoaded.clear();
  109808. this.onEventTriggered.clear();
  109809. this.onTemplateLoaded.clear();
  109810. this.onTemplateStateChange.clear();
  109811. };
  109812. return TemplateManager;
  109813. }());
  109814. exports.TemplateManager = TemplateManager;
  109815. var Handlebars = __webpack_require__(36);
  109816. var eventManager_1 = __webpack_require__(37);
  109817. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  109818. Handlebars.registerHelper('eachInMap', function (map, block) {
  109819. var out = '';
  109820. Object.keys(map).map(function (prop) {
  109821. var data = map[prop];
  109822. if (typeof data === 'object') {
  109823. data.id = data.id || prop;
  109824. out += block.fn(data);
  109825. }
  109826. else {
  109827. out += block.fn({ id: prop, value: data });
  109828. }
  109829. });
  109830. return out;
  109831. });
  109832. Handlebars.registerHelper('add', function (a, b) {
  109833. var out = a + b;
  109834. return out;
  109835. });
  109836. Handlebars.registerHelper('eq', function (a, b) {
  109837. var out = (a == b);
  109838. return out;
  109839. });
  109840. Handlebars.registerHelper('or', function (a, b) {
  109841. var out = a || b;
  109842. return out;
  109843. });
  109844. Handlebars.registerHelper('not', function (a) {
  109845. var out = !a;
  109846. return out;
  109847. });
  109848. Handlebars.registerHelper('count', function (map) {
  109849. return map.length;
  109850. });
  109851. Handlebars.registerHelper('gt', function (a, b) {
  109852. var out = a > b;
  109853. return out;
  109854. });
  109855. /**
  109856. * This class represents a single template in the viewer's template tree.
  109857. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  109858. * A template is injected using the template manager in the correct position.
  109859. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  109860. *
  109861. * For further information please refer to the documentation page, https://doc.babylonjs.com
  109862. */
  109863. var Template = /** @class */ (function () {
  109864. function Template(name, _configuration) {
  109865. var _this = this;
  109866. this.name = name;
  109867. this._configuration = _configuration;
  109868. this.onLoaded = new babylonjs_1.Observable();
  109869. this.onAppended = new babylonjs_1.Observable();
  109870. this.onStateChange = new babylonjs_1.Observable();
  109871. this.onEventTriggered = new babylonjs_1.Observable();
  109872. this.loadRequests = [];
  109873. this.isLoaded = false;
  109874. this.isShown = false;
  109875. this.isInHtmlTree = false;
  109876. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  109877. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  109878. if (htmlTemplate) {
  109879. _this._htmlTemplate = htmlTemplate;
  109880. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && _this._configuration.params.noEscape) });
  109881. var config = _this._configuration.params || {};
  109882. _this._rawHtml = compiledTemplate(config);
  109883. try {
  109884. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  109885. }
  109886. catch (e) {
  109887. var test = document.createElement(_this.name);
  109888. test.innerHTML = _this._rawHtml;
  109889. _this._fragment = test;
  109890. }
  109891. _this.isLoaded = true;
  109892. _this.isShown = true;
  109893. _this.onLoaded.notifyObservers(_this);
  109894. }
  109895. return _this;
  109896. });
  109897. }
  109898. /**
  109899. * Some templates have parameters (like background color for example).
  109900. * The parameters are provided to Handlebars which in turn generates the template.
  109901. * This function will update the template with the new parameters
  109902. *
  109903. * Note that when updating parameters the events will be registered again (after being cleared).
  109904. *
  109905. * @param params the new template parameters
  109906. */
  109907. Template.prototype.updateParams = function (params, append) {
  109908. if (append === void 0) { append = true; }
  109909. if (append) {
  109910. this._configuration.params = deepmerge(this._configuration.params, params);
  109911. }
  109912. else {
  109913. this._configuration.params = params;
  109914. }
  109915. // update the template
  109916. if (this.isLoaded) {
  109917. // this.dispose();
  109918. }
  109919. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  109920. var config = this._configuration.params || {};
  109921. this._rawHtml = compiledTemplate(config);
  109922. try {
  109923. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  109924. }
  109925. catch (e) {
  109926. var test = document.createElement(this.name);
  109927. test.innerHTML = this._rawHtml;
  109928. this._fragment = test;
  109929. }
  109930. if (this.parent) {
  109931. this.appendTo(this.parent, true);
  109932. }
  109933. };
  109934. Object.defineProperty(Template.prototype, "configuration", {
  109935. /**
  109936. * Get the template'S configuration
  109937. */
  109938. get: function () {
  109939. return this._configuration;
  109940. },
  109941. enumerable: true,
  109942. configurable: true
  109943. });
  109944. /**
  109945. * A template can be a parent element for other templates or HTML elements.
  109946. * This function will deliver all child HTML elements of this template.
  109947. */
  109948. Template.prototype.getChildElements = function () {
  109949. var childrenArray = [];
  109950. //Edge and IE don't support frage,ent.children
  109951. var children = this._fragment && this._fragment.children;
  109952. if (!this._fragment) {
  109953. var fragment = this.parent.querySelector(this.name);
  109954. if (fragment) {
  109955. children = fragment.querySelectorAll('*');
  109956. }
  109957. }
  109958. if (!children) {
  109959. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  109960. children = this._fragment.querySelectorAll('*');
  109961. }
  109962. for (var i = 0; i < children.length; ++i) {
  109963. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  109964. }
  109965. return childrenArray;
  109966. };
  109967. /**
  109968. * Appending the template to a parent HTML element.
  109969. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  109970. * @param parent the parent to which the template is added
  109971. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  109972. */
  109973. Template.prototype.appendTo = function (parent, forceRemove) {
  109974. var _this = this;
  109975. if (this.parent) {
  109976. if (forceRemove && this._addedFragment) {
  109977. /*let fragement = this.parent.querySelector(this.name)
  109978. if (fragement)
  109979. this.parent.removeChild(fragement);*/
  109980. this.parent.innerHTML = '';
  109981. }
  109982. else {
  109983. return;
  109984. }
  109985. }
  109986. this.parent = parent;
  109987. if (this._configuration.id) {
  109988. this.parent.id = this._configuration.id;
  109989. }
  109990. if (this._fragment) {
  109991. this.parent.appendChild(this._fragment);
  109992. this._addedFragment = this._fragment;
  109993. }
  109994. else {
  109995. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  109996. }
  109997. // appended only one frame after.
  109998. setTimeout(function () {
  109999. _this._registerEvents();
  110000. _this.onAppended.notifyObservers(_this);
  110001. });
  110002. };
  110003. /**
  110004. * Show the template using the provided visibilityFunction, or natively using display: flex.
  110005. * The provided function returns a promise that should be fullfilled when the element is shown.
  110006. * Since it is a promise async operations are more than possible.
  110007. * See the default viewer for an opacity example.
  110008. * @param visibilityFunction The function to execute to show the template.
  110009. */
  110010. Template.prototype.show = function (visibilityFunction) {
  110011. var _this = this;
  110012. if (this._isHiding)
  110013. return Promise.resolve(this);
  110014. return Promise.resolve().then(function () {
  110015. _this._isShowing = true;
  110016. if (visibilityFunction) {
  110017. return visibilityFunction(_this);
  110018. }
  110019. else {
  110020. // flex? box? should this be configurable easier than the visibilityFunction?
  110021. _this.parent.style.display = 'flex';
  110022. // support old browsers with no flex:
  110023. if (_this.parent.style.display !== 'flex') {
  110024. _this.parent.style.display = '';
  110025. }
  110026. return _this;
  110027. }
  110028. }).then(function () {
  110029. _this.isShown = true;
  110030. _this._isShowing = false;
  110031. _this.onStateChange.notifyObservers(_this);
  110032. return _this;
  110033. });
  110034. };
  110035. /**
  110036. * Hide the template using the provided visibilityFunction, or natively using display: none.
  110037. * The provided function returns a promise that should be fullfilled when the element is hidden.
  110038. * Since it is a promise async operations are more than possible.
  110039. * See the default viewer for an opacity example.
  110040. * @param visibilityFunction The function to execute to show the template.
  110041. */
  110042. Template.prototype.hide = function (visibilityFunction) {
  110043. var _this = this;
  110044. if (this._isShowing)
  110045. return Promise.resolve(this);
  110046. return Promise.resolve().then(function () {
  110047. _this._isHiding = true;
  110048. if (visibilityFunction) {
  110049. return visibilityFunction(_this);
  110050. }
  110051. else {
  110052. // flex? box? should this be configurable easier than the visibilityFunction?
  110053. _this.parent.style.display = 'none';
  110054. return _this;
  110055. }
  110056. }).then(function () {
  110057. _this.isShown = false;
  110058. _this._isHiding = false;
  110059. _this.onStateChange.notifyObservers(_this);
  110060. return _this;
  110061. });
  110062. };
  110063. /**
  110064. * Dispose this template
  110065. */
  110066. Template.prototype.dispose = function () {
  110067. this.onAppended.clear();
  110068. this.onEventTriggered.clear();
  110069. this.onLoaded.clear();
  110070. this.onStateChange.clear();
  110071. this.isLoaded = false;
  110072. // remove from parent
  110073. try {
  110074. this.parent.removeChild(this._fragment);
  110075. }
  110076. catch (e) {
  110077. //noop
  110078. }
  110079. this.loadRequests.forEach(function (request) {
  110080. request.abort();
  110081. });
  110082. if (this._registeredEvents) {
  110083. this._registeredEvents.forEach(function (evt) {
  110084. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  110085. });
  110086. }
  110087. delete this._fragment;
  110088. };
  110089. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  110090. var _this = this;
  110091. if (!templateConfig) {
  110092. return Promise.reject('No templateConfig provided');
  110093. }
  110094. else if (templateConfig.html !== undefined) {
  110095. return Promise.resolve(templateConfig.html);
  110096. }
  110097. else {
  110098. var location_1 = this._getTemplateLocation(templateConfig);
  110099. if (helper_1.isUrl(location_1)) {
  110100. return new Promise(function (resolve, reject) {
  110101. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  110102. resolve(data);
  110103. }, undefined, undefined, false, function (request, error) {
  110104. reject(error);
  110105. });
  110106. _this.loadRequests.push(fileRequest);
  110107. });
  110108. }
  110109. else {
  110110. location_1 = location_1.replace('#', '');
  110111. var element = document.getElementById(location_1);
  110112. if (element) {
  110113. return Promise.resolve(element.innerHTML);
  110114. }
  110115. else {
  110116. return Promise.reject('Template ID not found');
  110117. }
  110118. }
  110119. }
  110120. };
  110121. Template.prototype._registerEvents = function () {
  110122. var _this = this;
  110123. this._registeredEvents = this._registeredEvents || [];
  110124. if (this._registeredEvents.length) {
  110125. // first remove the registered events
  110126. this._registeredEvents.forEach(function (evt) {
  110127. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  110128. });
  110129. }
  110130. if (this._configuration.events) {
  110131. var _loop_1 = function (eventName) {
  110132. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  110133. var functionToFire_1 = function (selector, event) {
  110134. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  110135. };
  110136. // if boolean, set the parent as the event listener
  110137. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  110138. var selector = this_1.parent.id;
  110139. if (selector) {
  110140. selector = '#' + selector;
  110141. }
  110142. else {
  110143. selector = this_1.parent.tagName;
  110144. }
  110145. var binding = functionToFire_1.bind(this_1, selector);
  110146. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  110147. this_1._registeredEvents.push({
  110148. htmlElement: this_1.parent,
  110149. eventName: eventName,
  110150. function: binding
  110151. });
  110152. }
  110153. else if (typeof this_1._configuration.events[eventName] === 'object') {
  110154. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  110155. // strict null checl is working incorrectly, must override:
  110156. var event_1 = this_1._configuration.events[eventName] || {};
  110157. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  110158. if (selector && selector.indexOf('#') !== 0) {
  110159. selector = '#' + selector;
  110160. }
  110161. var htmlElement = _this.parent.querySelector(selector);
  110162. if (htmlElement) {
  110163. var binding = functionToFire_1.bind(_this, selector);
  110164. htmlElement.addEventListener(eventName, binding, false);
  110165. _this._registeredEvents.push({
  110166. htmlElement: htmlElement,
  110167. eventName: eventName,
  110168. function: binding
  110169. });
  110170. }
  110171. });
  110172. }
  110173. }
  110174. };
  110175. var this_1 = this;
  110176. for (var eventName in this._configuration.events) {
  110177. _loop_1(eventName);
  110178. }
  110179. }
  110180. };
  110181. Template.prototype._getTemplateLocation = function (templateConfig) {
  110182. if (!templateConfig || typeof templateConfig === 'string') {
  110183. return templateConfig;
  110184. }
  110185. else {
  110186. return templateConfig.location;
  110187. }
  110188. };
  110189. return Template;
  110190. }());
  110191. exports.Template = Template;
  110192. /***/ }),
  110193. /* 36 */
  110194. /***/ (function(module, exports, __webpack_require__) {
  110195. /**!
  110196. @license
  110197. handlebars v4.0.11
  110198. Copyright (C) 2011-2017 by Yehuda Katz
  110199. Permission is hereby granted, free of charge, to any person obtaining a copy
  110200. of this software and associated documentation files (the "Software"), to deal
  110201. in the Software without restriction, including without limitation the rights
  110202. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  110203. copies of the Software, and to permit persons to whom the Software is
  110204. furnished to do so, subject to the following conditions:
  110205. The above copyright notice and this permission notice shall be included in
  110206. all copies or substantial portions of the Software.
  110207. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  110208. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  110209. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  110210. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  110211. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  110212. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  110213. THE SOFTWARE.
  110214. */
  110215. !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],
  110216. 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){
  110217. 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"]}])});
  110218. /***/ }),
  110219. /* 37 */
  110220. /***/ (function(module, exports, __webpack_require__) {
  110221. "use strict";
  110222. Object.defineProperty(exports, "__esModule", { value: true });
  110223. /**
  110224. * The EventManager is in charge of registering user interctions with the viewer.
  110225. * It is used in the TemplateManager
  110226. */
  110227. var EventManager = /** @class */ (function () {
  110228. function EventManager(_templateManager) {
  110229. var _this = this;
  110230. this._templateManager = _templateManager;
  110231. this._callbacksContainer = {};
  110232. this._templateManager.onEventTriggered.add(function (eventData) {
  110233. _this._eventTriggered(eventData);
  110234. });
  110235. }
  110236. /**
  110237. * Register a new callback to a specific template.
  110238. * The best example for the usage can be found in the DefaultViewer
  110239. *
  110240. * @param templateName the templateName to register the event to
  110241. * @param callback The callback to be executed
  110242. * @param eventType the type of event to register
  110243. * @param selector an optional selector. if not defined the parent object in the template will be selected
  110244. */
  110245. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  110246. if (!this._callbacksContainer[templateName]) {
  110247. this._callbacksContainer[templateName] = [];
  110248. }
  110249. this._callbacksContainer[templateName].push({
  110250. eventType: eventType,
  110251. callback: callback,
  110252. selector: selector
  110253. });
  110254. };
  110255. /**
  110256. * This will remove a registered event from the defined template.
  110257. * Each one of the variables apart from the template name are optional, but one must be provided.
  110258. *
  110259. * @param templateName the templateName
  110260. * @param callback the callback to remove (optional)
  110261. * @param eventType the event type to remove (optional)
  110262. * @param selector the selector from which to remove the event (optional)
  110263. */
  110264. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  110265. var callbackDefs = this._callbacksContainer[templateName] || [];
  110266. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  110267. };
  110268. EventManager.prototype._eventTriggered = function (data) {
  110269. var templateName = data.template.name;
  110270. var eventType = data.event.type;
  110271. var selector = data.selector;
  110272. var callbackDefs = this._callbacksContainer[templateName] || [];
  110273. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  110274. callbackDef.callback(data);
  110275. });
  110276. };
  110277. /**
  110278. * Dispose the event manager
  110279. */
  110280. EventManager.prototype.dispose = function () {
  110281. this._callbacksContainer = {};
  110282. };
  110283. return EventManager;
  110284. }());
  110285. exports.EventManager = EventManager;
  110286. /***/ }),
  110287. /* 38 */
  110288. /***/ (function(module, exports, __webpack_require__) {
  110289. "use strict";
  110290. Object.defineProperty(exports, "__esModule", { value: true });
  110291. var mappers_1 = __webpack_require__(3);
  110292. var types_1 = __webpack_require__(39);
  110293. var configurationCompatibility_1 = __webpack_require__(50);
  110294. var deepmerge = __webpack_require__(1);
  110295. var babylonjs_1 = __webpack_require__(0);
  110296. /**
  110297. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  110298. * parse the object and return a conform ViewerConfiguration.
  110299. * It is a private member of the scene.
  110300. */
  110301. var ConfigurationLoader = /** @class */ (function () {
  110302. function ConfigurationLoader(_enableCache) {
  110303. if (_enableCache === void 0) { _enableCache = false; }
  110304. this._enableCache = _enableCache;
  110305. this._configurationCache = {};
  110306. this._loadRequests = [];
  110307. }
  110308. /**
  110309. * load a configuration object that is defined in the initial configuration provided.
  110310. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  110311. *
  110312. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  110313. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  110314. * @returns A promise that delivers the extended viewer configuration, when done.
  110315. */
  110316. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  110317. var _this = this;
  110318. if (initConfig === void 0) { initConfig = {}; }
  110319. var loadedConfig = deepmerge({}, initConfig);
  110320. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  110321. if (loadedConfig.configuration) {
  110322. var mapperType_1 = "json";
  110323. return Promise.resolve().then(function () {
  110324. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  110325. // a file to load
  110326. var url = '';
  110327. if (typeof loadedConfig.configuration === "string") {
  110328. url = loadedConfig.configuration;
  110329. }
  110330. // if configuration is an object
  110331. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  110332. url = loadedConfig.configuration.url;
  110333. var type = loadedConfig.configuration.mapper;
  110334. // empty string?
  110335. if (!type) {
  110336. // load mapper type from filename / url
  110337. type = loadedConfig.configuration.url.split('.').pop();
  110338. }
  110339. mapperType_1 = type || mapperType_1;
  110340. }
  110341. return _this._loadFile(url);
  110342. }
  110343. else {
  110344. if (typeof loadedConfig.configuration === "object") {
  110345. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  110346. return loadedConfig.configuration.payload || {};
  110347. }
  110348. return {};
  110349. }
  110350. }).then(function (data) {
  110351. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  110352. var parsed = deepmerge(mapper.map(data), loadedConfig);
  110353. var merged = deepmerge(extendedConfiguration, parsed);
  110354. configurationCompatibility_1.processConfigurationCompatibility(merged);
  110355. if (callback)
  110356. callback(merged);
  110357. return merged;
  110358. });
  110359. }
  110360. else {
  110361. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  110362. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  110363. if (callback)
  110364. callback(loadedConfig);
  110365. return Promise.resolve(loadedConfig);
  110366. }
  110367. };
  110368. /**
  110369. * Dispose the configuration loader. This will cancel file requests, if active.
  110370. */
  110371. ConfigurationLoader.prototype.dispose = function () {
  110372. this._loadRequests.forEach(function (request) {
  110373. request.abort();
  110374. });
  110375. this._loadRequests.length = 0;
  110376. };
  110377. ConfigurationLoader.prototype._loadFile = function (url) {
  110378. var _this = this;
  110379. var cacheReference = this._configurationCache;
  110380. if (this._enableCache && cacheReference[url]) {
  110381. return Promise.resolve(cacheReference[url]);
  110382. }
  110383. return new Promise(function (resolve, reject) {
  110384. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  110385. var idx = _this._loadRequests.indexOf(fileRequest);
  110386. if (idx !== -1)
  110387. _this._loadRequests.splice(idx, 1);
  110388. if (_this._enableCache)
  110389. cacheReference[url] = result;
  110390. resolve(result);
  110391. }, undefined, undefined, false, function (request, error) {
  110392. var idx = _this._loadRequests.indexOf(fileRequest);
  110393. if (idx !== -1)
  110394. _this._loadRequests.splice(idx, 1);
  110395. reject(error);
  110396. });
  110397. _this._loadRequests.push(fileRequest);
  110398. });
  110399. };
  110400. return ConfigurationLoader;
  110401. }());
  110402. exports.ConfigurationLoader = ConfigurationLoader;
  110403. /***/ }),
  110404. /* 39 */
  110405. /***/ (function(module, exports, __webpack_require__) {
  110406. "use strict";
  110407. Object.defineProperty(exports, "__esModule", { value: true });
  110408. var minimal_1 = __webpack_require__(40);
  110409. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  110410. var default_1 = __webpack_require__(41);
  110411. exports.defaultConfiguration = default_1.defaultConfiguration;
  110412. var extended_1 = __webpack_require__(47);
  110413. var shadowLight_1 = __webpack_require__(48);
  110414. var environmentMap_1 = __webpack_require__(49);
  110415. var deepmerge = __webpack_require__(1);
  110416. /**
  110417. * Get the configuration type you need to use as the base for your viewer.
  110418. * The types can either be a single string, or comma separated types that will extend each other. for example:
  110419. *
  110420. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  110421. *
  110422. * @param types a comma-separated string of the type(s) or configuration to load.
  110423. */
  110424. var getConfigurationType = function (types) {
  110425. var config = {};
  110426. var typesSeparated = types.split(",");
  110427. typesSeparated.forEach(function (type) {
  110428. switch (type.trim()) {
  110429. case 'environmentMap':
  110430. config = deepmerge(config, environmentMap_1.environmentMapConfiguration);
  110431. break;
  110432. case 'shadowDirectionalLight':
  110433. config = deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  110434. break;
  110435. case 'shadowSpotLight':
  110436. config = deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  110437. break;
  110438. case 'extended':
  110439. config = deepmerge(config, extended_1.extendedConfiguration);
  110440. break;
  110441. case 'minimal':
  110442. config = deepmerge(config, minimal_1.minimalConfiguration);
  110443. break;
  110444. case 'none':
  110445. break;
  110446. case 'default':
  110447. default:
  110448. config = deepmerge(config, default_1.defaultConfiguration);
  110449. break;
  110450. }
  110451. if (config.extends) {
  110452. config = deepmerge(config, getConfigurationType(config.extends));
  110453. }
  110454. });
  110455. return config;
  110456. };
  110457. exports.getConfigurationType = getConfigurationType;
  110458. /***/ }),
  110459. /* 40 */
  110460. /***/ (function(module, exports, __webpack_require__) {
  110461. "use strict";
  110462. Object.defineProperty(exports, "__esModule", { value: true });
  110463. /**
  110464. * The minimal configuration needed to make the viewer work.
  110465. * Some functionalities might not work correctly (like fill-screen)
  110466. */
  110467. exports.minimalConfiguration = {
  110468. version: "0.1",
  110469. templates: {
  110470. main: {
  110471. html: __webpack_require__(13)
  110472. },
  110473. fillContainer: {
  110474. html: __webpack_require__(14),
  110475. params: {
  110476. disable: false
  110477. }
  110478. },
  110479. loadingScreen: {
  110480. html: __webpack_require__(15),
  110481. params: {
  110482. backgroundColor: "#000000",
  110483. loadingImage: __webpack_require__(16)
  110484. }
  110485. },
  110486. viewer: {
  110487. html: __webpack_require__(17),
  110488. },
  110489. overlay: {
  110490. html: __webpack_require__(18),
  110491. params: {
  110492. closeImage: __webpack_require__(19),
  110493. closeText: 'Close'
  110494. }
  110495. },
  110496. error: {
  110497. html: __webpack_require__(20)
  110498. }
  110499. },
  110500. engine: {
  110501. antialiasing: true
  110502. }
  110503. };
  110504. /***/ }),
  110505. /* 41 */
  110506. /***/ (function(module, exports, __webpack_require__) {
  110507. "use strict";
  110508. Object.defineProperty(exports, "__esModule", { value: true });
  110509. /**
  110510. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  110511. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  110512. */
  110513. exports.defaultConfiguration = {
  110514. version: "3.2.0-alpha4",
  110515. templates: {
  110516. main: {
  110517. html: __webpack_require__(13),
  110518. params: {
  110519. babylonFont: __webpack_require__(42),
  110520. noEscape: true
  110521. }
  110522. },
  110523. fillContainer: {
  110524. html: __webpack_require__(14),
  110525. params: {
  110526. disable: false
  110527. }
  110528. },
  110529. loadingScreen: {
  110530. html: __webpack_require__(15),
  110531. params: {
  110532. backgroundColor: "#000000",
  110533. loadingImage: __webpack_require__(16)
  110534. }
  110535. },
  110536. viewer: {
  110537. html: __webpack_require__(17),
  110538. params: {
  110539. enableDragAndDrop: false
  110540. }
  110541. },
  110542. navBar: {
  110543. html: __webpack_require__(43),
  110544. params: {
  110545. speedList: {
  110546. "0.5x": "0.5",
  110547. "1.0x": "1.0",
  110548. "1.5x": "1.5",
  110549. "2.0x": "2.0",
  110550. },
  110551. logoImage: __webpack_require__(44),
  110552. logoText: 'BabylonJS',
  110553. logoLink: 'https://babylonjs.com',
  110554. hideHelp: true,
  110555. disableOnFullscreen: false,
  110556. },
  110557. events: {
  110558. pointerdown: {
  110559. 'navbar-control': true,
  110560. 'help-button': true
  110561. },
  110562. input: {
  110563. 'progress-wrapper': true
  110564. },
  110565. pointerup: {
  110566. 'progress-wrapper': true
  110567. }
  110568. }
  110569. },
  110570. overlay: {
  110571. html: __webpack_require__(18),
  110572. params: {
  110573. closeImage: __webpack_require__(19),
  110574. closeText: 'Close'
  110575. }
  110576. },
  110577. help: {
  110578. html: __webpack_require__(45)
  110579. },
  110580. share: {
  110581. html: __webpack_require__(46)
  110582. },
  110583. error: {
  110584. html: __webpack_require__(20)
  110585. }
  110586. },
  110587. camera: {
  110588. behaviors: {
  110589. autoRotate: {
  110590. type: 0
  110591. },
  110592. framing: {
  110593. type: 2,
  110594. zoomOnBoundingInfo: true,
  110595. zoomStopsAnimation: false
  110596. },
  110597. bouncing: {
  110598. type: 1
  110599. }
  110600. },
  110601. wheelPrecision: 200,
  110602. },
  110603. skybox: {},
  110604. ground: {
  110605. receiveShadows: true
  110606. },
  110607. engine: {
  110608. antialiasing: true
  110609. },
  110610. scene: {}
  110611. };
  110612. /***/ }),
  110613. /* 42 */
  110614. /***/ (function(module, exports) {
  110615. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABIgAA8AAAAAH7gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp9rlZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAABxAAAAsqyRvzljdnQgAAAEHAAAACAAAAAqCdkJr2ZwZ20AAAQ8AAAA8AAAAVn8nuaOZ2FzcAAABSwAAAAMAAAADAAIABtnbHlmAAAFOAAABlUAAAh+MHVDHWhlYWQAAAuQAAAAMgAAADb+LvI4aGhlYQAAC8QAAAAVAAAAJBABCAZobXR4AAAL3AAAACYAAAAqErQDvGxvY2EAAAwEAAAAIgAAACIJ6we4bWF4cAAADCgAAAAcAAAAIACJANFuYW1lAAAMRAAABTsAAAvzM/OUeXBvc3QAABGAAAAAEwAAACD/UQB3cHJlcAAAEZQAAACJAAAA03i98g542mNgZk9knMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vwhxgPoRkAKtjgfAUGBgAoqoGywB42hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYwURg6jhFHDaGH0MEYYM4wVxg7jhHHDeGH8MEGYMEwUJg6ThEnDZGHyMEWYMkwVpg7ThGnDdGH6MEOYMcwUZg6zhFnDbGH2MEeYM8wV5g7zhHnDfGH+sEBYMCwUFg6LhEXDYmHxsERYMiwVlg7LhGXDcmH5sEJYMawUVg6rhFXDamH1sEZYM6wV1g7rhHXDemH9sEHYMGwUNg6bhE3DZmHzsEXYMmwVtg7bhG3DdmH7sEPYMewUdg67hF3DbmH3sEfYM+wV9g77hH3DfmH/cEA4MBwUDg6HhEPDYeHwcEQ4MhwVjg7HhGPDceH4cEI4MZwUTg6nhFPDaeH0cEY4M5wVzg7nhHPDeeH8cEG4MFwULg6XhEvDZeHycEW4MlwVrg7XhGvDdeH6cEO4MdwUbg63hFvDbeH2cEe4M9wV7g73hHvDfeH+8EB4MDwUHg6PhEfDY+Hx8ER4MjwVng7PhGfDc+H58EJ4MbwUXg6vhFfDa+H18EZ4M7wV3g7vhHfDe+H98EH4MHwUPg6fhE/DZ+Hz8EX4MnwVvg7fhG/Dd+H78EP4MfwUfg6/hF/Db+H3MDj8Ef4Mf4W/wz/h3zAk/gPilQDpAAAAeNpjYGBgYmBkAAERBmYwy42BjcEISPMCRSAyhAATAwtDDpAWYxAAmsEG1KnwnO+5w/PMF0/f+33b9533u/D//2ATFZ7zPrd/ngEV5wGJ///y/5HEd4njEgvEVQX2cvoxMHD8wWIvG5jkY+AFANeUIx8AAAB42mPQYghlKGBoYFjFyMDYwOzAeIDBAYsIEAAAqhwHlXjaXY+/TsNADMZzJLSEJ0A6IZ11KkOViJ3phksk1CUlDOelgNRKpO+AlIXFA8/ibhnzYgjMEf4utr/P+ny/c6f5yXx2nKVHKilWnDfhoNQLDurtmf35IU/vNmVhTNV5VvdlwWoJomtOF/VNsGjI0PWWTG0eH7acLWKXxY7w0nDShk7qbQB2qL/HHeJVPJLFI4QS30/xfYxL+rUsVobTiyasA/des/OoAUzFYxN49BoQf8ikP3VnE+NsOWXbwE5zgkSfygL3RJqE+0uPf/Wgkv+G+23Iv6tB9U3c9Bb0h2HBgrChl2fbUAkaYPkOhPxkxgABAAIACAAK//8AD3jaVVRvbFvVFT/nvD/XThMnL8+OUyd1eH7YThPFiWw/G8jiuCn12q780QRE2EtgbC2FrpuqtdUKrLtCmzKlIFCL0LQPbEsUBBLtBzqxTpO2TOMDElCGkPZhlcY0CbQhFYEmdU3we+zc5xRB4nffuefP7/zOfedcIHgRQP+pcRI0EAAly7GyjuW8qP2j/Rq95u83Tm4uP6ffCQg2fiiumhNgAGAyilUU55ptu203tXPmBEva1Wb7KPtppAnfbCm/KOWjKFbbC+2FpuZrPmnaSnuxqQVtAiDOyJ7ChwhYjOlYroV5dNBJOFbJwiQCSekvNGklaOktXPOlpNWmJn3J8mKTVgkkyaBFK00OBwlS8D/08EZBbcE4npBysxNurAUtEcZvtsJQY00CMRcpgCMp5IyWzaThM5Dab9oP6NBm48Y1WqZl5kwSwWBF57SwZLkqF/OUmgLZBDN8lF0CCD8CXF0CBtk3z44iHyXFy1FR6uXw8azK1SbO4MyGZsCm1FuUlQFn1QGzwRXSVvwWra2wR/CXwJUR8K8EWZQEgcQsqFzIypDRTpgED6Zhl2KWcO1imhLxmL4DXa9c071ygdxMjBJuuUZZxSLk7nhchePtJHVcGhdSnzs+X8rdOndrToZrutwYHW2U07I4f6L9pMrL+SRnl0wT5QY/gfoQUq+X5o/Pfe3+vdPTu8fq9VCYG1ehCkKhrnMYA3CEbKsg3oQVgKpAwj5YgDW4CH+Gd7iCeIxcJzOJIjmQsNQmU6AZzAuTtQXiimgaqwX0LJZKjlo69ZJIKglVqfE0a2ukSsdixSvnxjHDLWbFB1iNuRpOY3EgETfHMREXqJDNBNucaqVUHEGVlx0rnpXPeeVZDJUYV268r5Sc4oD1lZ3YAusoIqDq/hxS9rlD79lfHOM5OxXIG6fywd1ePe4WhghGGwuet9AYTU3uGn36oLIHMFRw48o6WLh5oN+ZQjeVy6Vkyg7O+ldyqeyQHtGHsuuh0v4c7BTnYhkPXrBTKXvdzqVSuas2C7y78NlajvOG9nDd8uW13kHlRa+rvPbZg+99haM8+wX7u5IP3oZS8VJcFeexO+pTPU+xnX6hqCqT7YxvHy5mEz4oBjYeVXkn935z76Tar6cUVyWdD7ndIP1xh7R9nkJC/AQfbgl/D1d+ALq4WzpzZUMexrnjS1Dlnp+F3XCAu2arB9ytFrG3vr671Q225W4nvhUSjmd4TgIFVg3koUxiVnQGFLX1hdXHGo3HVhduvFXrqtaeOzFf5CF4km8lbmST23jzb63g06ZxZ/BpC/s2X8XeVvCJ+btmZ6JN+DKIevvA4XNfhjPUGMvr/AQ88FL9kcFYzWbwSQt7GbKPMxw79nv/CmXVJcCXNd8sxPPyb+jlM8hAgasWFlpci8WXlym8qBE3BRo21lBNgijn3AwrRBUrHOxLqtzkP6rVtfruGV/6d9ExOuY/o9fTw34pWFqkt3fsHR3bVxmRO0diqS7/QGaJfpugn0g6hbva7wQfSDyg9+KvgweDv3Zl3g7+hC8Fb+AteEv7ofx+hljEU/TWjuG0t29sJB/l+KUMXUzwR4P7YEK8Ii5Dkr/bLliE4/Bz+BWzj+nUS91o5Chfw6qVtWtoFJDlWUxjkn8miRiKKNdTjWEvdodmLc9LGpVLAScx54XbJIOkcQQTA/2s1liXy4cmjmUrwwz0Y0cwBas7lhpqlZurHRdkE//YwFnEK4iiZ9BNaf3BNf+/wf+6EpGZUzN0aX/5kfbF25d2n/jPye75l+8zIkbPjp4z7SeCC7ob2x6LdEf6gw3/WrDBM/qRaSDNPB58pJn6+D1jBvUMxvYs3b5tIFr70cy2SF/0jud/MPXAFOlkZWP10/XZx2e//sye7iTeveepxvQPp0WXLjTOWnmkoot/XcKjlzRDI5PordKhkmZqD7972L9Ye8JM6b3Fh84H1/9oi+++fuh9/MP7VqbPP3yVTvUNPV/8Tmm4mNIK354iUzsTfHymcM+o/0982ogaE/MT4si7R1nC0Uj23tz+Z/GNxnKj+v2qYPA3H9733DdewOoL3pFKNHY5OHy5+SqernyvQqap/fj66a7ByMS3JnqHEz8LNnHZO1juu8kiYoaVRyvdyW1I2Oc2XEQkouCXse09rLntSPX0ZAv+D0t//44AAAB42mNgZGBgYDpluyBuyf14fpuvDNwcDCCw/+/BBhB9XVCyFkRzMIDFORmYQBQAWhsJ1AAAeNpjYGRg4GAAATjJyIAKWAECzQAgAAAAeNpj1WJYxgAETIYMYMDBwCDMwAyEDUwMTA0MDRBRIB0GAEEkA4QAAAAAABQAFAAUABQAKAA9AGQAgQCXAKwA4AFBAlgC2QM1BD8AAHjaY2BkYGAQYLjAwMUAAoxgEsROAbMYABpgAVt42p1Uz2/cRBQe106T0CQqlCJQVRhVqLTV4m3CIUorhNJWooWkSElUqeI0a8/aQ70ea2bcxeKM4MIJISRuiFMlDiAOCCTEAf4RjvwXvPc83nXabQXsyjPfvHnvez9txtjmiQMWMPoFK7i0kJ2BU4tPsOXgnMdhTx718BJbCy54fJI9H8QeL7Od4B2PV9jZ4GOPT7ErwRcerwd/Bj97vEHykAVRCH7Xwk8ILwE+HX5G+CTJvya8TPLvCK8Q/onwKjCl4R8eB+xi9IbHJ9hGtO9x2JNHPbzEXo4+9PgkuxBZj5eZib7yeIVdWVr2+BQ7Wtr0eD38fOlTjzdm8ud6uZzCOFfXCa/15BuIV88TPo1xrl4mfAbwC6vbhF/s6Z8lnjuEX+rJXyHb+4TPkU5G+HxP57Uefp30p4SvEG7jf5Pwl4hXevGv9Hyt9eRrPpdHfOvq5jbfV4nRVo8dv6lNpY1wSpcx3y0KfqCy3Fl+IK00D2Uar9+WIyOn/INKlkdNJfmeaHTteKEzlfBEV41BC47MV9/iF3HbHvADUVQ5vy3KRCcPQPqezkt+u04t+jnKleVFn2esDb+hRoVKRMG9R9DR4JRbXZtEcgx3KozkdZlKw10u+f6dI76nEllaeZ1bKbmcjGSaypQXrZSn0iZGVZge+UilE6qw8Q0xagqQ7d/a2+K71kpnD2RWF8Lck8ai9la8veO1UKnVOZSZlhiY4M6IVE6EecD1uA1mVtPM6LpCcaInlSiVtPHCgufOVdeGw+l0Gk+6+xhshq6pdGZElTfDsS6dHc7NbV1VhYIM8SLm93XNJ6LhNeTqsKoo5k7zxEjh5ICnylZQ6QEXZcoro+A2ARUJu7C8kmainAO6UUNJdHVzcAHlNx0Yo4fBk6lWRqd14gYcpwVsB2jTOVAln+YqyXuRTcGpKpOihibNo9dl0fBL6nLbv546MDwr2rbdqsy4kdYZlWBV5w7QfMZ1nSpwSYEXJyfYAqPAa6qnZaFFerx6oi0VjBmko8EVrLWrYFxTiWmiTi6L6nhF4QUqG6+ODQFCqE+uRgpijtldpplhEyZYAWjEmmCdSfYRK9nf8MzvDpmDvWQprAY+lN+EP4a/hb/D80v4a/g9e8Q422JX2SbbBrTPFEtATzMLzxhsObtJbBWtAiQKUMliuNkF/gL2A5BlLIc7SycJuwTth7CmoHkD7CBCirQkL7fYHnhFBku6aIl2GatBCyO9RwzWe8MYY4hw5zGujqnPc0g8GlYO1hiRgMdR9ClIJ8T/AGSYId7kpLso94zONWTfaSewT+CMNVWUafwfqoY1ciC9xobwn9I/Br7H7WPvZwi4IZaMeCpgaEA6JjbMdrjQu6WYK6iSoh7wmQX27T7lxKkSDew11a6tRFuxThtlmrI2oIF5SDaAc0p6FfWqIUk7YxxkBu5a28SzSH8WxF1RZzFnR3doNaI4uk4UlBFadXG1Fpa6YJ6QjGc5DP5VVys6p2CTwHlA9WrntfU7mPl5PANFszilOiWwLq7Z1GeK2glkU9PcpQtrjzYFoUugfxl2nNCRr8si9jaG/1vbOXtKTBnIDM2xo84ls1ldlEHn/cm4rvdmADNpc3Hkr3sLkL/NNQXJlDLX9FY+a/bEsamS1Bft1zarFtf0ZtVkidF23ex4ULOgN/npM9p+1UrfmTl794YoX2WcH4x3RJVuezv/Igua4O78F5z6X2t57JtMX+Vj9+A9ejXajN6P3o3ehnXnGFMJ9ndB7yHVrWyjDH4Ivg0ZdXMXNA3Ei9mIfwCJoYWxAHjaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA="
  110616. /***/ }),
  110617. /* 43 */
  110618. /***/ (function(module, exports) {
  110619. module.exports = "<style>nav-bar{position:absolute;height:48px;width:100%;bottom:10px;display:flex;justify-content:center}nav-bar .nav-container{display:flex;flex-direction:row;margin:0 10px;height:100%;width:100%;justify-content:center}nav-bar .animation-control{background-color:rgba(91,93,107,.75);display:flex;flex-direction:row;height:100%;width:100%;max-width:1280px;justify-content:center}nav-bar .flex-container{display:flex;flex-direction:row;justify-content:center;height:100%;width:100%}nav-bar button{background:0 0;border:none;color:#fff;margin:0;padding:0;height:100%;min-width:48px;cursor:pointer}nav-bar button:active,nav-bar button:focus,nav-bar button:hover{background:0 0;border:none;outline:0}nav-bar button:hover{background-color:rgba(22,24,26,.2)}nav-bar .control-text{font-family:\"Segoe UI\";font-size:12px;font-weight:400;pointer-events:none}nav-bar .icon,nav-bar img{pointer-events:none}.logo-button{display:flex;align-items:center;flex-direction:row;justify-content:center;background-color:rgba(91,93,107,.75);height:48px;min-width:48px;margin-right:4px}.logo-button img{height:20px;width:20px}.types{display:flex;flex-direction:column;width:48px}.speed .flex-container,.types .flex-container{align-items:center}.menu-options{position:absolute;bottom:48px;width:48px;background-color:rgba(22,24,26,.9)}.animation-label,.help,.logo-button,.speed,.types-icon{display:none}.types-icon:after{font-size:16px;content:\"\\F6BE\"}.up-icon:after{line-height:16px;font-size:12px;content:\"\\E70E\"}.play-icon:after{font-size:16px;content:\"\\E768\"}.pause-icon:after{font-size:16px;content:\"\\E769\"}.fullscreen-icon:after{font-size:16px;content:\"\\E740\"}.help-icon:after{font-size:16px;content:\"\\EF4E\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-circle{width:12px;height:12px;border:2px solid #fff;border-radius:50%;background-color:#5b5d6b;cursor:pointer;position:relative;bottom:10px;pointer-events:none}.default-control{display:flex;flex-direction:row;height:100%;background-color:rgba(91,93,107,.75)}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button:hover{background-color:transparent;color:#fff}.menu-options .animation-number{margin:0 18px 0 6px}.menu-options .speed-text{margin-right:18px}.menu-options{visibility:hidden}.open .menu-options{visibility:visible}.types .menu-options{width:144px}.types .menu-options button{padding:0 8px;justify-content:left}.types .menu-options button>*{display:flex;margin:8px}.types .menu-options button span.animation-number{display:none}.fullscreen{display:none}@media screen and (min-width:540px){.help,.speed,.types-icon{display:inline-block}.logo-button{display:flex}.types{width:84px}.progress-bar-container{margin:0 12px}.speed{width:64px}.speed .menu-options{width:64px}.fullscreen{display:block}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px;text-overflow:ellipsis;overflow:hidden}nav-bar button.animation-buttons{padding:0 8px;justify-content:left}.icon.up-icon{margin-left:8px}nav-bar button.animation-buttons>div{display:flex;pointer-events:none}.animation-number{display:none}.progress-bar-container{margin:0 12px}.types{width:144px}}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;outline:0;margin:0 12px;height:30px;background-color:transparent}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:#fff}.progress-wrapper::-moz-range-progress{background-color:#fff;height:2px}.progress-wrapper::-moz-range-thumb{width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1)}.progress-wrapper::-moz-range-track{background:#fff;height:2px}.progress-wrapper::-ms-track{height:2px;background:0 0;border-color:transparent;border-width:10px 0;color:transparent}.progress-wrapper::-ms-fill-lower{background:#fff;border-radius:5px}.progress-wrapper::-ms-fill-upper{background:#fff;border-radius:5px}.progress-wrapper::-ms-thumb{width:16px;height:16px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:0}span{display:inline-block}</style> {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} <style>nav-bar .nav-container{justify-content:flex-end}</style> {{else}} <style>nav-bar .nav-container{justify-content:space-between}</style> {{/if}} {{/if}} {{#if disableOnFullscreen}} <style>viewer:fullscreen nav-bar{display:none}viewer:-moz-full-screen nav-bar{display:none}viewer:-webkit-full-screen nav-bar{display:none}</style> {{/if}} <div class=nav-container id=navbar-control> {{#unless hideLogo}} <div class=logo-button title={{logoText}}> {{#if logoLink}} <a href={{logoLink}} target=_blank> <img src={{logoImage}}> </a> {{else}} <img src={{logoImage}}> {{/if}} </div> {{/unless}}{{#unless (or (not animations) hideAnimations)}} <div class=animation-control> <div class=types> <button class=\"flex-container animation-buttons\" id=types-button> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{selectedAnimationName}}</span> <span class=\"control-text animation-number\">{{selectedAnimation}}</span> {{#if (gt (count animations) 1)}} <span class=\"icon up-icon\"></span> {{/if}} </button> <div class=menu-options> {{#each animations}} {{#unless (eq ../selectedAnimation (add @index 1))}} <button class=\"flex-container animation-buttons\" id=label-option-button data-value={{this}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control id=progress-control> <button class=play-pause id=play-pause-button> {{#if paused}} <span class=\"icon play-icon\"></span> {{else}} <span class=\"icon pause-icon\"></span> {{/if}} </button> <input class=progress-wrapper id=progress-wrapper type=range min=0 max=100 step=0.01> </div> <div class=speed> <button class=flex-container id=speed-button> <span class=\"control-text speed-text\">{{selectedSpeed}}</span> <span class=\"icon up-icon\"></span> </button> <div class=menu-options> {{#eachInMap speedList}} {{#unless (eq ../selectedSpeed id)}} <button class=flex-container id=speed-option-button data-value={{value}}> <span class=\"control-text speed-text\">{{id}}</span> </button> {{/unless}} {{/eachInMap}} </div> </div> </div> {{/unless}} <div class=default-control> {{#unless hideHelp}} <button class=help id=help-button title=Help> <span class=\"icon help-icon\"></span> </button> {{/unless}} {{#unless hideFullScreen}} <button class=fullscreen id=fullscreen-button title=Fullscreen> <span class=\"icon fullscreen-icon\"></span> </button> {{/unless}} </div> </div>";
  110620. /***/ }),
  110621. /* 44 */
  110622. /***/ (function(module, exports) {
  110623. 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="
  110624. /***/ }),
  110625. /* 45 */
  110626. /***/ (function(module, exports) {
  110627. module.exports = "HELP";
  110628. /***/ }),
  110629. /* 46 */
  110630. /***/ (function(module, exports) {
  110631. module.exports = "SHARE";
  110632. /***/ }),
  110633. /* 47 */
  110634. /***/ (function(module, exports, __webpack_require__) {
  110635. "use strict";
  110636. Object.defineProperty(exports, "__esModule", { value: true });
  110637. var babylonjs_1 = __webpack_require__(0);
  110638. /**
  110639. * The viewer's "extended" configuration.
  110640. * This configuration defines specific obejcts and parameters that we think make any model look good.
  110641. */
  110642. exports.extendedConfiguration = {
  110643. version: "3.2.0",
  110644. extends: "default",
  110645. camera: {
  110646. exposure: 3.034578,
  110647. fov: 0.7853981633974483,
  110648. contrast: 1.6,
  110649. toneMappingEnabled: true,
  110650. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  110651. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  110652. behaviors: {
  110653. framing: {
  110654. type: 2,
  110655. mode: 0,
  110656. positionScale: 0.5,
  110657. defaultElevation: 0.2617993877991494,
  110658. elevationReturnWaitTime: 3000,
  110659. elevationReturnTime: 2000,
  110660. framingTime: 500,
  110661. zoomStopsAnimation: false,
  110662. radiusScale: 0.866
  110663. },
  110664. autoRotate: {
  110665. type: 0,
  110666. idleRotationWaitTime: 4000,
  110667. idleRotationSpeed: 0.17453292519943295,
  110668. idleRotationSpinupTime: 2500,
  110669. zoomStopsAnimation: false
  110670. },
  110671. bouncing: {
  110672. type: 1,
  110673. lowerRadiusTransitionRange: 0.05,
  110674. upperRadiusTransitionRange: -0.2
  110675. }
  110676. },
  110677. upperRadiusLimit: 5,
  110678. lowerRadiusLimit: 0.5,
  110679. frameOnModelLoad: true,
  110680. framingElevation: 0.2617993877991494,
  110681. framingRotation: 1.5707963267948966,
  110682. radius: 2,
  110683. alpha: 1.5708,
  110684. beta: Math.PI * 0.5 - 0.2618,
  110685. wheelPrecision: 300,
  110686. minZ: 0.1,
  110687. maxZ: 50,
  110688. fovMode: 0,
  110689. pinchPrecision: 1500,
  110690. panningSensibility: 3000
  110691. },
  110692. lights: {
  110693. light0: {
  110694. type: 0,
  110695. frustumEdgeFalloff: 0,
  110696. intensity: 7,
  110697. intensityMode: 0,
  110698. radius: 0.6,
  110699. range: 0.6,
  110700. spotAngle: 60,
  110701. diffuse: {
  110702. r: 1,
  110703. g: 1,
  110704. b: 1
  110705. },
  110706. position: {
  110707. x: -2,
  110708. y: 2.5,
  110709. z: 2
  110710. },
  110711. target: {
  110712. x: 0,
  110713. y: 0,
  110714. z: 0
  110715. },
  110716. enabled: true,
  110717. shadowEnabled: true,
  110718. shadowBufferSize: 512,
  110719. shadowMinZ: 1,
  110720. shadowMaxZ: 10,
  110721. shadowFieldOfView: 60,
  110722. shadowFrustumSize: 2,
  110723. shadowConfig: {
  110724. useBlurCloseExponentialShadowMap: true,
  110725. useKernelBlur: true,
  110726. blurScale: 1.0,
  110727. bias: 0.001,
  110728. depthScale: 50 * (10 - 1),
  110729. frustumEdgeFalloff: 0
  110730. }
  110731. },
  110732. light1: {
  110733. type: 0,
  110734. frustumEdgeFalloff: 0,
  110735. intensity: 7,
  110736. intensityMode: 0,
  110737. radius: 0.4,
  110738. range: 0.4,
  110739. spotAngle: 57,
  110740. diffuse: {
  110741. r: 1,
  110742. g: 1,
  110743. b: 1
  110744. },
  110745. position: {
  110746. x: 4,
  110747. y: 3,
  110748. z: -0.5
  110749. },
  110750. target: {
  110751. x: 0,
  110752. y: 0,
  110753. z: 0
  110754. },
  110755. enabled: true,
  110756. shadowEnabled: false,
  110757. shadowBufferSize: 512,
  110758. shadowMinZ: 0.2,
  110759. shadowMaxZ: 10,
  110760. shadowFieldOfView: 28,
  110761. shadowFrustumSize: 2
  110762. },
  110763. light2: {
  110764. type: 0,
  110765. frustumEdgeFalloff: 0,
  110766. intensity: 1,
  110767. intensityMode: 0,
  110768. radius: 0.5,
  110769. range: 0.5,
  110770. spotAngle: 42.85,
  110771. diffuse: {
  110772. r: 0.8,
  110773. g: 0.8,
  110774. b: 0.8
  110775. },
  110776. position: {
  110777. x: -1,
  110778. y: 3,
  110779. z: -3
  110780. },
  110781. target: {
  110782. x: 0,
  110783. y: 0,
  110784. z: 0
  110785. },
  110786. enabled: true,
  110787. shadowEnabled: false,
  110788. shadowBufferSize: 512,
  110789. shadowMinZ: 0.2,
  110790. shadowMaxZ: 10,
  110791. shadowFieldOfView: 45,
  110792. shadowFrustumSize: 2
  110793. }
  110794. },
  110795. ground: {
  110796. shadowLevel: 0.9,
  110797. texture: "Ground_2.0-1024.png",
  110798. material: {
  110799. primaryColorHighlightLevel: 0.035,
  110800. primaryColorShadowLevel: 0,
  110801. enableNoise: true,
  110802. useRGBColor: false,
  110803. maxSimultaneousLights: 1,
  110804. diffuseTexture: {
  110805. gammaSpace: true
  110806. }
  110807. },
  110808. opacity: 1,
  110809. mirror: false,
  110810. receiveShadows: true,
  110811. size: 5
  110812. },
  110813. skybox: {
  110814. scale: 11,
  110815. cubeTexture: {
  110816. url: "Skybox_2.0-256.dds"
  110817. },
  110818. material: {
  110819. primaryColorHighlightLevel: 0.03,
  110820. primaryColorShadowLevel: 0.03,
  110821. enableNoise: true,
  110822. useRGBColor: false,
  110823. reflectionTexture: {
  110824. gammaSpace: true
  110825. }
  110826. }
  110827. },
  110828. engine: {
  110829. renderInBackground: true
  110830. },
  110831. scene: {
  110832. flags: {
  110833. shadowsEnabled: true,
  110834. particlesEnabled: false,
  110835. collisionsEnabled: false,
  110836. lightsEnabled: true,
  110837. texturesEnabled: true,
  110838. lensFlaresEnabled: false,
  110839. proceduralTexturesEnabled: false,
  110840. renderTargetsEnabled: true,
  110841. spritesEnabled: false,
  110842. skeletonsEnabled: true,
  110843. audioEnabled: false,
  110844. },
  110845. defaultMaterial: {
  110846. materialType: 'pbr',
  110847. reflectivityColor: {
  110848. r: 0.1,
  110849. g: 0.1,
  110850. b: 0.1
  110851. },
  110852. microSurface: 0.6
  110853. },
  110854. clearColor: {
  110855. r: 0.9,
  110856. g: 0.9,
  110857. b: 0.9,
  110858. a: 1.0
  110859. },
  110860. imageProcessingConfiguration: {
  110861. vignetteCentreX: 0,
  110862. vignetteCentreY: 0,
  110863. vignetteColor: {
  110864. r: 0.086,
  110865. g: 0.184,
  110866. b: 0.259,
  110867. a: 1
  110868. },
  110869. vignetteWeight: 0.855,
  110870. vignetteStretch: 0.5,
  110871. vignetteBlendMode: 0,
  110872. vignetteCameraFov: 0.7853981633974483,
  110873. isEnabled: true,
  110874. colorCurves: {
  110875. shadowsHue: 0,
  110876. shadowsDensity: 0,
  110877. shadowsSaturation: 0,
  110878. shadowsExposure: 0,
  110879. midtonesHue: 0,
  110880. midtonesDensity: 0,
  110881. midtonesExposure: 0,
  110882. midtonesSaturation: 0,
  110883. highlightsHue: 0,
  110884. highlightsDensity: 0,
  110885. highlightsExposure: 0,
  110886. highlightsSaturation: 0
  110887. }
  110888. },
  110889. mainColor: {
  110890. r: 0.8823529411764706,
  110891. g: 0.8823529411764706,
  110892. b: 0.8823529411764706
  110893. }
  110894. },
  110895. loaderPlugins: {
  110896. extendedMaterial: true,
  110897. applyMaterialConfig: true,
  110898. msftLod: true,
  110899. telemetry: true
  110900. },
  110901. model: {
  110902. rotationOffsetAxis: {
  110903. x: 0,
  110904. y: -1,
  110905. z: 0
  110906. },
  110907. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  110908. material: {
  110909. directEnabled: true,
  110910. directIntensity: 0.884,
  110911. emissiveIntensity: 1.04,
  110912. environmentIntensity: 0.6
  110913. },
  110914. entryAnimation: {
  110915. scaling: {
  110916. x: 0,
  110917. y: 0,
  110918. z: 0
  110919. },
  110920. time: 0.5,
  110921. easingFunction: 4,
  110922. easingMode: 1
  110923. },
  110924. exitAnimation: {
  110925. scaling: {
  110926. x: 0,
  110927. y: 0,
  110928. z: 0
  110929. },
  110930. time: 0.5,
  110931. easingFunction: 4,
  110932. easingMode: 1
  110933. },
  110934. normalize: true,
  110935. castShadow: true,
  110936. receiveShadows: true
  110937. },
  110938. lab: {
  110939. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  110940. environmentMap: {
  110941. texture: "EnvMap_2.0-256.env",
  110942. rotationY: 3,
  110943. tintLevel: 0.4
  110944. },
  110945. defaultRenderingPipelines: {
  110946. bloomEnabled: true,
  110947. bloomThreshold: 1.0,
  110948. fxaaEnabled: true,
  110949. bloomWeight: 0.05
  110950. }
  110951. }
  110952. };
  110953. /***/ }),
  110954. /* 48 */
  110955. /***/ (function(module, exports, __webpack_require__) {
  110956. "use strict";
  110957. Object.defineProperty(exports, "__esModule", { value: true });
  110958. /**
  110959. * Defines a default directional shadow light for normalized objects (!)
  110960. */
  110961. exports.shadowDirectionalLightConfiguration = {
  110962. model: {
  110963. receiveShadows: true,
  110964. castShadow: true
  110965. },
  110966. ground: {
  110967. receiveShadows: true
  110968. },
  110969. lights: {
  110970. shadowDirectionalLight: {
  110971. type: 1,
  110972. shadowEnabled: true,
  110973. target: { x: 0, y: 0, z: 0.5 },
  110974. position: { x: 1.49, y: 2.39, z: -1.33 },
  110975. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  110976. intensity: 4.887,
  110977. intensityMode: 0,
  110978. shadowBufferSize: 1024,
  110979. shadowFrustumSize: 6.0,
  110980. shadowFieldOfView: 50.977,
  110981. shadowMinZ: 0.1,
  110982. shadowMaxZ: 10.0,
  110983. shadowConfig: {
  110984. blurKernel: 32,
  110985. useBlurCloseExponentialShadowMap: true
  110986. }
  110987. }
  110988. }
  110989. };
  110990. /**
  110991. * Defines a default shadow-enabled spot light for normalized objects.
  110992. */
  110993. exports.shadowSpotlLightConfiguration = {
  110994. model: {
  110995. receiveShadows: true,
  110996. castShadow: true
  110997. },
  110998. ground: {
  110999. receiveShadows: true
  111000. },
  111001. lights: {
  111002. shadowSpotLight: {
  111003. type: 2,
  111004. intensity: 2,
  111005. shadowEnabled: true,
  111006. target: { x: 0, y: 0, z: 0.5 },
  111007. position: { x: 0, y: 3.5, z: 3.7 },
  111008. angle: 1,
  111009. shadowOrthoScale: 0.5,
  111010. shadowBufferSize: 1024,
  111011. shadowMinZ: 0.1,
  111012. shadowMaxZ: 50.0,
  111013. shadowConfig: {
  111014. frustumEdgeFalloff: 0.5,
  111015. blurKernel: 32,
  111016. useBlurExponentialShadowMap: true
  111017. }
  111018. }
  111019. }
  111020. };
  111021. /***/ }),
  111022. /* 49 */
  111023. /***/ (function(module, exports, __webpack_require__) {
  111024. "use strict";
  111025. Object.defineProperty(exports, "__esModule", { value: true });
  111026. /**
  111027. * Lab-oriented default .env support
  111028. */
  111029. exports.environmentMapConfiguration = {
  111030. lab: {
  111031. assetsRootURL: '/assets/environment/',
  111032. environmentMap: {
  111033. texture: 'EnvMap_2.0-256.env',
  111034. rotationY: 0,
  111035. tintLevel: 0.4
  111036. }
  111037. }
  111038. };
  111039. /***/ }),
  111040. /* 50 */
  111041. /***/ (function(module, exports, __webpack_require__) {
  111042. "use strict";
  111043. Object.defineProperty(exports, "__esModule", { value: true });
  111044. var _1 = __webpack_require__(21);
  111045. /**
  111046. * This function will make sure the configuration file is taking deprecated fields into account
  111047. * and is setting them to the correct keys and values.
  111048. *
  111049. * @param configuration The configuration to process. Mutable!
  111050. */
  111051. function processConfigurationCompatibility(configuration) {
  111052. if (configuration.camera) {
  111053. // camera contrast -> image processing contrast
  111054. if (configuration.camera.contrast !== undefined) {
  111055. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  111056. }
  111057. // camera exposure -> image processing exposure
  111058. if (configuration.camera.exposure !== undefined) {
  111059. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  111060. }
  111061. }
  111062. if (configuration.scene) {
  111063. //glow
  111064. if (configuration.scene.glow) {
  111065. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  111066. var enabledProcessing = _1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  111067. if (enabledProcessing !== false) {
  111068. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  111069. }
  111070. }
  111071. }
  111072. }
  111073. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  111074. function setKeyInObject(object, keys, value, shouldOverwrite) {
  111075. var keySplit = keys.split(".");
  111076. if (keySplit.length === 0)
  111077. return;
  111078. var lastKey = keySplit.pop();
  111079. if (!lastKey)
  111080. return;
  111081. var curObj = object;
  111082. keySplit.forEach(function (key) {
  111083. curObj[key] = curObj[key] || {};
  111084. curObj = curObj[key];
  111085. });
  111086. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  111087. return;
  111088. curObj[lastKey] = value;
  111089. }
  111090. /***/ }),
  111091. /* 51 */
  111092. /***/ (function(module, exports, __webpack_require__) {
  111093. "use strict";
  111094. Object.defineProperty(exports, "__esModule", { value: true });
  111095. var telemetryLoaderPlugin_1 = __webpack_require__(52);
  111096. var msftLodLoaderPlugin_1 = __webpack_require__(53);
  111097. var applyMaterialConfig_1 = __webpack_require__(54);
  111098. var extendedMaterialLoaderPlugin_1 = __webpack_require__(55);
  111099. var pluginCache = {};
  111100. /**
  111101. * Get a loader plugin according to its name.
  111102. * The plugin will be cached and will be reused if called for again.
  111103. *
  111104. * @param name the name of the plugin
  111105. */
  111106. function getLoaderPluginByName(name) {
  111107. if (!pluginCache[name]) {
  111108. switch (name) {
  111109. case 'telemetry':
  111110. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  111111. break;
  111112. case 'msftLod':
  111113. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  111114. break;
  111115. case 'applyMaterialConfig':
  111116. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  111117. break;
  111118. case 'extendedMaterial':
  111119. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  111120. break;
  111121. }
  111122. }
  111123. return pluginCache[name];
  111124. }
  111125. exports.getLoaderPluginByName = getLoaderPluginByName;
  111126. /***/ }),
  111127. /* 52 */
  111128. /***/ (function(module, exports, __webpack_require__) {
  111129. "use strict";
  111130. Object.defineProperty(exports, "__esModule", { value: true });
  111131. var telemetryManager_1 = __webpack_require__(5);
  111132. var babylonjs_1 = __webpack_require__(0);
  111133. var TelemetryLoaderPlugin = /** @class */ (function () {
  111134. function TelemetryLoaderPlugin() {
  111135. }
  111136. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  111137. this._model = model;
  111138. this._loadStart = babylonjs_1.Tools.Now;
  111139. };
  111140. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  111141. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewer(), {
  111142. model: model,
  111143. loadTime: babylonjs_1.Tools.Now - this._loadStart
  111144. });
  111145. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  111146. };
  111147. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  111148. this._loadEnd = babylonjs_1.Tools.Now;
  111149. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewer(), {
  111150. model: this._model,
  111151. loadTime: this._loadEnd - this._loadStart
  111152. });
  111153. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  111154. };
  111155. TelemetryLoaderPlugin.prototype.onComplete = function () {
  111156. this._loadEnd = babylonjs_1.Tools.Now;
  111157. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewer(), {
  111158. model: this._model,
  111159. loadTime: this._loadEnd - this._loadStart
  111160. });
  111161. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  111162. };
  111163. return TelemetryLoaderPlugin;
  111164. }());
  111165. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  111166. /***/ }),
  111167. /* 53 */
  111168. /***/ (function(module, exports, __webpack_require__) {
  111169. "use strict";
  111170. Object.defineProperty(exports, "__esModule", { value: true });
  111171. /**
  111172. * A loder plugin to use MSFT_lod extension correctly (glTF)
  111173. */
  111174. var MSFTLodLoaderPlugin = /** @class */ (function () {
  111175. function MSFTLodLoaderPlugin() {
  111176. }
  111177. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  111178. this._model = model;
  111179. };
  111180. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  111181. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  111182. var MSFT_lod = extension;
  111183. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  111184. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  111185. }
  111186. };
  111187. return MSFTLodLoaderPlugin;
  111188. }());
  111189. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  111190. /***/ }),
  111191. /* 54 */
  111192. /***/ (function(module, exports, __webpack_require__) {
  111193. "use strict";
  111194. Object.defineProperty(exports, "__esModule", { value: true });
  111195. /**
  111196. * Force-apply material configuration right after a material was loaded.
  111197. */
  111198. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  111199. function ApplyMaterialConfigPlugin() {
  111200. }
  111201. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  111202. this._model = model;
  111203. };
  111204. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  111205. this._model && this._model._applyModelMaterialConfiguration(material);
  111206. };
  111207. return ApplyMaterialConfigPlugin;
  111208. }());
  111209. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  111210. /***/ }),
  111211. /* 55 */
  111212. /***/ (function(module, exports, __webpack_require__) {
  111213. "use strict";
  111214. Object.defineProperty(exports, "__esModule", { value: true });
  111215. var babylonjs_1 = __webpack_require__(0);
  111216. /**
  111217. * A (PBR) material will be extended using this function.
  111218. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  111219. */
  111220. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  111221. function ExtendedMaterialLoaderPlugin() {
  111222. }
  111223. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  111224. var material = baseMaterial;
  111225. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  111226. };
  111227. return ExtendedMaterialLoaderPlugin;
  111228. }());
  111229. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  111230. /***/ }),
  111231. /* 56 */
  111232. /***/ (function(module, exports, __webpack_require__) {
  111233. /*!
  111234. * PEP v0.4.3 | https://github.com/jquery/PEP
  111235. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  111236. */
  111237. !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);
  111238. // define inherited MouseEvent properties
  111239. // skip bubbles and cancelable since they're set above in initEvent()
  111240. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  111241. // Spec requires that pointers without pressure specified use 0.5 for down
  111242. // state and 0 for up state.
  111243. var f=0;
  111244. // add x/y properties aliased to clientX/Y
  111245. // define the properties of the PointerEvent interface
  111246. 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(){
  111247. // only activate if this platform does not have pointer events
  111248. 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}})}/**
  111249. * This is the constructor for new PointerEvents.
  111250. *
  111251. * New Pointer Events must be given a type, and an optional dictionary of
  111252. * initialization properties.
  111253. *
  111254. * Due to certain platform requirements, events returned from the constructor
  111255. * identify as MouseEvents.
  111256. *
  111257. * @constructor
  111258. * @param {String} inType The type of the event to create.
  111259. * @param {Object} [inDict] An optional dictionary of initial event properties.
  111260. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  111261. */
  111262. 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},
  111263. // return value, key, map
  111264. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  111265. // MouseEvent
  111266. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  111267. // DOM Level 3
  111268. "buttons",
  111269. // PointerEvent
  111270. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  111271. // event instance
  111272. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  111273. // MouseEvent
  111274. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  111275. // DOM Level 3
  111276. 0,
  111277. // PointerEvent
  111278. 0,0,0,0,0,0,"",0,!1,
  111279. // event instance
  111280. "",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),
  111281. // Scope objects for native events.
  111282. // This exists for ease of testing.
  111283. eventSources:Object.create(null),eventSourceList:[],/**
  111284. * Add a new event source that will generate pointer events.
  111285. *
  111286. * `inSource` must contain an array of event names named `events`, and
  111287. * functions with the names specified in the `events` array.
  111288. * @param {string} name A name for the event source
  111289. * @param {Object} source A new source of platform events.
  111290. */
  111291. 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++)
  111292. // call eventsource register
  111293. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  111294. // call eventsource register
  111295. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  111296. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  111297. return!1}},
  111298. // EVENTS
  111299. 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)},
  111300. // LISTENER LOGIC
  111301. eventHandler:function(a){
  111302. // This is used to prevent multiple dispatch of pointerevents from
  111303. // platform events. This can happen when two elements in different scopes
  111304. // are set up to create pointer events, which is relevant to Shadow DOM.
  111305. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  111306. // set up event listeners
  111307. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  111308. // remove event listeners
  111309. 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)},
  111310. // EVENT CREATION AND TRACKING
  111311. /**
  111312. * Creates a new Event of type `inType`, based on the information in
  111313. * `inEvent`.
  111314. *
  111315. * @param {string} inType A string representing the type of event to create
  111316. * @param {Event} inEvent A platform event with a target
  111317. * @return {Event} A PointerEvent of type `inType`
  111318. */
  111319. makeEvent:function(b,c){
  111320. // relatedTarget must be null if pointer is captured
  111321. 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},
  111322. // make and dispatch an event in one call
  111323. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  111324. * Returns a snapshot of inEvent, with writable properties.
  111325. *
  111326. * @param {Event} inEvent An event that contains properties to copy.
  111327. * @return {Object} An object containing shallow copies of `inEvent`'s
  111328. * properties.
  111329. */
  111330. 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],
  111331. // Work around SVGInstanceElement shadow tree
  111332. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  111333. // This is the behavior implemented by Firefox.
  111334. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  111335. // keep the semantics of preventDefault
  111336. 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){
  111337. // Order of conditions due to document.contains() missing in IE.
  111338. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  111339. // Touch: Do not propagate if node is detached.
  111340. 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)}},/**
  111341. * Dispatches the event to its target.
  111342. *
  111343. * @param {Event} inEvent The event to be dispatched.
  111344. * @return {Boolean} True if an event handler returns true, false otherwise.
  111345. */
  111346. 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(
  111347. // is element a shadow host?
  111348. e=this.targetingShadow(f);e;){if(
  111349. // find the the element inside the shadow root
  111350. d=e.elementFromPoint(b,c)){
  111351. // shadowed element may contain a shadow root
  111352. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  111353. // check for older shadows
  111354. e=this.olderShadow(e)}
  111355. // light dom element is the target
  111356. return f}},owner:function(a){
  111357. // walk up until you hit the shadow root or document
  111358. for(var b=a;b.parentNode;)b=b.parentNode;
  111359. // the owner element is expected to be a Document or ShadowRoot
  111360. 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);
  111361. // if x, y is not in this root, fall back to document search
  111362. 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){
  111363. // Only watch scopes that can target find, as these are top-level.
  111364. // Otherwise we can see duplicate additions and removals that add noise.
  111365. //
  111366. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  111367. // a removal without an insertion when a node is redistributed among
  111368. // shadows. Since it all ends up correct in the document, watching only
  111369. // the document will yield the correct mutations to watch.
  111370. 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))},
  111371. // register all touch-action = none nodes on document load
  111372. 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){
  111373. // find children with touch-action
  111374. var b=x(a,this.findElements,this);
  111375. // flatten the list
  111376. // make sure the added nodes are accounted for
  111377. 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){}
  111378. // handler block for native mouse events
  111379. 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:[],
  111380. // collide with the global mouse listener
  111381. 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++){
  111382. // simulated mouse events will be swallowed near a primary touchend
  111383. 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);
  111384. // Update buttons state after possible out-of-document mouseup.
  111385. 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];
  111386. // Produces wrong state of buttons in Browsers without `buttons` support
  111387. // when a mouse button that was pressed outside the document is released
  111388. // inside and other buttons are still pressed down.
  111389. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  111390. // Support: Firefox <=44 only
  111391. // FF Ubuntu includes the lifted button in the `buttons` property on
  111392. // mouseup.
  111393. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  111394. 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),
  111395. // set touch-action on shadows as well
  111396. 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),
  111397. // remove touch-action from shadow
  111398. 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);
  111399. // simply update scrollType if listeners are already established
  111400. 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){
  111401. // set primary touch if there no pointers, or the only pointer is the mouse
  111402. (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,
  111403. // forward modifier keys
  111404. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  111405. // forward touch preventDefaults
  111406. 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))},
  111407. // For single axis scrollers, determines whether the element should emit
  111408. // pointer events or behave as a scroller
  111409. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  111410. // this element is a touch-action: none, should never scroll
  111411. b=!1;else if("XY"===c)
  111412. // this element should always scroll
  111413. 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]);
  111414. // if delta in the scroll axis > delta other axis, scroll instead of
  111415. // making events
  111416. 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},
  111417. // In some instances, a touchstart can happen without a touchend. This
  111418. // leaves the pointermap in a broken state.
  111419. // Therefore, on every touchstart, we remove the touches that did not fire a
  111420. // touchend event.
  111421. // To keep state globally consistent, we fire a
  111422. // pointercancel for this "abandoned" touch
  111423. vacuumTouches:function(a){var b=a.touches;
  111424. // pointermap.size should be < tl.length here, as the touchstart has not
  111425. // been processed yet.
  111426. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  111427. // Never remove pointerId == 1, which is mouse.
  111428. // Touch identifiers are 2 smaller than their pointerId, which is the
  111429. // index in pointermap.
  111430. 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);
  111431. // a finger drifted off the screen, ignore it
  111432. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  111433. // recover from retargeting by shadow
  111434. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  111435. // clean up case when finger leaves the screen
  111436. 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)},
  111437. // prevent synth mouse events from creating pointer events
  111438. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  111439. // only the primary finger will synth mouse events
  111440. if(this.isPrimaryTouch(c)){
  111441. // remember x/y of last touch
  111442. 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});
  111443. /***/ }),
  111444. /* 57 */
  111445. /***/ (function(module, exports, __webpack_require__) {
  111446. "use strict";
  111447. Object.defineProperty(exports, "__esModule", { value: true });
  111448. var defaultViewer_1 = __webpack_require__(9);
  111449. var mappers_1 = __webpack_require__(3);
  111450. var _1 = __webpack_require__(6);
  111451. /**
  111452. * Will attach an init function the the DOMContentLoaded event.
  111453. * The init function will be removed automatically after the event was triggered.
  111454. */
  111455. function initListeners() {
  111456. document.addEventListener("DOMContentLoaded", init);
  111457. function init(event) {
  111458. document.removeEventListener("DOMContentLoaded", init);
  111459. if (_1.viewerGlobals.disableInit || _1.disableInit)
  111460. return;
  111461. InitTags();
  111462. }
  111463. }
  111464. exports.initListeners = initListeners;
  111465. /**
  111466. * Select all HTML tags on the page that match the selector and initialize a viewer
  111467. *
  111468. * @param selector the selector to initialize the viewer on (default is 'babylon')
  111469. */
  111470. function InitTags(selector) {
  111471. if (selector === void 0) { selector = 'babylon'; }
  111472. var elements = document.querySelectorAll(selector);
  111473. for (var i = 0; i < elements.length; ++i) {
  111474. var element = elements.item(i);
  111475. // get the html configuration
  111476. var configMapper = mappers_1.mapperManager.getMapper('dom');
  111477. var config = configMapper.map(element);
  111478. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  111479. }
  111480. }
  111481. exports.InitTags = InitTags;
  111482. /***/ })
  111483. /******/ ]);
  111484. return BabylonViewer;
  111485. });